Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat(desktop): add a persistent file system and eleven native OS apps (Files, Notepad, Photos, Calculator, Clock, Weather, Camera, Paint, Terminal, Task Manager, Media Player)
nirholasa25eb364a259
diff --git a/docs/desktop.md b/docs/desktop.mdindex fd8e5fbc6..07f515028 100644--- a/docs/desktop.md+++ b/docs/desktop.md@@ -117,9 +117,10 @@ storage: migration `20261015000000_world_gems.sql`.and blur presets, the CTRL token names, light and dark. Dark is the default.Light follows the site-wide `twx_theme` switch, so the desktop and everyframed page flip together. Tokens: `src/desktop/theme.css`.-- **Shell.** Taskbar with pinned and running apps, Start menu (search, pinned,- recommended, all apps), widgets panel with a resident `<agent-3d>`, calendar,- desktop icons, right-click menu, toasts. `src/desktop/shell.js`.+- **Shell.** Floating taskbar with pinned and running apps, Start menu, system+ tray, notification centre and calendar, lock screen, power menu, Run and About+ dialogs, desktop icons and files, right-click menus. `src/desktop/shell.js`+ and `src/desktop/chrome/` (see "The shell" below).- **Windows.** Drag, eight-handle resize, snap to left, right or top edge,minimize, maximize, Alt+Tab, Alt+W. On a phone every window is full screen.`src/desktop/wm.js`; geometry in `src/desktop/layout.js` (unit tested).@@ -135,11 +136,34 @@ storage: migration `20261015000000_world_gems.sql`.- **Motion.** Minimize flies the window into its taskbar button and restore flies it back; snapping, maximizing and restoring morph between the two frames. Every motion is skipped when the system asks for reduced motion.- **Peek.** Hover a running app in the taskbar for its window card (title, page, state, close). Hover the card and every other window fades out so the one you are pointing at shows through. The taskbar marks running apps with a short pill and the window in front with a long accent pill; pinned apps that are not running show none.- **Rubber band.** Drag on the empty desktop to draw a selection box; Ctrl or Shift adds to the current selection.-- **Right-click.** The desktop menu sets icon size, sorts by name, auto-arranges, refreshes, and opens All Apps and Personalize. Icon menus open or remove the selection.+- **Right-click.** The desktop menu has View (icon size, auto arrange, select all), Sort by, Refresh, New (Folder, Text document), Edit widgets, Add a widget, Open in Terminal, Open Desktop folder, Run, Display settings, Personalize and About. App icons open or remove the selection; file icons add Open with Files, Rename (F2), Delete and, for pictures, Set as desktop background; the Recycle Bin adds Empty Recycle Bin.+- **Files on the desktop.** The desktop is the `/Desktop` folder of the OS file system, so anything saved there (from Notepad, Paint, Camera, the Terminal or File Explorer) appears as an icon at once, and New, Rename and Delete on the desktop write through to it. Drop files from your computer onto the desktop to import them. Delete moves to the Recycle Bin. This PC and Recycle Bin sit on the desktop like any other icon.- **All Apps.** A native app listing every app and page from the site navigation, with Open and Add to desktop for each.-- **Settings.** Profile (name, avatar colour), Arrival (start in the campus or on the desktop, startup chime, a Walk the campus button), Personalization (style, dark, light or match system, seven accents, six wallpapers or your own photo; the default `three.ws` wallpaper is the classic site's violet glow over a hairline grid), Desktop and taskbar (icon size, taskbar alignment, 24-hour clock), and Session and storage.+- **Settings.** Profile (name, avatar colour), Arrival (start in the campus or on the desktop, startup chime, a Walk the campus button), Personalization (style, dark, light or match system, seven accents, seven wallpapers or your own photo; the default `bubbles` wallpaper floats glass spheres over a violet field in dark and pastel in light, and `three.ws` is the classic site's violet glow over a hairline grid), Desktop and taskbar (icon size, taskbar alignment, 24-hour clock), and Session and storage.- **Session.** Open windows and their geometry, icon layout, preferences, recent apps and the custom wallpaper are saved in this browser (`tws:desktop`, `tws:icons`, `tws:prefs`, `tws:recent` in localStorage; the wallpaper image in IndexedDB database `tws-desktop`) and restored on reload. Settings can export the session to a JSON file, import one (only known `tws:` keys are accepted, files over 2 MB are refused), close all windows, or reset everything. Nothing is sent to a server.+## The shell++`src/desktop/chrome/` holds the parts of the shell that make it feel like an operating system rather than a page. Pure rules live in `chrome/logic.js` (clock formatting, battery and network readouts, the notification log, Run parsing; unit tested in `tests/desktop-chrome.test.js`); the UI is `chrome/index.js` and `chrome/chrome.css`.++- **Taskbar.** In Fluent the taskbar is a floating island centred above the bottom edge (or anchored left with the taskbar alignment setting): Start, Widgets and Assistant on the left, pinned and running apps in the middle, the tray on the right. On a phone it is a compact full-width bar.+- **Start.** Your avatar overlaps the top edge above a search field. Below, an A to Z list of every app and page on the left and, on the right, the time and date, a Pinned grid (with All to expand), and Recommended (recent files from the file system and recent apps). Search covers apps, pages and files and folders. The footer opens Documents, Pictures, Music, Downloads and Settings, and holds Walk the campus, classic view and the power menu.+- **Tray.** One status pill shows network (from the Network Information API), volume and battery (from the Battery Status API; hidden when the browser has none). Click it for quick settings: dark mode, night light, do not disturb, energy saver, system sounds, full screen, brightness and volume sliders, connection and battery details, and your account with Settings and power.+- **Notifications and calendar.** The clock opens the notification centre over a month calendar. Apps post with `notify({ title, body, app })` (passed to every native app); each notification shows as a toast, lands in the centre, and opens its app when clicked. Do not disturb holds the toasts but keeps the log. The log is saved in `tws:notifications`.+- **Lock and power.** Ctrl+Alt+L (or Lock in the power menu) shows the lock screen: large time and date over the wallpaper, network and battery in the corner; any key or click reveals the sign-in card. The power menu offers Lock, Sign in or Sign out, Restart (saves the session, closes every window and reloads) and Shut down (saves, closes every window and leaves a dark screen with a power button).+- **Run and About.** Ctrl+Alt+R opens Run: type an app, a page, a folder path or a URL. About shows the version, browser, platform, processor cores, memory, display, storage used, network, battery and account, read from the browser's own APIs. Run keeps a history of what you typed in `tws:run`.+- **Keyboard.** Ctrl+Esc opens Start. With Ctrl+Alt: R Run, L lock, D show desktop, A quick settings, N notifications, T Terminal, E File Explorer, I Settings, M Task Manager, W widgets, C assistant.+- **Widgets and assistant.** The Widgets button opens the widgets board and the Assistant button opens the chat panel; widgets pinned to the desktop sit below every window. Both live in `src/desktop/widgets/` and `src/desktop/assistant/`.++## The OS layer: file system and native apps++`src/desktop/os/` ([README](../src/desktop/os/README.md)) gives the desktop the apps a real computer ships with. Everything is real: no mock data, no seeded sample files.++- **File system.** `os/fs.js` is a virtual file system in IndexedDB (`tws-os`, store `fs`) with Desktop, Documents, Pictures, Downloads, Music, Videos and a Recycle Bin. Files hold Blobs; delete moves to the Recycle Bin and remembers the origin; move, copy, rename, restore and permanent delete are atomic transactions. Nothing leaves the browser.+- **Apps** (lazy loaded from `os/registry.js`): File Explorer, Notepad, Photos, Calculator (standard, scientific, programmer, converter), Clock (world clocks, alarms, timers, stopwatch), Weather (Open-Meteo, any city), Camera (`getUserMedia`, photos and video saved to the file system), Paint, Terminal (a real shell over the file system plus `three price`, `three agents`, `curl`, `weather`), Task Manager (live frame rate, heap, main-thread load, network and battery from real browser APIs; unsupported metrics say so) and Media Player (audio visualizer, video, Picture-in-Picture).+- **Opening files.** `ctx.openPath(path)` routes by type: folders to File Explorer, text to Notepad, pictures to Photos, audio and video to the Media Player.+- **Adding an OS app.** Add an entry to `os/registry.js`, a module in `os/apps/<id>.js` exporting `mount(host, ctx)`, and a `<id>.css` scoped under `.napp-<id>`.+## URLs and preferences| What | How |diff --git a/scripts/desktop-os-smoke.mjs b/scripts/desktop-os-smoke.mjsnew file mode 100644index 000000000..538f2e339--- /dev/null+++ b/scripts/desktop-os-smoke.mjs@@ -0,0 +1,28 @@+// Launches every native OS app in the real desktop shell and reports console errors.+// Usage: node scripts/desktop-os-smoke.mjs [baseUrl] [outDir]+import { chromium } from '@playwright/test';++const base = process.argv[2] || 'http://localhost:3000';+const out = process.argv[3] || '';+const apps = ['files', 'notepad', 'photos', 'calculator', 'clock', 'weather', 'camera', 'paint', 'terminal', 'taskmgr', 'media'];+const browser = await chromium.launch({ args: ['--use-fake-ui-for-media-stream', '--use-fake-device-for-media-stream'] });+let failed = 0;+for (const id of apps) {+ const ctx = await browser.newContext({ viewport: { width: 1440, height: 900 }, permissions: ['camera', 'microphone', 'geolocation'], geolocation: { latitude: 40.7, longitude: -74 } });+ const page = await ctx.newPage();+ const errors = [];+ page.on('console', (m) => m.type() === 'error' && !/503|Failed to load resource/.test(m.text()) && errors.push(m.text()));+ page.on('pageerror', (e) => errors.push(String(e)));+ await page.goto(`${base}/?view=desktop&boot=0&world=0&app=${id}`, { waitUntil: 'domcontentloaded' });+ const win = page.locator(`.win[data-app="${id}"]`);+ await win.waitFor({ timeout: 15000 }).catch(() => errors.push('window did not open'));+ await page.waitForTimeout(2500);+ const broken = await page.locator(`.win[data-app="${id}"] .napp-error`).count();+ if (broken) errors.push(await page.locator('.napp-error').first().innerText());+ if (out) await page.screenshot({ path: `${out}/${id}.png` });+ console.log(`${errors.length ? 'FAIL' : 'ok '} ${id}${errors.length ? `: ${errors.join(' | ').slice(0, 300)}` : ''}`);+ failed += errors.length ? 1 : 0;+ await ctx.close();+}+await browser.close();+process.exit(failed ? 1 : 0);diff --git a/src/desktop/README.md b/src/desktop/README.mdindex cf59e2372..c38f59305 100644--- a/src/desktop/README.md+++ b/src/desktop/README.md@@ -8,10 +8,13 @@ The web desktop served at `/` (page: `pages/desktop.html`). See| `main.js` | Entry: runs the boot checks, shows the lock screen, then walks the visitor in as an avatar or lands them on the desktop; deep links || `boot-logic.js` | Pure boot rules: concurrent boot steps with timings, entry mode (`?world=1`, `?world=0`, `?view=desktop`, deep links, WebGL, the Arrival preference), greeting, summary, GPU name (unit tested) || `boot.js`, `boot.css` | The boot screen (live log of real checks) and the lock screen (greeting, $THREE, gems and account chips, Walk in / Desktop), plus the synthesised startup chime |-| `shell.js` | Taskbar (peek cards, Aqua dock magnification and menu bar), Start, widgets, calendar, menus, native apps, the World button and the Arrival settings |+| `shell.js` | Taskbar (peek cards, Aqua dock magnification and menu bar), Start, desktop files and menus, widgets and assistant wiring, native apps, the World button and the Arrival settings |+| `chrome/` | OS chrome: tray status pill, quick settings, notification centre and calendar, toasts, lock screen, power menu, Run and About dialogs, the bubbles wallpaper and the Fluent island taskbar; pure rules in `chrome/logic.js` (unit tested) |+| `icon-layer.js` | Desktop icon grid: selection, rubber band, drag, keyboard, per-item menus, rename and delete hooks || `wm.js` | Window manager (drag, resize, edge and corner snap, Snap layouts flyout, Snap assist, minimize flight and morph motion, focus, persistence hooks) || `layout.js` | Pure geometry (snap zones, Snap layouts, dock magnification curve), shell styles and their bar sizes, search ranking, state and preference validation (unit tested) || `apps.js` | App registry and wallpapers |+| `os/` | The OS layer: virtual file system (`fs.js`), app registry, app host and the native apps in `os/apps/` (see [os/README.md](os/README.md)) || `icons.js` | Stroke glyphs || `theme.css`, `desktop.css`, `styles.css` | CTRL tokens; shell and window styles; Snap layouts, Snap assist, peek and the Fluent, Aqua and Classic skins || `world/index.js` | The campus controller: mounts the 3D world over the desktop, input, proximity prompts, sit-down and walk-in transitions, the phone, the VR headset, mining, the frame loop |diff --git a/src/desktop/apps.js b/src/desktop/apps.jsindex 429403270..2527f2cdd 100644--- a/src/desktop/apps.js+++ b/src/desktop/apps.js@@ -214,13 +214,16 @@ export const NATIVE_APPS = [},];-export const ALL_APPS = [...APPS, ...NATIVE_APPS];+import { OS_APPS } from './os/registry.js';++export const ALL_APPS = [...APPS, ...NATIVE_APPS, ...OS_APPS];export function appById(id) {return ALL_APPS.find((a) => a.id === id) || null;}export const WALLPAPERS = [+ { id: 'bubbles', label: 'Bubbles' },{ id: 'three', label: 'three.ws' },{ id: 'aurora', label: 'Aurora' },{ id: 'midnight', label: 'Midnight' },diff --git a/src/desktop/icons.js b/src/desktop/icons.jsindex f925b3aea..b3cf6d2ff 100644--- a/src/desktop/icons.js+++ b/src/desktop/icons.js@@ -38,8 +38,55 @@ const P = {phone: '<rect x="7" y="3" width="10" height="18" rx="2"/><path d="M11 17.5h2"/>',rocket: '<path d="M12 3c3 2.5 4.5 6 4.5 10L12 16l-4.5-3C7.5 9 9 5.5 12 3z"/><path d="M7.5 13 5 17l3.5-.5M16.5 13 19 17l-3.5-.5M12 16v5"/><circle cx="12" cy="9.5" r="1.5"/>',close: '<path d="m6 6 12 12M18 6 6 18"/>',+ files: '<path d="M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"/><path d="M3 11h18"/>',+ note: '<path d="M6 3h9l4 4v14H6z"/><path d="M14 3v5h5M9 12h7M9 16h7"/>',+ calc: '<rect x="5" y="3" width="14" height="18" rx="2"/><path d="M8 7h8M8.5 11h1M12 11h1M15.5 11h.5M8.5 14.5h1M12 14.5h1M15.5 14.5h.5M8.5 18h1M12 18h1M15.5 18h.5"/>',+ taskmgr: '<rect x="3" y="4" width="18" height="16" rx="2"/><path d="M6 15l3-4 3 2 3-5 3 3"/>',+ paint: '<path d="M12 3a9 9 0 1 0 0 18c1.4 0 2-1 2-2s-.6-1.6-.6-2.5S14.3 15 15.5 15H17a4 4 0 0 0 4-4c0-4.4-4-8-9-8z"/><circle cx="7.5" cy="11" r="1"/><circle cx="10" cy="7" r="1"/><circle cx="15" cy="7.5" r="1"/>',+ clock: '<circle cx="12" cy="12" r="9"/><path d="M12 7v5l3.5 2"/>',+ cloud: '<path d="M7 18a4.5 4.5 0 0 1-.6-8.96A6 6 0 0 1 18 10.5a3.8 3.8 0 0 1-.5 7.5z"/>',+ music: '<path d="M9 18V6l11-2v12"/><circle cx="6.5" cy="18" r="2.5"/><circle cx="17.5" cy="16" r="2.5"/>',+ video: '<rect x="3" y="5" width="13" height="14" rx="2"/><path d="m16 10 5-3v10l-5-3"/>',+ trash: '<path d="M4 7h16M10 7V4h4v3M6 7l1 13h10l1-13M10 11v6M14 11v6"/>',+ pc: '<rect x="3" y="4" width="18" height="12" rx="2"/><path d="M8 20h8M12 16v4"/>',+ lock: '<rect x="5" y="11" width="14" height="9" rx="2"/><path d="M8 11V8a4 4 0 0 1 8 0v3"/>',+ wifi: '<path d="M2.5 9a14 14 0 0 1 19 0M5.5 12.5a9.5 9.5 0 0 1 13 0M8.8 16a5 5 0 0 1 6.4 0"/><circle cx="12" cy="19" r=".8"/>',+ battery: '<rect x="2.5" y="8" width="16" height="9" rx="2"/><path d="M21 11v3M5.5 11v3M8.5 11v3"/>',+ bell: '<path d="M6 17V11a6 6 0 0 1 12 0v6l1.5 2h-15zM10 21h4"/>',+ volume: '<path d="M4 9h3.5L12 5v14l-4.5-4H4zM15.5 9a4 4 0 0 1 0 6M18 6.5a8 8 0 0 1 0 11"/>',+ bluetooth: '<path d="m7 7 10 10-5 4V3l5 4L7 17"/>',+ plane: '<path d="M21 15.5 13.5 11V5a1.5 1.5 0 0 0-3 0v6L3 15.5V18l7.5-2v3L9 20.5V22l3-1 3 1v-1.5L13.5 19v-3l7.5 2z"/>',+ focus: '<circle cx="12" cy="12" r="8"/><circle cx="12" cy="12" r="3"/>',+ fullscreen: '<path d="M4 9V4h5M20 9V4h-5M4 15v5h5M20 15v5h-5"/>',+ eye: '<path d="M2 12s3.6-6.5 10-6.5S22 12 22 12s-3.6 6.5-10 6.5S2 12 2 12z"/><circle cx="12" cy="12" r="3"/>',+ plus: '<path d="M12 5v14M5 12h14"/>',+ check: '<path d="m5 12.5 4.5 4.5L19 7.5"/>',+ edit: '<path d="M4 20h4L19 9l-4-4L4 16zM13.5 6.5l4 4"/>',+ download: '<path d="M12 4v11M7 11l5 5 5-5M5 20h14"/>',+ upload: '<path d="M12 16V5M7 9l5-5 5 5M5 20h14"/>',+ save: '<path d="M5 4h11l3 3v13H5z"/><path d="M8 4v5h7V4M8 20v-6h8v6"/>',+ sleep: '<path d="M20 14.5A8 8 0 1 1 9.5 4 6.5 6.5 0 0 0 20 14.5z"/><path d="M15 4h4l-4 4h4"/>',+ restart: '<path d="M20 11a8 8 0 1 0-2.3 5.7M20 4v7h-7"/>',+ pin: '<path d="m15 4 5 5-3 1-3 3 .5 4-2 2-3.5-3.5L4 20l5-5.5L5.5 11l2-2 4 .5 3-3z"/>',+ star: '<path d="m12 3.5 2.6 5.4 5.9.8-4.3 4.1 1 5.9L12 16.9 6.8 19.7l1-5.9L3.5 9.7l5.9-.8z"/>',+ home: '<path d="M4 11 12 4l8 7v9h-5v-6H9v6H4z"/>',+ arrowLeft: '<path d="M19 12H5M11 6l-6 6 6 6"/>',+ arrowUp: '<path d="M12 19V5M6 11l6-6 6 6"/>',+ list: '<path d="M8 6h12M8 12h12M8 18h12M4 6h.01M4 12h.01M4 18h.01"/>',+ more: '<path d="M5 12h.01M12 12h.01M19 12h.01"/>',+ pause: '<path d="M8 5v14M16 5v14"/>',+ next: '<path d="M6 5v14l9-7zM18 5v14"/>',+ prev: '<path d="M18 5v14l-9-7zM6 5v14"/>',+ mic: '<rect x="9" y="3" width="6" height="11" rx="3"/><path d="M5 11a7 7 0 0 0 14 0M12 18v3"/>',+ shield: '<path d="M12 3 4.5 6v6c0 4.4 3 7.5 7.5 9 4.5-1.5 7.5-4.6 7.5-9V6z"/>',+ cpu: '<rect x="6" y="6" width="12" height="12" rx="2"/><path d="M9 2v4M15 2v4M9 18v4M15 18v4M2 9h4M2 15h4M18 9h4M18 15h4"/>',};+/** Apps ship their own glyphs: registerGlyph('name', '<path d="..."/>') on a 24px stroke grid. */+export function registerGlyph(name, body) {+ if (!P[name]) P[name] = body;+}+export function icon(name, size = 20) {const body = P[name] || P.logo;return (diff --git a/src/desktop/os/README.md b/src/desktop/os/README.mdnew file mode 100644index 000000000..9ed4eefc8--- /dev/null+++ b/src/desktop/os/README.md@@ -0,0 +1,38 @@+# src/desktop/os++The native operating-system layer of the three.ws desktop: a virtual file+system and the apps a real computer ships with. Everything here is real+(IndexedDB storage, `getUserMedia`, Open-Meteo, three.ws APIs); there is no+mock data.++## App contract++`registry.js` declares each app (title, size, glyph, keywords) and lazily+imports `apps/<id>.js`, which exports:++```js+export function mount(host, ctx) { /* build UI inside host */ return cleanupFn; /* optional */ }+```++`host` is an empty element that fills the window body (use class `napp` on+your root; the window already has its own title bar). `ctx`:++| Member | Meaning |+| --- | --- |+| `h(tag, cls, html)`, `esc(s)`, `icon(name, size)`, `tile(app, size, glyph)` | DOM and glyph helpers |+| `registerGlyph(name, pathBody)` | add a 24px stroke glyph (also exported by `../icons.js`) |+| `toast(msg)`, `notify({ title, body, app })` | transient toast; notification centre entry |+| `fs` | the virtual file system (`./fs.js`) |+| `arg` | launch argument (`launchId(id, { arg })`), for example a path to open |+| `onArg(fn)` | called when the app is already open and is launched again with a new `arg` |+| `setTitle(text)` | live window title, e.g. the open file name |+| `onClose(fn)` | run on window close (stop streams, timers, listeners) |+| `launchId(id, { arg })`, `openPath(path)` | open an app, or a file in the app that handles its type |+| `prefs`, `onPrefs(fn)`, `store.get/set/del` | desktop preferences and namespaced localStorage |+| `windows()`, `closeWindow(id)`, `focusWindow(id)` | the running windows (Task Manager) |+| `fetchJson(url, init)` | same-origin credentialed JSON fetch that throws on non-2xx |++Styling: each app ships `apps/<id>.css`, imported from its module, with all+selectors scoped under `.napp-<id>`. Use the desktop tokens (`--card`,+`--hover`, `--bd`, `--text`, `--text2`, `--accent`, `--bg`) so light mode,+accent colour and the Fluent, Aqua and Classic styles all work.diff --git a/src/desktop/os/apps/alarm-logic.js b/src/desktop/os/apps/alarm-logic.jsnew file mode 100644index 000000000..bdba83b13--- /dev/null+++ b/src/desktop/os/apps/alarm-logic.js@@ -0,0 +1,219 @@+// Alarm, timer and stopwatch logic plus a tiny module-level scheduler.+//+// The scheduler runs while the page is open, not after it closes: Clock registers its listeners+// once on mount and the interval keeps ticking after the Clock window is closed, so a timer or+// alarm still rings if you close the app. Nothing here can wake a closed tab.++export const DAYS = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];++/** Next Date an alarm {h, m, days[]} fires strictly after `from`. days empty means one-shot. Null if disabled. */+export function nextAlarmTime(alarm, from = new Date()) {+ if (!alarm.on) return null;+ const days = alarm.days || [];+ for (let add = 0; add < 8; add++) {+ const d = new Date(from.getFullYear(), from.getMonth(), from.getDate() + add, alarm.h, alarm.m, 0, 0);+ if (d.getTime() <= from.getTime()) continue;+ if (!days.length || days.includes(d.getDay())) return d;+ }+ return null;+}++/** Human summary of repeat days. */+export function repeatLabel(days = []) {+ if (!days.length) return 'Once';+ if (days.length === 7) return 'Every day';+ const s = [...days].sort();+ if (s.join() === '1,2,3,4,5') return 'Weekdays';+ if (s.join() === '0,6') return 'Weekends';+ return s.map((d) => DAYS[d]).join(', ');+}++/** Time until `target` as "in 3 h 20 min". */+export function untilLabel(target, now = new Date()) {+ const ms = target - now;+ if (ms <= 0) return 'now';+ const m = Math.ceil(ms / 60000);+ const d = Math.floor(m / 1440);+ const h = Math.floor((m % 1440) / 60);+ const mm = m % 60;+ const parts = [];+ if (d) parts.push(`${d} d`);+ if (h) parts.push(`${h} h`);+ if (mm || !parts.length) parts.push(`${mm} min`);+ return `in ${parts.join(' ')}`;+}++/** mm:ss or h:mm:ss; `cs` adds centiseconds for the stopwatch. */+export function formatDuration(ms, cs = false) {+ const neg = ms < 0;+ let t = Math.abs(Math.floor(ms));+ const c = Math.floor((t % 1000) / 10);+ t = Math.floor(t / 1000);+ const s = t % 60;+ const m = Math.floor(t / 60) % 60;+ const h = Math.floor(t / 3600);+ const p = (n) => String(n).padStart(2, '0');+ const base = h ? `${h}:${p(m)}:${p(s)}` : `${p(m)}:${p(s)}`;+ return (neg ? '-' : '') + base + (cs ? `.${p(c)}` : '');+}++/** Parse "90", "1:30", "1:02:03" or "5m 30s" to milliseconds, or null. */+export function parseDuration(text) {+ const t = String(text).trim().toLowerCase();+ if (!t) return null;+ if (/^\d+(:\d{1,2}){1,2}$/.test(t)) {+ const p = t.split(':').map(Number);+ const sec = p.length === 3 ? p[0] * 3600 + p[1] * 60 + p[2] : p[0] * 60 + p[1];+ return sec * 1000;+ }+ if (/^\d+$/.test(t)) return Number(t) * 1000;+ const re = /(\d+(?:\.\d+)?)\s*(h|m|s)/g;+ let total = 0;+ let hit = false;+ for (let m = re.exec(t); m; m = re.exec(t)) {+ hit = true;+ total += Number(m[1]) * { h: 3600, m: 60, s: 1 }[m[2]] * 1000;+ }+ return hit ? Math.round(total) : null;+}++/** Stopwatch state helpers (pure): { running, startedAt, elapsed, laps[] }. */+export const stopwatch = {+ fresh: () => ({ running: false, startedAt: 0, elapsed: 0, laps: [] }),+ now: (s, t = Date.now()) => s.elapsed + (s.running ? t - s.startedAt : 0),+ start: (s, t = Date.now()) => (s.running ? s : { ...s, running: true, startedAt: t }),+ pause: (s, t = Date.now()) => (s.running ? { ...s, running: false, elapsed: s.elapsed + t - s.startedAt } : s),+ lap(s, t = Date.now()) {+ const total = stopwatch.now(s, t);+ const prev = s.laps.length ? s.laps[s.laps.length - 1].total : 0;+ return { ...s, laps: [...s.laps, { n: s.laps.length + 1, split: total - prev, total }] };+ },+};++/** Fastest and slowest lap numbers, only meaningful with 2+ laps. */+export function lapExtremes(laps) {+ if (laps.length < 2) return {};+ let min = laps[0];+ let max = laps[0];+ for (const l of laps) {+ if (l.split < min.split) min = l;+ if (l.split > max.split) max = l;+ }+ return { fastest: min.n, slowest: max.n };+}++/** Zone offset in minutes east of UTC for an IANA zone at `date`, via Intl. Throws RangeError for a bad zone. */+export function zoneOffsetMinutes(zone, date = new Date()) {+ const f = new Intl.DateTimeFormat('en-US', { timeZone: zone, hourCycle: 'h23', year: 'numeric', month: 'numeric', day: 'numeric', hour: 'numeric', minute: 'numeric', second: 'numeric' });+ const o = {};+ for (const p of f.formatToParts(date)) o[p.type] = p.value;+ const asUtc = Date.UTC(+o.year, +o.month - 1, +o.day, +o.hour % 24, +o.minute, +o.second);+ return Math.round((asUtc - Math.floor(date.getTime() / 1000) * 1000) / 60000);+}++export function isValidZone(zone) {+ try {+ new Intl.DateTimeFormat('en-US', { timeZone: zone });+ return true;+ } catch {+ return false;+ }+}++/** "UTC+5:30" label. */+export function offsetLabel(mins) {+ const sign = mins < 0 ? '-' : '+';+ const a = Math.abs(mins);+ const h = Math.floor(a / 60);+ const m = a % 60;+ return `UTC${sign}${h}${m ? `:${String(m).padStart(2, '0')}` : ''}`;+}++/** "Same time", "+3 h", "-5 h 30 min" relative to the local zone. */+export function relativeOffset(zoneMins, localMins) {+ const d = zoneMins - localMins;+ if (d === 0) return 'Same time';+ const a = Math.abs(d);+ const h = Math.floor(a / 60);+ const m = a % 60;+ return `${d > 0 ? '+' : '-'}${h ? `${h} h` : ''}${h && m ? ' ' : ''}${m ? `${m} min` : ''}`;+}++/** Day or night at a zone, using a plain 06:00 to 18:00 rule on the zone's local hour. */+export function isDaytime(zone, date = new Date()) {+ const hour = Number(new Intl.DateTimeFormat('en-US', { timeZone: zone, hourCycle: 'h23', hour: 'numeric' }).format(date));+ return hour >= 6 && hour < 18;+}++// ---- scheduler ----++let timerId = null;+const listeners = new Set();+let started = 0;++/**+ * Start (reference counted) the 1 s scheduler and subscribe `fn(nowMs)`. Returns an unsubscribe.+ * The interval survives window close; it stops only when the last subscriber leaves, and the+ * Clock keeps a permanent subscriber for armed alarms and timers (see registerRinger).+ */+export function subscribeTick(fn) {+ listeners.add(fn);+ if (!timerId) {+ timerId = setInterval(tick, 500);+ if (typeof document !== 'undefined') document.addEventListener('visibilitychange', tick);+ }+ started++;+ return () => {+ listeners.delete(fn);+ if (!listeners.size && timerId) {+ clearInterval(timerId);+ timerId = null;+ if (typeof document !== 'undefined') document.removeEventListener('visibilitychange', tick);+ }+ };+}++function tick() {+ const now = Date.now();+ for (const fn of [...listeners]) {+ try {+ fn(now);+ } catch (err) {+ console.error('[clock] tick listener failed', err);+ }+ }+}++export const schedulerStats = () => ({ running: !!timerId, listeners: listeners.size, started });++/**+ * Ringer: evaluates alarms and timers against the clock. Kept pure-ish so it can be tested:+ * `check(state, now, lastNow)` returns { fired: [...], state } where alarms that crossed their time+ * since `lastNow` (so a throttled background tab still fires on its next tick) are reported once.+ */+export function checkAlarms(alarms, now, lastNow) {+ const fired = [];+ const next = alarms.map((a) => {+ if (!a.on) return a;+ const t = nextAlarmTime(a, new Date(lastNow));+ if (t && t.getTime() <= now) {+ fired.push(a);+ return (a.days || []).length ? a : { ...a, on: false };+ }+ return a;+ });+ return { fired, alarms: next };+}++/** Timers: { id, label, total, endsAt|null, left, done }. Returns timers that finished at `now`. */+export function checkTimers(timers, now) {+ const fired = [];+ const next = timers.map((t) => {+ if (t.endsAt && !t.done && t.endsAt <= now) {+ fired.push(t);+ return { ...t, done: true, endsAt: null, left: 0 };+ }+ return t;+ });+ return { fired, timers: next };+}diff --git a/src/desktop/os/apps/calc-engine.js b/src/desktop/os/apps/calc-engine.jsnew file mode 100644index 000000000..4eaf1fcb5--- /dev/null+++ b/src/desktop/os/apps/calc-engine.js@@ -0,0 +1,313 @@+// Calculator engine. A tokenizer plus a shunting-yard evaluator: no eval, no Function.+// Pure functions only, so the Calculator app and the unit tests share one implementation.++const FUNCS = {+ sin: { n: 1, trig: 'in', f: Math.sin },+ cos: { n: 1, trig: 'in', f: Math.cos },+ tan: { n: 1, trig: 'in', f: Math.tan },+ asin: { n: 1, trig: 'out', f: Math.asin },+ acos: { n: 1, trig: 'out', f: Math.acos },+ atan: { n: 1, trig: 'out', f: Math.atan },+ sinh: { n: 1, f: Math.sinh },+ cosh: { n: 1, f: Math.cosh },+ tanh: { n: 1, f: Math.tanh },+ log: { n: 1, f: Math.log10 },+ ln: { n: 1, f: Math.log },+ log2: { n: 1, f: Math.log2 },+ sqrt: { n: 1, f: Math.sqrt },+ cbrt: { n: 1, f: Math.cbrt },+ abs: { n: 1, f: Math.abs },+ exp: { n: 1, f: Math.exp },+ floor: { n: 1, f: Math.floor },+ ceil: { n: 1, f: Math.ceil },+ round: { n: 1, f: Math.round },+ fact: { n: 1, f: (x) => factorial(x) },+ min: { n: 2, f: Math.min },+ max: { n: 2, f: Math.max },+ root: { n: 2, f: (x, y) => (x < 0 && y % 2 !== 0 ? -Math.pow(-x, 1 / y) : Math.pow(x, 1 / y)) },+ mod: { n: 2, f: (x, y) => x % y },+};+const CONSTS = { pi: Math.PI, e: Math.E, tau: Math.PI * 2, phi: (1 + Math.sqrt(5)) / 2 };+const OPS = {+ '+': { p: 2, r: false, f: (a, b) => a + b },+ '-': { p: 2, r: false, f: (a, b) => a - b },+ '*': { p: 3, r: false, f: (a, b) => a * b },+ '/': { p: 3, r: false, f: (a, b) => a / b },+ '%': { p: 3, r: false, f: (a, b) => a % b },+ '^': { p: 5, r: true, f: (a, b) => Math.pow(a, b) },+};+const UNARY_P = 4;++export function factorial(x) {+ if (!Number.isFinite(x) || x < 0 || !Number.isInteger(x)) throw new CalcError('Factorial needs a whole number of 0 or more');+ if (x > 170) return Infinity;+ let r = 1;+ for (let i = 2; i <= x; i++) r *= i;+ return r;+}++export class CalcError extends Error {}++/** Normalise display glyphs to ASCII operators. */+const GLYPHS = { '\u00d7': '*', '\u00f7': '/', '\u2212': '-', '\u03c0': 'pi', '\u221a': 'sqrt', '\u00b2': '^2', '\u00b3': '^3', '\u00b7': '*' };++export function tokenize(src) {+ const s = String(src).replace(/[\u00d7\u00f7\u2212\u03c0\u221a\u00b2\u00b3\u00b7]/g, (c) => (GLYPHS[c][0] === '^' ? GLYPHS[c] : ` ${GLYPHS[c]} `));+ const out = [];+ let i = 0;+ while (i < s.length) {+ const c = s[i];+ if (/\s/.test(c)) { i++; continue; }+ if (/[0-9.]/.test(c)) {+ const m = /^(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?/.exec(s.slice(i));+ if (!m) throw new CalcError('Invalid number');+ out.push({ t: 'num', v: parseFloat(m[0]) });+ i += m[0].length;+ continue;+ }+ if (/[a-zA-Z]/.test(c)) {+ const m = /^[a-zA-Z][a-zA-Z0-9]*/.exec(s.slice(i));+ const w = m[0].toLowerCase();+ if (FUNCS[w]) out.push({ t: 'fn', v: w });+ else if (w in CONSTS) out.push({ t: 'num', v: CONSTS[w] });+ else if (w === 'ans') out.push({ t: 'ans' });+ else throw new CalcError(`Unknown name "${m[0]}"`);+ i += m[0].length;+ continue;+ }+ if (c === '(' || c === ')') { out.push({ t: c }); i++; continue; }+ if (c === '!') { out.push({ t: 'post', v: '!' }); i++; continue; }+ if (c === ',') { out.push({ t: ',' }); i++; continue; }+ if (c === '*' && s[i + 1] === '*') { out.push({ t: 'op', v: '^' }); i += 2; continue; }+ if (OPS[c]) { out.push({ t: 'op', v: c }); i++; continue; }+ throw new CalcError(`Unexpected "${c}"`);+ }+ return out;+}++/**+ * Evaluate an expression string.+ * opts: { angle: 'deg'|'rad', ans: number }. Percent after a number divides by 100 ("50%" = 0.5).+ */+export function evaluate(src, opts = {}) {+ const angle = opts.angle === 'deg' ? 'deg' : 'rad';+ const toks = tokenize(src);+ if (!toks.length) throw new CalcError('Empty expression');+ // Resolve ans, mark unary signs, postfix percent, and insert implicit multiplication.+ const seq = [];+ let prev = null;+ const isValueEnd = (t) => t && (t.t === 'num' || t.t === ')' || t.t === 'post' || t.t === 'pct');+ for (let k = 0; k < toks.length; k++) {+ let t = toks[k];+ if (t.t === 'ans') t = { t: 'num', v: Number(opts.ans ?? 0) };+ if (t.t === 'fn' && toks[k + 1]?.t !== '(') throw new CalcError(`${t.v} needs parentheses, like ${t.v}(2)`);+ if (t.t === 'fn' && toks[k + 1]?.t !== '(') throw new CalcError(`${t.v} needs parentheses, like ${t.v}(2)`);+ if (t.t === 'op' && t.v === '%' && isValueEnd(prev)) {+ const nx = toks[k + 1];+ const nextIsValue = nx && (nx.t === 'num' || nx.t === 'fn' || nx.t === '(' || nx.t === 'ans');+ if (!nextIsValue) t = { t: 'pct' };+ }+ if (t.t === 'op' && (t.v === '-' || t.v === '+') && !isValueEnd(prev)) t = { t: 'un', v: t.v };+ if ((t.t === 'num' || t.t === 'fn' || t.t === '(') && isValueEnd(prev)) seq.push({ t: 'op', v: '*' });+ seq.push(t);+ prev = t;+ }+ const out = [];+ const st = [];+ const flush = (pred) => {+ while (st.length && pred(st[st.length - 1])) out.push(st.pop());+ };+ for (const t of seq) {+ if (t.t === 'num') out.push(t);+ else if (t.t === 'post' || t.t === 'pct') out.push(t);+ else if (t.t === 'fn') st.push(t);+ else if (t.t === 'un') st.push({ t: 'un', v: t.v, p: UNARY_P });+ else if (t.t === ',') {+ flush((x) => x.t !== '(');+ if (!st.length) throw new CalcError('Misplaced comma');+ } else if (t.t === 'op') {+ const o = OPS[t.v];+ flush((x) => {+ if (x.t === 'un') return x.p > o.p || (x.p === o.p && !o.r);+ if (x.t === 'op') {+ const xo = OPS[x.v];+ return xo.p > o.p || (xo.p === o.p && !o.r);+ }+ return false;+ });+ st.push(t);+ } else if (t.t === '(') st.push(t);+ else if (t.t === ')') {+ flush((x) => x.t !== '(');+ if (!st.length) throw new CalcError('Unbalanced parentheses');+ st.pop();+ if (st.length && st[st.length - 1].t === 'fn') out.push(st.pop());+ }+ }+ while (st.length) {+ const x = st.pop();+ if (x.t === '(') throw new CalcError('Unbalanced parentheses');+ out.push(x);+ }+ const stack = [];+ const need = (n) => {+ if (stack.length < n) throw new CalcError('Incomplete expression');+ };+ for (const t of out) {+ if (t.t === 'num') stack.push(t.v);+ else if (t.t === 'post') { need(1); stack.push(factorial(stack.pop())); }+ else if (t.t === 'pct') { need(1); stack.push(stack.pop() / 100); }+ else if (t.t === 'un') { need(1); const v = stack.pop(); stack.push(t.v === '-' ? -v : v); }+ else if (t.t === 'op') {+ need(2);+ const b = stack.pop();+ const a = stack.pop();+ stack.push(OPS[t.v].f(a, b));+ } else if (t.t === 'fn') {+ const fn = FUNCS[t.v];+ need(fn.n);+ const args = stack.splice(stack.length - fn.n, fn.n);+ if (fn.trig === 'in' && angle === 'deg') args[0] = (args[0] * Math.PI) / 180;+ let r = fn.f(...args);+ if (fn.trig === 'out' && angle === 'deg') r = (r * 180) / Math.PI;+ if (fn.trig === 'in' && angle === 'deg') r = cleanTrig(r);+ stack.push(r);+ }+ }+ if (stack.length !== 1) throw new CalcError('Incomplete expression');+ const v = stack[0];+ if (Number.isNaN(v)) throw new CalcError('Not a number');+ if (!Number.isFinite(v)) throw new CalcError(v > 0 ? 'Result too large or division by zero' : 'Result too small or division by zero');+ return v;+}++/** Remove float dust such as sin(180deg) = 1.2e-16. */+function cleanTrig(r) {+ return Math.abs(r) < 1e-14 ? 0 : r;+}++/** Format a result: up to 12 significant digits, exponent form for extremes. */+export function formatNumber(v, { group = true } = {}) {+ if (!Number.isFinite(v)) return String(v);+ if (v === 0) return '0';+ const a = Math.abs(v);+ if (a >= 1e15 || a < 1e-9) return v.toExponential(8).replace(/\.?0+e/, 'e').replace('e+', 'e');+ let s = String(parseFloat(v.toPrecision(12)));+ if (/e/.test(s)) s = v.toFixed(12).replace(/\.?0+$/, '');+ if (!group) return s;+ const [i, f] = s.split('.');+ const neg = i.startsWith('-');+ const g = (neg ? i.slice(1) : i).replace(/\B(?=(\d{3})+(?!\d))/g, ',');+ return (neg ? '-' : '') + g + (f ? `.${f}` : '');+}++// ---- Programmer mode (BigInt, fixed bit width, two's complement) ----++export const BASES = { hex: 16, dec: 10, oct: 8, bin: 2 };+export const WIDTHS = [8, 16, 32, 64];++export const mask = (width) => (1n << BigInt(width)) - 1n;+/** Wrap to unsigned width. */+export const wrap = (v, width) => BigInt.asUintN(width, v);+/** Interpret as signed. */+export const signed = (v, width) => BigInt.asIntN(width, v);++export function toBase(v, base, width) {+ const u = wrap(v, width);+ let s = u.toString(BASES[base]).toUpperCase();+ if (base === 'bin') s = s.padStart(width, '0').replace(/(.{4})(?=.)/g, '$1 ');+ return s;+}++export function parseInBase(text, base) {+ const t = String(text).replace(/[\s_]/g, '');+ if (!t) return 0n;+ const re = { hex: /^[0-9a-f]+$/i, dec: /^-?[0-9]+$/, oct: /^[0-7]+$/, bin: /^[01]+$/ }[base];+ if (!re.test(t)) throw new CalcError(`Not a valid ${base} number`);+ if (base === 'dec') return BigInt(t);+ return BigInt((base === 'hex' ? '0x' : base === 'oct' ? '0o' : '0b') + t);+}++const PROG_OPS = {+ '|': { p: 1, f: (a, b) => a | b },+ '^': { p: 2, f: (a, b) => a ^ b },+ '&': { p: 3, f: (a, b) => a & b },+ '<': { p: 4, f: (a, b) => a << (b & 127n) },+ '>': { p: 4, f: (a, b) => a >> (b & 127n) },+ '+': { p: 5, f: (a, b) => a + b },+ '-': { p: 5, f: (a, b) => a - b },+ '*': { p: 6, f: (a, b) => a * b },+ '/': { p: 6, f: (a, b) => { if (b === 0n) throw new CalcError('Division by zero'); return a / b; } },+ '%': { p: 6, f: (a, b) => { if (b === 0n) throw new CalcError('Division by zero'); return a % b; } },+};++/**+ * Evaluate a programmer expression in `base` with `width` bits.+ * Operators: + - * / % & | ^ << >> and unary ~ and -. The result wraps to the width (two's complement).+ * Returns an unsigned BigInt.+ */+export function evalProgrammer(src, base = 'dec', width = 64) {+ const s = String(src).replace(/\u00d7/g, '*').replace(/\u00f7/g, '/').replace(/<<|\bLSH\b/gi, '<').replace(/>>|\bRSH\b/gi, '>').replace(/\bAND\b/gi, '&').replace(/\bOR\b/gi, '|').replace(/\bXOR\b/gi, '^').replace(/\bNOT\b/gi, '~').replace(/\bMOD\b/gi, '%');+ const toks = [];+ let i = 0;+ const numRe = { hex: /^[0-9a-fA-F]+/, dec: /^[0-9]+/, oct: /^[0-7]+/, bin: /^[01]+/ }[base];+ while (i < s.length) {+ const c = s[i];+ if (/\s/.test(c)) { i++; continue; }+ const pre = base === 'dec' ? /^0[xob][0-9a-fA-F]+/i.exec(s.slice(i)) : null;+ if (pre) { toks.push({ t: 'n', v: BigInt(pre[0].toLowerCase()) }); i += pre[0].length; continue; }+ const m = numRe.exec(s.slice(i));+ if (m) { toks.push({ t: 'n', v: parseInBase(m[0], base) }); i += m[0].length; continue; }+ if (c === '(' || c === ')') { toks.push({ t: c }); i++; continue; }+ if (c === '~') { toks.push({ t: 'u', v: '~' }); i++; continue; }+ if (PROG_OPS[c]) { toks.push({ t: 'o', v: c }); i++; continue; }+ throw new CalcError(`Unexpected "${c}" in ${base} mode`);+ }+ if (!toks.length) throw new CalcError('Empty expression');+ const out = [];+ const st = [];+ let prev = null;+ for (let t of toks) {+ const valEnd = prev && (prev.t === 'n' || prev.t === ')');+ if (t.t === 'o' && t.v === '-' && !valEnd) t = { t: 'u', v: '-' };+ if (t.t === 'n') out.push(t);+ else if (t.t === 'u') st.push(t);+ else if (t.t === 'o') {+ const p = PROG_OPS[t.v].p;+ while (st.length) {+ const x = st[st.length - 1];+ if (x.t === 'u' || (x.t === 'o' && PROG_OPS[x.v].p >= p)) out.push(st.pop());+ else break;+ }+ st.push(t);+ } else if (t.t === '(') st.push(t);+ else {+ while (st.length && st[st.length - 1].t !== '(') out.push(st.pop());+ if (!st.length) throw new CalcError('Unbalanced parentheses');+ st.pop();+ }+ prev = t;+ }+ while (st.length) {+ const x = st.pop();+ if (x.t === '(') throw new CalcError('Unbalanced parentheses');+ out.push(x);+ }+ const stack = [];+ for (const t of out) {+ if (t.t === 'n') stack.push(t.v);+ else if (t.t === 'u') {+ if (!stack.length) throw new CalcError('Incomplete expression');+ const v = stack.pop();+ stack.push(t.v === '~' ? ~v : -v);+ } else {+ if (stack.length < 2) throw new CalcError('Incomplete expression');+ const b = stack.pop();+ const a = stack.pop();+ // Arithmetic works on signed values so -1 + 1 behaves; shifts and bitwise use the raw pattern.+ stack.push(PROG_OPS[t.v].f(signed(a, width), signed(b, width)));+ }+ }+ if (stack.length !== 1) throw new CalcError('Incomplete expression');+ return wrap(stack[0], width);+}diff --git a/src/desktop/os/apps/calculator.css b/src/desktop/os/apps/calculator.cssnew file mode 100644index 000000000..759cd030a--- /dev/null+++ b/src/desktop/os/apps/calculator.css@@ -0,0 +1,82 @@+.napp-calculator { display: flex; flex-direction: column; min-height: 0; color: var(--text); background: var(--card); font-family: inherit; container-type: inline-size; }+.napp-calculator .calc { position: relative; display: flex; flex-direction: column; flex: 1; min-height: 0; outline: none; padding: 8px 10px 10px; gap: 6px; }+.napp-calculator .calc-bar { display: flex; align-items: center; gap: 4px; }+.napp-calculator .calc-grow { flex: 1; }+.napp-calculator .calc-sr { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); }+.napp-calculator select, .napp-calculator .calc-cvin { background: var(--hover-half, var(--hover)); color: var(--text); border: 1px solid var(--bd); border-radius: 6px; padding: 6px 8px; font: inherit; font-size: 0.92rem; min-width: 0; }+.napp-calculator .calc-mode { font-weight: 600; background: transparent; border-color: transparent; padding-left: 4px; }+.napp-calculator select:hover, .napp-calculator .calc-cvin:hover { background: var(--hover); }+.napp-calculator select:focus-visible, .napp-calculator input:focus-visible, .napp-calculator button:focus-visible { outline: 2px solid var(--accent); outline-offset: 1px; }+.napp-calculator .calc-ibtn { display: grid; place-items: center; width: 32px; height: 32px; border: 0; border-radius: 6px; background: transparent; color: var(--text); cursor: pointer; }+.napp-calculator .calc-ibtn:hover { background: var(--hover); }+.napp-calculator .calc-ibtn:active { background: var(--hover-b, var(--hover)); transform: scale(0.96); }+.napp-calculator .calc-ibtn.on { background: var(--hover-b, var(--hover)); color: var(--accent); }+.napp-calculator .calc-ibtn[hidden] { display: none; }+.napp-calculator .calc-body { flex: 1; display: flex; flex-direction: column; gap: 6px; min-height: 0; overflow: auto; }+.napp-calculator .calc-disp { padding: 6px 8px 2px; text-align: right; min-height: 78px; display: flex; flex-direction: column; justify-content: flex-end; }+.napp-calculator .calc-expr { color: var(--text2); font-size: 0.95rem; white-space: nowrap; overflow-x: auto; scrollbar-width: none; min-height: 1.3em; }+.napp-calculator .calc-res { font-size: 2.9rem; font-weight: 600; line-height: 1.15; overflow-wrap: anywhere; font-variant-numeric: tabular-nums; }+.napp-calculator .calc-res.err, .napp-calculator .calc-cvout.err { font-size: 1.05rem; font-weight: 500; color: #e5484d; }+.napp-calculator .calc-memrow { display: flex; align-items: center; gap: 2px; }+.napp-calculator .calc-mem { border: 0; background: transparent; color: var(--text); border-radius: 6px; padding: 4px 8px; font-size: 0.8rem; font-weight: 600; cursor: pointer; }+.napp-calculator .calc-mem:hover:not(:disabled) { background: var(--hover); }+.napp-calculator .calc-mem:disabled { color: var(--text2); opacity: 0.45; cursor: default; }+.napp-calculator .calc-memval { margin-left: auto; font-size: 0.78rem; color: var(--text2); font-variant-numeric: tabular-nums; }+.napp-calculator .calc-pads { flex: 1; display: flex; flex-direction: column; gap: 4px; min-height: 0; }+.napp-calculator .calc-pad { display: grid; gap: 4px; flex: 1; grid-auto-rows: minmax(40px, 1fr); }+.napp-calculator .calc-pad.c4 { grid-template-columns: repeat(4, 1fr); }+.napp-calculator .calc-pad.c5 { grid-template-columns: repeat(5, 1fr); }+.napp-calculator .calc-pad.sci { flex: 0 0 auto; grid-auto-rows: minmax(34px, auto); }+.napp-calculator .calc-pad.sci .calc-key { font-size: 0.88rem; }+.napp-calculator .calc-pad.prog { grid-auto-rows: minmax(36px, 1fr); }+.napp-calculator .w2 { grid-column: span 2; }+.napp-calculator .calc-key { border: 1px solid var(--bd); border-radius: 6px; background: var(--hover-half, var(--hover)); color: var(--text); font: inherit; font-size: 1.1rem; cursor: pointer; transition: background 0.1s, transform 0.06s; }+.napp-calculator .calc-key.num { background: var(--hover); font-weight: 600; }+.napp-calculator .calc-key.op, .napp-calculator .calc-key.fn { font-weight: 500; }+.napp-calculator .calc-key.fn { font-size: 0.98rem; }+.napp-calculator .calc-key:hover:not(:disabled) { background: var(--hover-b, var(--hover)); }+.napp-calculator .calc-key:active:not(:disabled) { transform: scale(0.97); filter: brightness(0.92); }+.napp-calculator .calc-key:disabled { opacity: 0.35; cursor: default; }+.napp-calculator .calc-key.eq { background: var(--accent); border-color: var(--accent); color: #fff; font-weight: 700; }+.napp-calculator .calc-key.eq:hover { filter: brightness(1.1); background: var(--accent); }+.napp-calculator .calc-hist { position: absolute; z-index: 3; inset: 44px 0 0 auto; width: min(320px, 90%); background: var(--card); border-left: 1px solid var(--bd); box-shadow: var(--shadow-md); display: flex; flex-direction: column; animation: calc-slide 0.16s ease-out; }+.napp-calculator .calc-hist[hidden] { display: none; }+@keyframes calc-slide { from { transform: translateX(24px); opacity: 0; } to { transform: none; opacity: 1; } }+.napp-calculator .calc-hhead { display: flex; align-items: center; justify-content: space-between; padding: 10px 14px; border-bottom: 1px solid var(--bd); }+.napp-calculator .calc-link { border: 0; background: transparent; color: var(--accent); cursor: pointer; font: inherit; padding: 4px 6px; border-radius: 4px; }+.napp-calculator .calc-link:hover:not(:disabled) { background: var(--hover); }+.napp-calculator .calc-link:disabled { color: var(--text2); cursor: default; }+.napp-calculator .calc-hempty { color: var(--text2); padding: 16px 14px; margin: 0; line-height: 1.5; font-size: 0.9rem; }+.napp-calculator .calc-hlist { list-style: none; margin: 0; padding: 4px; overflow: auto; flex: 1; }+.napp-calculator .calc-hitem { display: flex; flex-direction: column; align-items: flex-end; width: 100%; border: 0; background: transparent; color: var(--text); padding: 8px 10px; border-radius: 6px; cursor: pointer; font: inherit; gap: 2px; }+.napp-calculator .calc-hitem:hover { background: var(--hover); }+.napp-calculator .calc-hitem span { color: var(--text2); font-size: 0.82rem; overflow-wrap: anywhere; text-align: right; }+.napp-calculator .calc-hitem b { font-size: 1.25rem; font-weight: 600; font-variant-numeric: tabular-nums; }+.napp-calculator .calc-bases { display: flex; flex-direction: column; gap: 1px; }+.napp-calculator .calc-base { display: flex; gap: 12px; align-items: baseline; border: 0; border-left: 3px solid transparent; background: transparent; color: var(--text); font: inherit; padding: 3px 8px; border-radius: 4px; cursor: pointer; text-align: left; font-variant-numeric: tabular-nums; }+.napp-calculator .calc-base b { width: 32px; color: var(--text2); font-size: 0.78rem; }+.napp-calculator .calc-base span { overflow-wrap: anywhere; font-size: 0.95rem; }+.napp-calculator .calc-base:hover { background: var(--hover); }+.napp-calculator .calc-base.on { border-left-color: var(--accent); background: var(--hover); }+.napp-calculator .calc-base.on b { color: var(--accent); }+.napp-calculator .calc-widths { display: flex; gap: 4px; }+.napp-calculator .calc-chip { flex: 1; border: 1px solid var(--bd); border-radius: 999px; background: transparent; color: var(--text2); padding: 3px 0; font: inherit; font-size: 0.8rem; cursor: pointer; }+.napp-calculator .calc-chip:hover { background: var(--hover); }+.napp-calculator .calc-chip.on { background: var(--accent); border-color: var(--accent); color: #fff; }+.napp-calculator .calc-bits { display: flex; flex-wrap: wrap; gap: 2px; justify-content: center; }+.napp-calculator .calc-bit { width: 17px; height: 22px; padding: 0; border: 0; border-radius: 3px; background: var(--hover); color: var(--text2); font: inherit; font-size: 0.72rem; cursor: pointer; }+.napp-calculator .calc-bit.gap { margin-right: 5px; }+.napp-calculator .calc-bit.on { background: var(--accent); color: #fff; }+.napp-calculator .calc-bit:hover { filter: brightness(1.2); }+.napp-calculator .calc-cvbox { display: flex; flex-direction: column; gap: 6px; padding: 8px; border: 1px solid var(--bd); border-radius: 8px; }+.napp-calculator .calc-cvin { font-size: 1.7rem; font-weight: 600; background: transparent; border-color: transparent; padding: 2px 4px; text-align: right; font-variant-numeric: tabular-nums; }+.napp-calculator .calc-cvout { font-size: 1.7rem; font-weight: 600; text-align: right; padding: 2px 4px; overflow-wrap: anywhere; min-height: 2.2rem; font-variant-numeric: tabular-nums; }+.napp-calculator .swap { align-self: center; margin: -10px 0; background: var(--card); border: 1px solid var(--bd); position: relative; z-index: 1; }+.napp-calculator .calc-cvhead { color: var(--text2); font-size: 0.8rem; padding: 4px 4px 0; }+.napp-calculator .calc-cvall { display: flex; flex-direction: column; overflow: auto; }+.napp-calculator .calc-cvrow { display: flex; justify-content: space-between; gap: 12px; border: 0; background: transparent; color: var(--text); font: inherit; padding: 6px 8px; border-radius: 6px; cursor: pointer; font-size: 0.9rem; }+.napp-calculator .calc-cvrow:hover { background: var(--hover); }+.napp-calculator .calc-cvrow span { color: var(--text2); }+.napp-calculator .calc-cvrow b { font-variant-numeric: tabular-nums; overflow-wrap: anywhere; text-align: right; }+@media (prefers-reduced-motion: reduce) { .napp-calculator * { animation: none !important; transition: none !important; } }+@container (min-width: 560px) { .napp-calculator .calc-res { font-size: 3.3rem; } }diff --git a/src/desktop/os/apps/calculator.js b/src/desktop/os/apps/calculator.jsnew file mode 100644index 000000000..67c092cce--- /dev/null+++ b/src/desktop/os/apps/calculator.js@@ -0,0 +1,612 @@+// Calculator: Standard, Scientific, Programmer and Converter. All arithmetic goes through the+// safe parsers in calc-engine.js (no eval). History, memory and mode persist via ctx.store.+import './calculator.css';+import { evaluate, formatNumber, evalProgrammer, toBase, signed, wrap, WIDTHS, BASES } from './calc-engine.js';+import { CATEGORIES, convert } from './unit-convert.js';++const K = { prefs: 'tws:calc:prefs', history: 'tws:calc:history', mem: 'tws:calc:mem' };+const U = { times: '×', div: '÷', minus: '−', back: '⌫', pi: 'π', sqrt: '√', pm: '±', sq: 'x²', inv: '1/x', swap: '⇅' };+const MODES = [['standard', 'Standard'], ['scientific', 'Scientific'], ['programmer', 'Programmer'], ['converter', 'Converter']];++const readJson = (store, k, d) => {+ try {+ const v = JSON.parse(store.get(k));+ return v ?? d;+ } catch {+ return d;+ }+};++export function mount(host, ctx) {+ const { h, esc, store } = ctx;+ const prefs = { mode: 'standard', angle: 'deg', base: 'dec', width: 64, cat: 'length', ...readJson(store, K.prefs, {}) };+ if (!MODES.some(([id]) => id === prefs.mode)) prefs.mode = 'standard';+ let history = readJson(store, K.history, []);+ if (!Array.isArray(history)) history = [];+ let memory = Number(store.get(K.mem));+ if (!Number.isFinite(memory)) memory = null;++ // calculator state+ let expr = '';+ let ans = 0;+ let justEvaled = false;+ let doneExpr = '';+ // programmer state+ let pexpr = '';+ // converter state+ let cv = { text: '1', from: null, to: null };++ const savePrefs = () => store.set(K.prefs, JSON.stringify(prefs));+ const saveHistory = () => store.set(K.history, JSON.stringify(history.slice(0, 60)));++ host.classList.add('napp-calculator');+ host.innerHTML = '';+ const root = h('div', 'calc');+ root.tabIndex = 0;+ root.setAttribute('aria-label', 'Calculator');+ const bar = h('div', 'calc-bar');+ const modeSel = h('select', 'calc-mode');+ modeSel.setAttribute('aria-label', 'Calculator mode');+ modeSel.innerHTML = MODES.map(([id, l]) => `<option value="${id}">${l}</option>`).join('');+ modeSel.value = prefs.mode;+ const copyBtn = h('button', 'calc-ibtn', ctx.icon('files', 16));+ copyBtn.title = 'Copy result (Ctrl+C)';+ copyBtn.setAttribute('aria-label', 'Copy result');+ const histBtn = h('button', 'calc-ibtn', ctx.icon('clock', 16));+ histBtn.title = 'History';+ histBtn.setAttribute('aria-label', 'History');+ histBtn.setAttribute('aria-expanded', 'false');+ bar.append(modeSel, h('span', 'calc-grow'), copyBtn, histBtn);+ const body = h('div', 'calc-body');+ const hist = h('aside', 'calc-hist');+ hist.hidden = true;+ hist.setAttribute('aria-label', 'History');+ root.append(bar, body, hist);+ host.append(root);++ const live = h('div', 'calc-sr');+ live.setAttribute('aria-live', 'polite');+ root.append(live);++ let els = {};+ const setBodyFocus = () => root.focus({ preventScroll: true });++ // ---------- shared helpers ----------+ const withClose = (s) => {+ let o = 0;+ for (const c of s) {+ if (c === '(') o++;+ else if (c === ')') o--;+ }+ return o > 0 ? s + ')'.repeat(o) : s;+ };+ const rawNum = (v) => formatNumber(v, { group: false });+ const pretty = (s) => s.replace(/\*/g, ` ${U.times} `).replace(/\//g, ` ${U.div} `).replace(/(?<=[\d)!%a-z])-/gi, ` ${U.minus} `).replace(/\+/g, ' + ').replace(/\^/g, '^').replace(/\s{2,}/g, ' ').trim();+ const tryEval = (s) => {+ try {+ return { v: evaluate(withClose(s), { angle: prefs.angle, ans }) };+ } catch (err) {+ return { err: err.message };+ }+ };+ const copyText = async (text) => {+ try {+ await navigator.clipboard.writeText(text);+ ctx.toast('Copied to clipboard');+ } catch {+ ctx.toast('Copy was blocked by the browser');+ }+ };++ // ---------- standard / scientific ----------+ function press(tok) {+ const isOp = /^[+\-*/^%]$/.test(tok) || tok === '!' || tok === '^2';+ if (justEvaled) {+ if (!isOp) expr = '';+ justEvaled = false;+ doneExpr = '';+ }+ if (/^[*/^%]$/.test(tok) && (!expr || /[*/^(+\-]$/.test(expr))) {+ if (!expr) expr = rawNum(ans);+ else if (/[*/^+\-]$/.test(expr)) expr = expr.slice(0, -1);+ else if (/\($/.test(expr)) return;+ } else if (/^[+-]$/.test(tok) && /[+\-*/]$/.test(expr) && !/\($/.test(expr)) {+ expr = expr.slice(0, -1);+ }+ if (tok === '.' && /(\d*\.\d*)$/.test(expr.match(/[\d.]*$/)?.[0] || '') && /\./.test(expr.match(/[\d.]*$/)?.[0] || '')) return;+ expr += tok;+ renderStd();+ }+ function neg() {+ if (justEvaled) justEvaled = false;+ const m = /\(-([\d.]+(?:e[+-]?\d+)?)\)$/i.exec(expr);+ if (m) expr = expr.slice(0, m.index) + m[1];+ else {+ const n = /([\d.]+(?:e[+-]?\d+)?)$/i.exec(expr);+ if (n) expr = `${expr.slice(0, n.index)}(-${n[1]})`;+ else expr += '(-';+ }+ renderStd();+ }+ function equals() {+ if (!expr) return;+ const r = tryEval(expr);+ if (r.err) {+ els.res.textContent = r.err;+ els.res.classList.add('err');+ live.textContent = r.err;+ return;+ }+ const shown = pretty(withClose(expr));+ history.unshift({ expr: withClose(expr), shown, res: r.v, angle: prefs.angle });+ history = history.slice(0, 60);+ saveHistory();+ ans = r.v;+ doneExpr = `${shown} =`;+ expr = rawNum(r.v);+ justEvaled = true;+ renderStd();+ renderHist();+ live.textContent = `Result ${formatNumber(r.v)}`;+ }+ function clearAll() {+ expr = '';+ justEvaled = false;+ doneExpr = '';+ renderStd();+ }+ function backspace() {+ if (justEvaled) return clearAll();+ expr = expr.replace(/(?:[a-z0-9]+\($|.)$/i, '');+ renderStd();+ }+ function memOp(op) {+ const cur = tryEval(expr || '0');+ const val = cur.v ?? ans;+ if (op === 'MC') memory = null;+ else if (op === 'MR') {+ if (memory == null) return;+ press(rawNum(memory));+ return;+ } else if (op === 'MS') memory = val;+ else if (op === 'M+') memory = (memory ?? 0) + val;+ else if (op === 'M-') memory = (memory ?? 0) - val;+ if (memory == null) store.del(K.mem);+ else store.set(K.mem, String(memory));+ renderStd();+ }++ const T = (label, tok, cls = '', aria) => ({ label, act: () => press(tok), cls, aria });+ const A = (label, act, cls = '', aria) => ({ label, act, cls, aria });+ const STD_PAD = () => [+ A('C', clearAll, 'fn', 'Clear'), A(U.back, backspace, 'fn', 'Backspace'), T('%', '%', 'fn', 'Percent'), T(U.div, '/', 'op', 'Divide'),+ T('7', '7', 'num'), T('8', '8', 'num'), T('9', '9', 'num'), T(U.times, '*', 'op', 'Multiply'),+ T('4', '4', 'num'), T('5', '5', 'num'), T('6', '6', 'num'), T(U.minus, '-', 'op', 'Subtract'),+ T('1', '1', 'num'), T('2', '2', 'num'), T('3', '3', 'num'), T('+', '+', 'op', 'Add'),+ A(U.pm, neg, 'num', 'Toggle sign'), T('0', '0', 'num'), T('.', '.', 'num', 'Decimal point'), A('=', equals, 'eq', 'Equals'),+ ];+ const SCI_PAD = () => [+ A(prefs.angle === 'deg' ? 'DEG' : 'RAD', () => {+ prefs.angle = prefs.angle === 'deg' ? 'rad' : 'deg';+ savePrefs();+ renderStd();+ }, 'fn', 'Toggle degrees or radians'), T(U.pi, 'pi', 'fn', 'Pi'), T('e', 'e', 'fn', 'Euler number'), T('(', '(', 'fn'), T(')', ')', 'fn'),+ T('sin', 'sin(', 'fn'), T('cos', 'cos(', 'fn'), T('tan', 'tan(', 'fn'), T('asin', 'asin(', 'fn'), T('acos', 'acos(', 'fn'),+ T('atan', 'atan(', 'fn'), T('log', 'log(', 'fn', 'Log base 10'), T('ln', 'ln(', 'fn', 'Natural log'), T(U.sqrt, 'sqrt(', 'fn', 'Square root'), T('³√', 'cbrt(', 'fn', 'Cube root'),+ T(U.sq, '^2', 'fn', 'Square'), T('xʸ', '^', 'fn', 'Power'), T('n!', '!', 'fn', 'Factorial'), T('|x|', 'abs(', 'fn', 'Absolute value'),+ A(U.inv, () => {+ expr = `1/(${expr || rawNum(ans)})`;+ justEvaled = false;+ renderStd();+ }, 'fn', 'Reciprocal'),+ ];++ function padHtml(items, cols, wrapCls = '') {+ const grid = h('div', `calc-pad c${cols} ${wrapCls}`);+ for (const it of items) {+ const b = h('button', `calc-key ${it.cls}`, it.label);+ b.type = 'button';+ if (it.aria) b.setAttribute('aria-label', it.aria);+ if (it.off) b.disabled = true;+ b.addEventListener('click', () => {+ it.act();+ setBodyFocus();+ });+ grid.append(b);+ }+ return grid;+ }++ function renderStd() {+ const sci = prefs.mode === 'scientific';+ if (!els.std) {+ body.replaceChildren();+ const disp = h('div', 'calc-disp');+ els.expr = h('div', 'calc-expr');+ els.res = h('div', 'calc-res');+ els.res.setAttribute('role', 'status');+ disp.append(els.expr, els.res);+ els.mem = h('div', 'calc-memrow');+ els.pads = h('div', 'calc-pads');+ body.append(disp, els.mem, els.pads);+ els.std = true;+ els.padKey = '';+ }+ const prev = expr ? tryEval(expr) : null;+ els.expr.textContent = justEvaled ? doneExpr : pretty(expr);+ els.expr.title = els.expr.textContent;+ els.res.classList.remove('err');+ if (justEvaled) els.res.textContent = formatNumber(ans);+ else if (!expr) els.res.textContent = '0';+ else if (prev && prev.v !== undefined) els.res.textContent = /^[\d.]+$/.test(expr) ? groupLiteral(expr) : formatNumber(prev.v);+ else els.res.textContent = expr;+ const len = els.res.textContent.length;+ els.res.style.fontSize = len > 22 ? '1.4rem' : len > 15 ? '1.9rem' : len > 10 ? '2.4rem' : '';+ const memOn = memory != null;+ els.mem.replaceChildren(+ ...['MC', 'MR', 'M+', 'M-', 'MS'].map((m) => {+ const b = h('button', 'calc-mem', m);+ b.type = 'button';+ b.setAttribute('aria-label', { MC: 'Memory clear', MR: 'Memory recall', 'M+': 'Memory add', 'M-': 'Memory subtract', MS: 'Memory store' }[m]);+ if ((m === 'MC' || m === 'MR') && !memOn) b.disabled = true;+ b.addEventListener('click', () => {+ memOp(m);+ setBodyFocus();+ });+ return b;+ }),+ Object.assign(h('span', 'calc-memval'), { textContent: memOn ? `M = ${formatNumber(memory)}` : '', title: 'Memory value' }),+ );+ const key = sci + prefs.angle;+ if (els.padKey !== key) {+ els.padKey = key;+ els.pads.replaceChildren(...(sci ? [padHtml(SCI_PAD(), 5, 'sci')] : []), padHtml(STD_PAD(), 4));+ }+ bodyScroll();+ }+ const groupLiteral = (t) => {+ const [i, f] = t.split('.');+ return i.replace(/\B(?=(\d{3})+(?!\d))/g, ',') + (f !== undefined ? `.${f}` : '');+ };+ const bodyScroll = () => {+ if (els.expr) els.expr.scrollLeft = els.expr.scrollWidth;+ };++ // ---------- programmer ----------+ const compact = (v, base) => {+ if (base === 'dec') return signed(v, prefs.width).toString();+ return toBase(v, base, prefs.width).replace(/\s/g, '').replace(/^0+(?=.)/, '');+ };+ function pval() {+ try {+ return { v: evalProgrammer(pexpr || '0', prefs.base, prefs.width) };+ } catch (err) {+ return { err: err.message };+ }+ }+ function pPress(tok) {+ pexpr += tok;+ renderProg();+ }+ function pEquals() {+ const r = pval();+ if (r.err) {+ els.perr.textContent = r.err;+ return;+ }+ pexpr = compact(r.v, prefs.base);+ renderProg();+ }+ function renderProg() {+ body.replaceChildren();+ els.std = false;+ const r = pval();+ const v = r.v ?? 0n;+ const disp = h('div', 'calc-disp');+ const ex = h('div', 'calc-expr', '');+ ex.textContent = pexpr.replace(/\*/g, ` ${U.times} `).replace(/\//g, ` ${U.div} `).trim();+ els.perr = h('div', 'calc-res');+ els.perr.setAttribute('role', 'status');+ els.perr.textContent = r.err ? r.err : '';+ els.perr.classList.toggle('err', !!r.err);+ if (!r.err) {+ els.perr.textContent = pexpr ? compact(v, prefs.base).toUpperCase() : '0';+ }+ disp.append(ex, els.perr);+ const bases = h('div', 'calc-bases');+ for (const b of Object.keys(BASES)) {+ const row = h('button', `calc-base${prefs.base === b ? ' on' : ''}`);+ row.type = 'button';+ row.setAttribute('aria-pressed', String(prefs.base === b));+ const txt = b === 'dec' ? signed(v, prefs.width).toString() : toBase(v, b, prefs.width);+ row.innerHTML = `<b>${b.toUpperCase()}</b><span>${esc(txt)}</span>`;+ row.addEventListener('click', () => {+ if (prefs.base === b) return;+ const cur = pval().v ?? 0n;+ prefs.base = b;+ savePrefs();+ pexpr = pexpr ? compact(cur, b) : '';+ renderProg();+ setBodyFocus();+ });+ bases.append(row);+ }+ const wrow = h('div', 'calc-widths');+ wrow.setAttribute('role', 'group');+ wrow.setAttribute('aria-label', 'Word size');+ for (const w of WIDTHS) {+ const b = h('button', `calc-chip${prefs.width === w ? ' on' : ''}`, `${w}-bit`);+ b.type = 'button';+ b.setAttribute('aria-pressed', String(prefs.width === w));+ b.addEventListener('click', () => {+ const cur = pval().v ?? 0n;+ prefs.width = w;+ savePrefs();+ pexpr = pexpr ? compact(wrap(cur, w), prefs.base) : '';+ renderProg();+ });+ wrow.append(b);+ }+ const bits = h('div', 'calc-bits');+ bits.setAttribute('role', 'group');+ bits.setAttribute('aria-label', 'Bits');+ const u = wrap(v, prefs.width);+ for (let i = prefs.width - 1; i >= 0; i--) {+ const on = (u >> BigInt(i)) & 1n;+ const b = h('button', `calc-bit${on ? ' on' : ''}${i % 4 === 0 && i ? ' gap' : ''}`, on ? '1' : '0');+ b.type = 'button';+ b.setAttribute('aria-label', `Bit ${i}`);+ b.setAttribute('aria-pressed', String(!!on));+ b.addEventListener('click', () => {+ pexpr = compact(u ^ (1n << BigInt(i)), prefs.base);+ renderProg();+ });+ bits.append(b);+ }+ const baseIdx = Object.keys(BASES).indexOf(prefs.base);+ const maxDigit = BASES[prefs.base];+ const P = (label, tok, cls, aria) => ({ label, act: () => pPress(tok), cls, aria });+ const dg = (d, hexOnly = false) => ({ ...P(d, d, 'num'), off: hexOnly ? baseIdx !== 0 : parseInt(d, 16) >= maxDigit });+ const items = [+ A('AC', () => { pexpr = ''; renderProg(); }, 'fn', 'Clear'), A(U.back, () => { pexpr = pexpr.replace(/\s*(?:<<|>>|.)$/, ''); renderProg(); }, 'fn', 'Backspace'), P('(', '(', 'fn'), P(')', ')', 'fn'),+ P('<<', '<<', 'fn', 'Shift left'), P('>>', '>>', 'fn', 'Shift right'), P('AND', ' AND ', 'fn'), P('OR', ' OR ', 'fn'),+ P('XOR', ' XOR ', 'fn'), P('NOT', '~', 'fn'), P('MOD', ' MOD ', 'fn'), P(U.div, '/', 'op', 'Divide'),+ dg('D', true), dg('E', true), dg('F', true), P(U.times, '*', 'op', 'Multiply'),+ dg('A', true), dg('B', true), dg('C', true), P(U.minus, '-', 'op', 'Subtract'),+ dg('7'), dg('8'), dg('9'), P('+', '+', 'op', 'Add'),+ dg('4'), dg('5'), dg('6'), A(U.pm, () => { pexpr = pexpr ? `-(${pexpr})` : '-'; renderProg(); }, 'num', 'Negate'),+ dg('1'), dg('2'), dg('3'), { ...P('00', '00', 'num'), off: maxDigit < 2 },+ { ...dg('0'), cls: 'num w2' }, A('=', pEquals, 'eq w2', 'Equals'),+ ];+ // Programmer pad is 4 columns; "=" spans two rows through CSS.+ const pad = padHtml(items, 4, 'prog');+ body.append(disp, bases, wrow, bits, pad);+ }++ // ---------- converter ----------+ function renderConv() {+ body.replaceChildren();+ els.std = false;+ const cat = CATEGORIES[prefs.cat] ? prefs.cat : 'length';+ const def = CATEGORIES[cat];+ const keys = Object.keys(def.units);+ if (!keys.includes(cv.from)) cv.from = keys[0];+ if (!keys.includes(cv.to)) cv.to = keys[1] || keys[0];+ const catSel = h('select', 'calc-sel');+ catSel.setAttribute('aria-label', 'Unit category');+ catSel.innerHTML = Object.entries(CATEGORIES).map(([id, c]) => `<option value="${id}"${id === cat ? ' selected' : ''}>${c.label}</option>`).join('');+ catSel.addEventListener('change', () => {+ prefs.cat = catSel.value;+ cv.from = cv.to = null;+ savePrefs();+ renderConv();+ });+ const unitSel = (cur, onChange, label) => {+ const s = h('select', 'calc-sel');+ s.setAttribute('aria-label', label);+ s.innerHTML = keys.map((k) => `<option value="${esc(k)}"${k === cur ? ' selected' : ''}>${esc(def.units[k][0])}</option>`).join('');+ s.addEventListener('change', () => onChange(s.value));+ return s;+ };+ const input = h('input', 'calc-cvin');+ input.type = 'text';+ input.inputMode = 'decimal';+ input.value = cv.text;+ input.setAttribute('aria-label', 'Value to convert');+ const out = h('output', 'calc-cvout');+ out.setAttribute('aria-live', 'polite');+ const all = h('div', 'calc-cvall');+ const update = () => {+ cv.text = input.value;+ const n = Number(String(input.value).replace(/,/g, ''));+ all.replaceChildren();+ if (input.value.trim() === '' || !Number.isFinite(n)) {+ out.textContent = input.value.trim() === '' ? '0' : 'Enter a number';+ out.classList.toggle('err', input.value.trim() !== '');+ return;+ }+ try {+ const r = convert(cat, cv.from, cv.to, n);+ out.classList.remove('err');+ out.textContent = formatNumber(r);+ out.dataset.raw = rawNum(r);+ for (const k of keys) {+ if (k === cv.from) continue;+ const b = h('button', 'calc-cvrow');+ b.type = 'button';+ let txt;+ try {+ txt = formatNumber(convert(cat, cv.from, k, n));+ } catch {+ continue;+ }+ b.innerHTML = `<span>${esc(def.units[k][0])}</span><b>${esc(txt)}</b>`;+ b.title = 'Click to copy';+ b.addEventListener('click', () => copyText(txt.replace(/,/g, '')));+ all.append(b);+ }+ } catch (err) {+ out.textContent = err.message;+ out.classList.add('err');+ }+ };+ input.addEventListener('input', update);+ const swap = h('button', 'calc-ibtn swap', U.swap);+ swap.type = 'button';+ swap.title = 'Swap units';+ swap.setAttribute('aria-label', 'Swap units');+ swap.addEventListener('click', () => {+ [cv.from, cv.to] = [cv.to, cv.from];+ const o = out.dataset.raw;+ if (o && !out.classList.contains('err')) cv.text = o;+ renderConv();+ });+ const a = h('div', 'calc-cvbox');+ a.append(unitSel(cv.from, (v) => { cv.from = v; update(); }, 'From unit'), input);+ const b = h('div', 'calc-cvbox');+ b.append(unitSel(cv.to, (v) => { cv.to = v; update(); }, 'To unit'), out);+ body.append(catSel, a, swap, b, h('div', 'calc-cvhead', 'All units'), all);+ update();+ input.focus({ preventScroll: true });+ }++ // ---------- history ----------+ function renderHist() {+ hist.replaceChildren();+ const head = h('div', 'calc-hhead');+ head.innerHTML = '<b>History</b>';+ const clr = h('button', 'calc-link', 'Clear');+ clr.type = 'button';+ clr.disabled = !history.length;+ clr.addEventListener('click', () => {+ history = [];+ saveHistory();+ renderHist();+ });+ head.append(clr);+ hist.append(head);+ if (!history.length) {+ hist.append(h('p', 'calc-hempty', 'Calculations you finish with = appear here. Select one to reuse it.'));+ return;+ }+ const list = h('ul', 'calc-hlist');+ for (const e of history) {+ const li = h('li');+ const b = h('button', 'calc-hitem');+ b.type = 'button';+ b.innerHTML = `<span>${esc(e.shown)} =</span><b>${esc(formatNumber(e.res))}</b>`;+ b.title = 'Click to reuse the result. Shift+click to reuse the expression.';+ b.addEventListener('click', (ev) => {+ if (prefs.mode === 'programmer' || prefs.mode === 'converter') setMode('standard');+ justEvaled = false;+ expr = ev.shiftKey ? e.expr : rawNum(e.res);+ renderStd();+ toggleHist(false);+ setBodyFocus();+ });+ li.append(b);+ list.append(li);+ }+ hist.append(list);+ }+ function toggleHist(force) {+ const open = force ?? hist.hidden;+ hist.hidden = !open;+ histBtn.setAttribute('aria-expanded', String(open));+ histBtn.classList.toggle('on', open);+ if (open) renderHist();+ }+ histBtn.addEventListener('click', () => toggleHist());++ // ---------- mode + keyboard ----------+ function setMode(m) {+ prefs.mode = m;+ modeSel.value = m;+ savePrefs();+ root.dataset.mode = m;+ els.std = false;+ histBtn.hidden = m === 'programmer' || m === 'converter';+ if (histBtn.hidden) toggleHist(false);+ if (m === 'programmer') renderProg();+ else if (m === 'converter') renderConv();+ else renderStd();+ ctx.setTitle(`Calculator - ${MODES.find(([id]) => id === m)[1]}`);+ }+ modeSel.addEventListener('change', () => setMode(modeSel.value));++ copyBtn.addEventListener('click', () => {+ if (prefs.mode === 'converter') return copyText(els.cvout?.dataset.raw || root.querySelector('.calc-cvout')?.dataset.raw || '');+ if (prefs.mode === 'programmer') return copyText(root.querySelector('.calc-res')?.textContent || '');+ const r = justEvaled ? ans : tryEval(expr || '0').v;+ if (r === undefined) return ctx.toast('Nothing to copy yet');+ copyText(rawNum(r));+ });++ root.addEventListener('keydown', (e) => {+ if (e.target.closest('input, select')) return;+ if (e.target.closest('button') && (e.key === 'Enter' || e.key === ' ')) return;+ const mode = prefs.mode;+ if (mode === 'converter') return;+ if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === 'c') {+ if (!window.getSelection()?.toString()) {+ e.preventDefault();+ copyBtn.click();+ }+ return;+ }+ if (e.ctrlKey || e.metaKey || e.altKey) return;+ const k = e.key;+ if (mode === 'programmer') {+ if (/^[0-9a-fA-F]$/.test(k)) {+ if (parseInt(k, 16) < BASES[prefs.base]) pPress(k.toUpperCase());+ } else if ('+-*/()%&|^~'.includes(k) && k.length === 1) pPress(k);+ else if (k === '<' || k === '>') pPress(k + k);+ else if (k === 'Enter' || k === '=') pEquals();+ else if (k === 'Backspace') { pexpr = pexpr.replace(/\s*(?:<<|>>|.)$/, ''); renderProg(); }+ else if (k === 'Escape' || k === 'Delete') { pexpr = ''; renderProg(); }+ else return;+ e.preventDefault();+ return;+ }+ if (/^[0-9.]$/.test(k)) press(k);+ else if ('+-*/^%!()'.includes(k) && k.length === 1) press(k);+ else if (k === 'x' || k === 'X') press('*');+ else if (k === 'Enter' || k === '=') equals();+ else if (k === 'Backspace') backspace();+ else if (k === 'Escape' || k === 'Delete') clearAll();+ else if (k === 'p' || k === 'P') press('pi');+ else if (k === 'r' && mode === 'scientific') press('sqrt(');+ else if (k === 'l' && mode === 'scientific') press('log(');+ else if (k === 's' && mode === 'scientific') press('sin(');+ else if (k === 'c' && mode === 'scientific') press('cos(');+ else if (k === 't' && mode === 'scientific') press('tan(');+ else if (k === 'F9') neg();+ else return;+ e.preventDefault();+ });+ root.addEventListener('paste', (e) => {+ if (e.target.closest('input')) return;+ const t = (e.clipboardData?.getData('text') || '').trim();+ if (!t) return;+ e.preventDefault();+ if (prefs.mode === 'programmer') {+ pexpr += t.replace(/[,\s]/g, '');+ return renderProg();+ }+ const clean = t.replace(/,/g, '').replace(/\s+/g, '').replace(/×/g, '*').replace(/÷/g, '/').replace(/−/g, '-');+ if (justEvaled) {+ justEvaled = false;+ expr = '';+ }+ const r = tryEval(clean);+ if (r.err) return ctx.toast(`Cannot paste: ${r.err}`);+ expr += clean;+ renderStd();+ });++ setMode(prefs.mode);+ setBodyFocus();+ return () => {+ savePrefs();+ };+}diff --git a/src/desktop/os/apps/camera-logic.js b/src/desktop/os/apps/camera-logic.jsnew file mode 100644index 000000000..2fa30ad0b--- /dev/null+++ b/src/desktop/os/apps/camera-logic.js@@ -0,0 +1,53 @@+// Pure helpers for the Camera app: file names, recorder mime choice and getUserMedia error mapping.++const p2 = (n) => String(n).padStart(2, '0');++/** "Camera 2026-10-11 07.45.12.png" (colons are avoided so the name is valid everywhere). */+export function captureName(date, ext) {+ const d = `${date.getFullYear()}-${p2(date.getMonth() + 1)}-${p2(date.getDate())}`;+ const t = `${p2(date.getHours())}.${p2(date.getMinutes())}.${p2(date.getSeconds())}`;+ return `Camera ${d} ${t}.${ext}`;+}++export const RECORDER_TYPES = ['video/webm;codecs=vp9,opus', 'video/webm;codecs=vp8,opus', 'video/webm', 'video/mp4'];++/** First recorder mime type the browser supports, given an `isTypeSupported` function. */+export function pickRecorderType(isSupported) {+ return RECORDER_TYPES.find((t) => isSupported(t)) || '';+}++export const extForRecorderType = (type) => (/mp4/.test(type) ? 'mp4' : 'webm');++/**+ * Map a getUserMedia failure to { kind, title, steps[] } the UI can show.+ * kinds: denied, none, busy, insecure, unsupported, other.+ */+export function classifyMediaError(err, { hasMediaDevices = true, secure = true } = {}) {+ if (!secure) {+ return { kind: 'insecure', title: 'The camera needs a secure connection', steps: ['Open three.ws over https:// (or localhost). Browsers block camera access on insecure pages.'] };+ }+ if (!hasMediaDevices) {+ return { kind: 'unsupported', title: 'This browser cannot reach a camera', steps: ['Try a current version of Chrome, Edge, Firefox or Safari.'] };+ }+ const name = err?.name || '';+ if (name === 'NotAllowedError' || name === 'SecurityError' || name === 'PermissionDeniedError') {+ return {+ kind: 'denied',+ title: 'Camera access is blocked',+ steps: ['Click the camera or lock icon in the address bar.', 'Set Camera to Allow for this site.', 'Choose Try again below.'],+ };+ }+ if (name === 'NotFoundError' || name === 'DevicesNotFoundError' || name === 'OverconstrainedError') {+ return { kind: 'none', title: 'No camera was found', steps: ['Plug in or turn on a camera.', 'Check that another app has not disabled it in system privacy settings.', 'Choose Try again below.'] };+ }+ if (name === 'NotReadableError' || name === 'TrackStartError' || name === 'AbortError') {+ return { kind: 'busy', title: 'The camera is in use by another app', steps: ['Close other apps or browser tabs that use the camera, such as a video call.', 'Choose Try again below.'] };+ }+ return { kind: 'other', title: 'The camera could not start', steps: [err?.message || 'Unknown error.', 'Choose Try again below.'] };+}++/** "0:07" elapsed label for the recording indicator. */+export function elapsedLabel(ms) {+ const s = Math.floor(ms / 1000);+ return `${Math.floor(s / 60)}:${p2(s % 60)}`;+}diff --git a/src/desktop/os/apps/camera.css b/src/desktop/os/apps/camera.cssnew file mode 100644index 000000000..c8e75c611--- /dev/null+++ b/src/desktop/os/apps/camera.css@@ -0,0 +1,58 @@+.napp-camera { display: flex; flex-direction: column; min-height: 0; background: #0b0b0d; color: #f3f3f3; }+.napp-camera .cam { position: relative; flex: 1; display: flex; flex-direction: column; min-height: 0; outline: none; }+.napp-camera .cam-top { display: flex; align-items: center; gap: 6px; padding: 8px 10px; background: var(--card); color: var(--text); border-bottom: 1px solid var(--bd); }+.napp-camera .cam-grow { flex: 1; }+.napp-camera .cam-sel { background: var(--hover); color: var(--text); border: 1px solid var(--bd); border-radius: 6px; padding: 6px 8px; font: inherit; font-size: 0.88rem; max-width: 50%; }+.napp-camera .cam-sel[hidden], .napp-camera .cam-tb[hidden] { display: none; }+.napp-camera .cam-tb { display: inline-flex; align-items: center; gap: 6px; border: 1px solid transparent; background: transparent; color: var(--text); border-radius: 6px; padding: 6px 10px; font: inherit; font-size: 0.85rem; cursor: pointer; }+.napp-camera .cam-tb:hover { background: var(--hover); }+.napp-camera .cam-tb.on { color: var(--accent); background: var(--hover); }+.napp-camera .cam-tb.txt { font-weight: 600; min-width: 48px; justify-content: center; border-color: var(--bd); }+.napp-camera button:focus-visible, .napp-camera select:focus-visible, .napp-camera .cam:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }+.napp-camera .cam-stage { position: relative; flex: 1; min-height: 0; background: #000; display: grid; place-items: center; overflow: hidden; }+.napp-camera .cam-video { width: 100%; height: 100%; object-fit: contain; background: #000; }+.napp-camera .cam-video.mirror { transform: scaleX(-1); }+.napp-camera .cam-flash { position: absolute; inset: 0; background: #fff; opacity: 0; pointer-events: none; }+.napp-camera .cam-flash.go { animation: cam-flash 0.38s ease-out; }+@keyframes cam-flash { 0% { opacity: 0.9; } 100% { opacity: 0; } }+.napp-camera .cam-count { position: absolute; inset: 0; display: grid; place-items: center; font-size: 9rem; font-weight: 700; color: #fff; text-shadow: 0 4px 30px #000a; pointer-events: none; }+.napp-camera .cam-count.pop { animation: cam-pop 1s ease-out; }+@keyframes cam-pop { 0% { transform: scale(1.5); opacity: 0; } 20% { opacity: 1; } 100% { transform: scale(0.9); opacity: 0.6; } }+.napp-camera .cam-rec { position: absolute; top: 12px; left: 12px; display: inline-flex; align-items: center; gap: 8px; background: #000a; border-radius: 999px; padding: 5px 12px; font-size: 0.85rem; font-weight: 600; font-variant-numeric: tabular-nums; }+.napp-camera .cam-rec[hidden] { display: none; }+.napp-camera .cam-rec i { width: 10px; height: 10px; border-radius: 50%; background: #ff3b30; animation: cam-blink 1.1s infinite; }+.napp-camera .cam-rec small { color: #ccc; font-weight: 400; }+@keyframes cam-blink { 50% { opacity: 0.25; } }+.napp-camera .cam-state { position: absolute; inset: 0; display: none; place-items: center; background: #101012; padding: 20px; }+.napp-camera .cam-state.on { display: grid; }+.napp-camera .cam-msg { max-width: 360px; display: flex; flex-direction: column; align-items: center; gap: 8px; text-align: center; }+.napp-camera .cam-msg p, .napp-camera .cam-msg ol { margin: 0; color: #b5b5bb; font-size: 0.9rem; line-height: 1.55; }+.napp-camera .cam-msg ol { text-align: left; padding-left: 20px; }+.napp-camera .cam-ico { color: #8a8a92; }+.napp-camera .cam-btn { margin-top: 8px; border: 0; border-radius: 6px; background: var(--accent); color: #fff; padding: 9px 20px; font: inherit; font-weight: 600; cursor: pointer; }+.napp-camera .cam-btn:hover { filter: brightness(1.12); }+.napp-camera .cam-btn:active { transform: scale(0.97); }+.napp-camera .cam-spin { width: 28px; height: 28px; border-radius: 50%; border: 3px solid #ffffff30; border-top-color: var(--accent); animation: cam-rot 0.8s linear infinite; }+@keyframes cam-rot { to { transform: rotate(360deg); } }+.napp-camera .cam-bar { display: grid; grid-template-columns: 1fr auto 1fr; align-items: center; gap: 12px; padding: 10px 14px; background: var(--card); color: var(--text); border-top: 1px solid var(--bd); }+.napp-camera .cam-seg { display: inline-flex; gap: 2px; background: var(--hover); border-radius: 999px; padding: 3px; justify-self: start; }+.napp-camera .cam-seg button { display: inline-flex; align-items: center; gap: 6px; border: 0; background: transparent; color: var(--text2); border-radius: 999px; padding: 6px 12px; font: inherit; font-size: 0.85rem; cursor: pointer; }+.napp-camera .cam-seg button svg { width: 16px; height: 16px; }+.napp-camera .cam-seg button.on { background: var(--accent); color: #fff; }+.napp-camera .cam-seg button:disabled:not(.on) { opacity: 0.4; }+.napp-camera .cam-shutter { width: 58px; height: 58px; border-radius: 50%; border: 3px solid var(--text); background: transparent; position: relative; cursor: pointer; padding: 0; transition: transform 0.08s; }+.napp-camera .cam-shutter::after { content: ''; position: absolute; inset: 4px; border-radius: 50%; background: var(--text); transition: all 0.15s; }+.napp-camera .cam-shutter.video::after { background: #ff3b30; }+.napp-camera .cam-shutter.recording::after { inset: 15px; border-radius: 5px; }+.napp-camera .cam-shutter.counting::after { background: var(--accent); }+.napp-camera .cam-shutter:hover:not(:disabled) { transform: scale(1.05); }+.napp-camera .cam-shutter:active:not(:disabled) { transform: scale(0.94); }+.napp-camera .cam-shutter:disabled { opacity: 0.35; cursor: default; }+.napp-camera .cam-strip { display: flex; gap: 6px; justify-content: flex-end; overflow-x: auto; scrollbar-width: thin; }+.napp-camera .cam-thumb { flex: none; width: 46px; height: 46px; border-radius: 6px; border: 1px solid var(--bd); background: var(--hover); overflow: hidden; padding: 0; cursor: pointer; display: grid; place-items: center; color: var(--text2); }+.napp-camera .cam-thumb:hover { border-color: var(--accent); }+.napp-camera .cam-thumb img { width: 100%; height: 100%; object-fit: cover; }+.napp-camera .cam-thumb svg { width: 22px; height: 22px; }+.napp-camera .cam-hint { color: var(--text2); font-size: 0.78rem; text-align: right; }+@media (max-width: 520px) { .napp-camera .cam-bar { grid-template-columns: auto 1fr; } .napp-camera .cam-strip { grid-column: 1 / -1; grid-row: 2; justify-content: flex-start; } .napp-camera .cam-seg span { display: none; } }+@media (prefers-reduced-motion: reduce) { .napp-camera * { animation-duration: 0.01ms !important; transition: none !important; } }diff --git a/src/desktop/os/apps/camera.js b/src/desktop/os/apps/camera.jsnew file mode 100644index 000000000..e75974c2f--- /dev/null+++ b/src/desktop/os/apps/camera.js@@ -0,0 +1,390 @@+// Camera: live getUserMedia preview, photo capture and MediaRecorder video, saved into the+// virtual file system (/Pictures and /Videos). Every track is stopped when the window closes.+import './camera.css';+import { captureName, pickRecorderType, extForRecorderType, classifyMediaError, elapsedLabel } from './camera-logic.js';++const K = { mirror: 'tws:camera:mirror', fmt: 'tws:camera:format', timer: 'tws:camera:timer', device: 'tws:camera:device' };+const svg = (b, s = 20) => `<svg viewBox="0 0 24 24" width="${s}" height="${s}" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">${b}</svg>`;+const ICO = {+ photo: svg('<path d="M4 8h3l2-3h6l2 3h3v11H4z"/><circle cx="12" cy="13" r="3.5"/>'),+ video: svg('<rect x="3" y="6" width="13" height="12" rx="2"/><path d="m16 10 5-3v10l-5-3"/>'),+ mirror: svg('<path d="M12 3v18M8 7 3 12l5 5zM16 7l5 5-5 5z"/>'),+ timer: svg('<circle cx="12" cy="13" r="8"/><path d="M12 9v4l2.5 1.5M9 3h6"/>'),+ film: svg('<rect x="3" y="4" width="18" height="16" rx="2"/><path d="M8 4v16M16 4v16M3 9h5M3 15h5M16 9h5M16 15h5"/>', 28),+};++export function mount(host, ctx) {+ const { h, esc, fs, store } = ctx;+ host.classList.add('napp-camera');+ host.innerHTML = '';+ const root = h('div', 'cam');+ host.append(root);++ let stream = null;+ let devices = [];+ let deviceId = store.get(K.device) || '';+ let mode = 'photo';+ let mirror = store.get(K.mirror) !== '0';+ let fmt = store.get(K.fmt) === 'jpeg' ? 'jpeg' : 'png';+ let delay = [0, 3, 10].includes(Number(store.get(K.timer))) ? Number(store.get(K.timer)) : 0;+ let recorder = null;+ let recStart = 0;+ let recTick = 0;+ let countdown = null;+ let disposed = false;+ let starting = 0;+ const urls = new Set();++ // ---- layout ----+ const stage = h('div', 'cam-stage');+ const video = h('video', 'cam-video');+ video.autoplay = true;+ video.playsInline = true;+ video.muted = true;+ video.setAttribute('aria-label', 'Camera preview');+ const flash = h('div', 'cam-flash');+ const count = h('div', 'cam-count');+ count.setAttribute('aria-live', 'assertive');+ const rec = h('div', 'cam-rec');+ rec.hidden = true;+ const state = h('div', 'cam-state');+ stage.append(video, flash, count, rec, state);++ const top = h('div', 'cam-top');+ const devSel = h('select', 'cam-sel');+ devSel.setAttribute('aria-label', 'Camera');+ const mirrorB = h('button', 'cam-tb', ICO.mirror);+ mirrorB.type = 'button';+ mirrorB.title = 'Mirror preview and photos';+ mirrorB.setAttribute('aria-label', 'Mirror');+ const timerB = h('button', 'cam-tb');+ timerB.type = 'button';+ const fmtB = h('button', 'cam-tb txt');+ fmtB.type = 'button';+ fmtB.title = 'Photo format';+ top.append(devSel, h('span', 'cam-grow'), timerB, mirrorB, fmtB);++ const bar = h('div', 'cam-bar');+ const modeSeg = h('div', 'cam-seg');+ modeSeg.setAttribute('role', 'group');+ modeSeg.setAttribute('aria-label', 'Capture mode');+ const photoB = h('button', '', `${ICO.photo}<span>Photo</span>`);+ const videoB = h('button', '', `${ICO.video}<span>Video</span>`);+ [photoB, videoB].forEach((b) => (b.type = 'button'));+ modeSeg.append(photoB, videoB);+ const shutter = h('button', 'cam-shutter');+ shutter.type = 'button';+ const strip = h('div', 'cam-strip');+ strip.setAttribute('aria-label', 'Recent captures');+ bar.append(modeSeg, shutter, strip);+ root.append(top, stage, bar);++ // ---- ui sync ----+ function sync() {+ mirrorB.classList.toggle('on', mirror);+ mirrorB.setAttribute('aria-pressed', String(mirror));+ video.classList.toggle('mirror', mirror);+ timerB.innerHTML = `${ICO.timer}<span>${delay ? `${delay}s` : 'Off'}</span>`;+ timerB.title = 'Countdown timer';+ timerB.setAttribute('aria-label', `Countdown ${delay ? `${delay} seconds` : 'off'}`);+ fmtB.textContent = fmt.toUpperCase();+ fmtB.hidden = mode !== 'photo';+ photoB.classList.toggle('on', mode === 'photo');+ videoB.classList.toggle('on', mode === 'video');+ photoB.setAttribute('aria-pressed', String(mode === 'photo'));+ videoB.setAttribute('aria-pressed', String(mode === 'video'));+ const live = !!stream;+ shutter.disabled = !live;+ shutter.className = `cam-shutter ${mode}${recorder ? ' recording' : ''}${countdown ? ' counting' : ''}`;+ shutter.setAttribute('aria-label', countdown ? 'Cancel countdown' : mode === 'photo' ? 'Take photo' : recorder ? 'Stop recording' : 'Start recording');+ shutter.title = shutter.getAttribute('aria-label');+ photoB.disabled = videoB.disabled = !!recorder;+ }++ // ---- stream ----+ const stopStream = () => {+ stream?.getTracks().forEach((t) => t.stop());+ stream = null;+ video.srcObject = null;+ };+ async function refreshDevices() {+ try {+ devices = (await navigator.mediaDevices.enumerateDevices()).filter((d) => d.kind === 'videoinput');+ } catch {+ devices = [];+ }+ devSel.replaceChildren(+ ...devices.map((d, i) => {+ const o = h('option');+ o.value = d.deviceId;+ o.textContent = d.label || `Camera ${i + 1}`;+ return o;+ }),+ );+ const active = stream?.getVideoTracks()[0]?.getSettings().deviceId;+ if (active) devSel.value = active;+ devSel.hidden = devices.length < 2;+ }+ function showState(info) {+ state.replaceChildren();+ if (!info) {+ state.classList.remove('on');+ return;+ }+ state.classList.add('on');+ const box = h('div', 'cam-msg');+ if (info.loading) {+ box.innerHTML = '<div class="cam-spin" aria-hidden="true"></div><b>Starting camera</b><p>If your browser asks, choose Allow to use your camera.</p>';+ } else {+ box.innerHTML = `<div class="cam-ico">${ICO.photo.replace('width="20" height="20"', 'width="40" height="40"')}</div><b>${esc(info.title)}</b><ol>${info.steps.map((s) => `<li>${esc(s)}</li>`).join('')}</ol>`;+ const retry = h('button', 'cam-btn', 'Try again');+ retry.type = 'button';+ retry.addEventListener('click', () => start());+ box.append(retry);+ }+ state.append(box);+ }+ async function start(id = deviceId) {+ const mine = ++starting;+ stopStream();+ if (!window.isSecureContext) return showState(classifyMediaError(null, { secure: false })), sync();+ if (!navigator.mediaDevices?.getUserMedia) return showState(classifyMediaError(null, { hasMediaDevices: false })), sync();+ showState({ loading: true });+ sync();+ try {+ const base = { width: { ideal: 1920 }, height: { ideal: 1080 } };+ let s;+ try {+ s = await navigator.mediaDevices.getUserMedia({ video: id ? { ...base, deviceId: { exact: id } } : { ...base, facingMode: 'user' }, audio: false });+ } catch (err) {+ if (id && (err.name === 'OverconstrainedError' || err.name === 'NotFoundError')) s = await navigator.mediaDevices.getUserMedia({ video: base, audio: false });+ else throw err;+ }+ if (mine !== starting || disposed) {+ s.getTracks().forEach((t) => t.stop());+ return;+ }+ stream = s;+ video.srcObject = s;+ await video.play().catch(() => {});+ deviceId = s.getVideoTracks()[0]?.getSettings().deviceId || id;+ if (deviceId) store.set(K.device, deviceId);+ s.getVideoTracks()[0]?.addEventListener('ended', () => {+ if (stream === s && !disposed) {+ stream = null;+ showState({ title: 'The camera was disconnected', steps: ['Reconnect the camera, or pick another one.', 'Choose Try again below.'] });+ sync();+ }+ });+ showState(null);+ await refreshDevices();+ } catch (err) {+ if (mine !== starting || disposed) return;+ showState(classifyMediaError(err));+ }+ sync();+ }++ // ---- capture ----+ async function saveBlob(dir, name, blob, mime) {+ const unique = await fs.uniqueName(dir, name);+ const path = fs.join(dir, unique);+ await fs.write(path, blob, { mime });+ return path;+ }+ function doFlash() {+ flash.classList.remove('go');+ void flash.offsetWidth;+ flash.classList.add('go');+ }+ async function takePhoto() {+ if (!stream || !video.videoWidth) return ctx.toast('The camera is not ready yet');+ const c = document.createElement('canvas');+ c.width = video.videoWidth;+ c.height = video.videoHeight;+ const g = c.getContext('2d');+ if (mirror) {+ g.translate(c.width, 0);+ g.scale(-1, 1);+ }+ g.drawImage(video, 0, 0);+ doFlash();+ const type = fmt === 'jpeg' ? 'image/jpeg' : 'image/png';+ const blob = await new Promise((res) => c.toBlob(res, type, 0.92));+ if (!blob) return ctx.toast('Could not encode the photo');+ try {+ const path = await saveBlob('/Pictures', captureName(new Date(), fmt === 'jpeg' ? 'jpg' : 'png'), blob, type);+ ctx.toast(`Saved ${fs.nameOf(path)} to Pictures`);+ } catch (err) {+ ctx.toast(`Could not save the photo: ${err.message}`);+ }+ }+ function runCountdown(done) {+ let n = delay;+ const tick = () => {+ if (!countdown) return;+ if (n <= 0) {+ count.textContent = '';+ countdown = null;+ sync();+ done();+ return;+ }+ count.textContent = String(n);+ count.classList.remove('pop');+ void count.offsetWidth;+ count.classList.add('pop');+ n--;+ countdown = setTimeout(tick, 1000);+ };+ countdown = true;+ sync();+ tick();+ }+ const cancelCountdown = () => {+ if (countdown && countdown !== true) clearTimeout(countdown);+ countdown = null;+ count.textContent = '';+ sync();+ };+ async function startRecording() {+ const type = pickRecorderType((t) => window.MediaRecorder?.isTypeSupported?.(t));+ if (!window.MediaRecorder || !type) return ctx.toast('This browser cannot record video');+ const tracks = [...stream.getVideoTracks()];+ let micOk = true;+ try {+ const mic = await navigator.mediaDevices.getUserMedia({ audio: true });+ tracks.push(...mic.getAudioTracks());+ } catch {+ micOk = false;+ }+ const rs = new MediaRecorder(new MediaStream(tracks), { mimeType: type });+ const chunks = [];+ rs.ondataavailable = (e) => e.data.size && chunks.push(e.data);+ rs.onstop = async () => {+ clearInterval(recTick);+ tracks.filter((t) => t.kind === 'audio').forEach((t) => t.stop());+ rec.hidden = true;+ recorder = null;+ sync();+ if (!chunks.length) return;+ const blob = new Blob(chunks, { type: type.split(';')[0] });+ try {+ const path = await saveBlob('/Videos', captureName(new Date(recStart), extForRecorderType(type)), blob, blob.type);+ ctx.toast(`Saved ${fs.nameOf(path)} to Videos`);+ } catch (err) {+ ctx.toast(`Could not save the video: ${err.message}`);+ }+ };+ rs.start(1000);+ recorder = rs;+ recStart = Date.now();+ rec.hidden = false;+ const draw = () => (rec.innerHTML = `<i></i>REC ${elapsedLabel(Date.now() - recStart)}${micOk ? '' : ' <small>no microphone</small>'}`);+ draw();+ recTick = setInterval(draw, 500);+ if (!micOk) ctx.toast('Microphone unavailable, recording video only');+ sync();+ }+ function stopRecording() {+ if (recorder && recorder.state !== 'inactive') recorder.stop();+ }+ function onShutter() {+ if (countdown) return cancelCountdown();+ if (mode === 'video') {+ if (recorder) return stopRecording();+ return delay ? runCountdown(startRecording) : startRecording();+ }+ return delay ? runCountdown(takePhoto) : takePhoto();+ }++ // ---- recents ----+ async function loadStrip() {+ const found = [];+ for (const dir of ['/Pictures', '/Videos']) {+ try {+ found.push(...(await fs.list(dir)).filter((n) => n.type === 'file' && n.name.startsWith('Camera ')));+ } catch {+ /* folder missing: nothing to show yet */+ }+ }+ if (disposed) return;+ found.sort((a, b) => b.mtime - a.mtime);+ urls.forEach((u) => URL.revokeObjectURL(u));+ urls.clear();+ const items = await Promise.all(+ found.slice(0, 12).map(async (n) => {+ const b = h('button', 'cam-thumb');+ b.type = 'button';+ b.title = n.name;+ b.setAttribute('aria-label', `Open ${n.name}`);+ if (fs.kindOf(n.name) === 'image') {+ const u = await fs.urlFor(n.path);+ if (u) {+ urls.add(u);+ b.innerHTML = `<img alt="" src="${u}">`;+ }+ } else b.innerHTML = ICO.film;+ b.addEventListener('click', () => ctx.openPath(n.path));+ return b;+ }),+ );+ if (disposed) return;+ strip.replaceChildren(...(items.length ? items : [h('span', 'cam-hint', 'Photos and videos you take appear here')]));+ }+ const offFs = fs.subscribe((paths) => {+ if (!paths || paths.some((p) => p === '/Pictures' || p === '/Videos')) loadStrip();+ });++ // ---- events ----+ devSel.addEventListener('change', () => {+ deviceId = devSel.value;+ start(deviceId);+ });+ mirrorB.addEventListener('click', () => {+ mirror = !mirror;+ store.set(K.mirror, mirror ? '1' : '0');+ sync();+ });+ timerB.addEventListener('click', () => {+ delay = delay === 0 ? 3 : delay === 3 ? 10 : 0;+ store.set(K.timer, String(delay));+ sync();+ });+ fmtB.addEventListener('click', () => {+ fmt = fmt === 'png' ? 'jpeg' : 'png';+ store.set(K.fmt, fmt);+ sync();+ });+ photoB.addEventListener('click', () => ((mode = 'photo'), sync()));+ videoB.addEventListener('click', () => ((mode = 'video'), sync()));+ shutter.addEventListener('click', onShutter);+ root.tabIndex = 0;+ root.addEventListener('keydown', (e) => {+ if (e.target.closest('select')) return;+ if (e.key === ' ' || e.key === 'Enter') {+ if (e.target.closest('button')) return;+ e.preventDefault();+ if (!shutter.disabled) onShutter();+ } else if (e.key === 'Escape') cancelCountdown();+ });+ const onDeviceChange = () => refreshDevices();+ navigator.mediaDevices?.addEventListener?.('devicechange', onDeviceChange);++ sync();+ loadStrip();+ start();++ return () => {+ disposed = true;+ starting++;+ navigator.mediaDevices?.removeEventListener?.('devicechange', onDeviceChange);+ offFs();+ cancelCountdown();+ clearInterval(recTick);+ if (recorder && recorder.state !== 'inactive') recorder.stop();+ stopStream();+ urls.forEach((u) => URL.revokeObjectURL(u));+ urls.clear();+ };+}diff --git a/src/desktop/os/apps/clock.css b/src/desktop/os/apps/clock.cssnew file mode 100644index 000000000..d97154350--- /dev/null+++ b/src/desktop/os/apps/clock.css@@ -0,0 +1,119 @@+.napp-clock { display: flex; flex-direction: column; min-height: 0; color: var(--text); background: var(--card); }+.napp-clock .clk { position: relative; display: flex; flex-direction: column; flex: 1; min-height: 0; }+.napp-clock .clk-tabs { display: flex; gap: 2px; padding: 8px 10px 0; border-bottom: 1px solid var(--bd); overflow-x: auto; scrollbar-width: none; }+.napp-clock .clk-tab { border: 0; background: transparent; color: var(--text2); font: inherit; font-size: 0.92rem; padding: 8px 14px; border-radius: 6px 6px 0 0; cursor: pointer; position: relative; white-space: nowrap; }+.napp-clock .clk-tab:hover { background: var(--hover); color: var(--text); }+.napp-clock .clk-tab.on { color: var(--text); font-weight: 600; }+.napp-clock .clk-tab.on::after { content: ''; position: absolute; left: 14px; right: 14px; bottom: -1px; height: 3px; border-radius: 3px; background: var(--accent); }+.napp-clock button:focus-visible, .napp-clock input:focus-visible { outline: 2px solid var(--accent); outline-offset: 1px; }+.napp-clock .clk-panel { flex: 1; min-height: 0; overflow: auto; padding: 14px; }+.napp-clock h2 { margin: 0; font-size: 1.25rem; font-weight: 600; }+.napp-clock small { color: var(--text2); }+.napp-clock .clk-head { display: flex; align-items: center; justify-content: space-between; gap: 12px; margin-bottom: 12px; }+.napp-clock .clk-head small { display: block; margin-top: 2px; }+.napp-clock .clk-btn { display: inline-flex; align-items: center; gap: 6px; border: 1px solid var(--bd); background: var(--hover); color: var(--text); font: inherit; font-size: 0.9rem; padding: 7px 14px; border-radius: 6px; cursor: pointer; transition: background 0.1s, transform 0.06s; }+.napp-clock .clk-btn:hover:not(:disabled) { background: var(--hover-b, var(--hover)); }+.napp-clock .clk-btn:active:not(:disabled) { transform: scale(0.97); }+.napp-clock .clk-btn:disabled { opacity: 0.4; cursor: default; }+.napp-clock .clk-btn.primary { background: var(--accent); border-color: var(--accent); color: #fff; font-weight: 600; }+.napp-clock .clk-btn.primary:hover:not(:disabled) { background: var(--accent); filter: brightness(1.1); }+.napp-clock .clk-btn.round { width: 40px; height: 40px; padding: 0; justify-content: center; border-radius: 50%; }+.napp-clock .clk-btn.big { min-width: 130px; justify-content: center; padding: 11px 22px; border-radius: 999px; font-size: 1rem; }+.napp-clock .clk-x { display: grid; place-items: center; width: 32px; height: 32px; border: 0; border-radius: 6px; background: transparent; color: var(--text2); cursor: pointer; }+.napp-clock .clk-x:hover { background: var(--hover); color: var(--text); }+.napp-clock .clk-input { background: var(--hover-half, var(--hover)); color: var(--text); border: 1px solid var(--bd); border-radius: 6px; padding: 8px 10px; font: inherit; font-size: 0.92rem; width: 100%; box-sizing: border-box; }+.napp-clock .clk-empty { color: var(--text2); text-align: center; padding: 18px 8px; margin: 0; font-size: 0.9rem; line-height: 1.5; }+.napp-clock .clk-emptybox { display: flex; flex-direction: column; align-items: center; gap: 4px; text-align: center; color: var(--text2); padding: 28px 16px; border: 1px dashed var(--bd); border-radius: 10px; }+.napp-clock .clk-emptybox b { color: var(--text); }+.napp-clock .clk-emptybox p { margin: 0; max-width: 340px; line-height: 1.5; font-size: 0.9rem; }+.napp-clock .clk-emptybox .ico { opacity: 0.4; }+/* ring */+.napp-clock .clk-ringbox { display: none; flex-direction: column; gap: 6px; padding: 8px 10px; background: var(--accent); }+.napp-clock .clk-ringbox.on { display: flex; }+.napp-clock .clk-ring { display: flex; align-items: center; gap: 10px; color: #fff; }+.napp-clock .clk-ring .ico svg { width: 24px; height: 24px; animation: clk-shake 0.6s infinite; transform-origin: 50% 0; }+.napp-clock .clk-ring div { flex: 1; display: flex; flex-direction: column; min-width: 0; }+.napp-clock .clk-ring b { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }+.napp-clock .clk-ring small { color: #ffffffcc; }+.napp-clock .clk-ring .clk-btn { background: #ffffff30; border-color: #ffffff50; color: #fff; }+.napp-clock .clk-ring .clk-btn.primary { background: #fff; color: #111; }+@keyframes clk-shake { 0%, 100% { transform: rotate(0); } 25% { transform: rotate(14deg); } 75% { transform: rotate(-14deg); } }+/* world */+.napp-clock .clk-hero { display: flex; align-items: center; gap: 18px; padding: 8px 4px 14px; }+.napp-clock .clk-face { width: 120px; height: 120px; flex: none; }+.napp-clock .clk-face .rim { fill: var(--hover); stroke: var(--bd); }+.napp-clock .clk-face line { stroke: var(--text2); stroke-width: 0.8; stroke-linecap: round; }+.napp-clock .clk-face line.big { stroke: var(--text); stroke-width: 1.6; }+.napp-clock .clk-face .hh, .napp-clock .clk-face .mh { stroke: var(--text); stroke-width: 3; }+.napp-clock .clk-face .mh { stroke-width: 2.2; }+.napp-clock .clk-face .sh { stroke: var(--accent); stroke-width: 1.1; }+.napp-clock .clk-face .pin { fill: var(--accent); }+.napp-clock .clk-hero-t .big { font-size: 2.6rem; font-weight: 600; font-variant-numeric: tabular-nums; line-height: 1.1; }+.napp-clock .clk-hero-t .sub { margin-top: 2px; }+.napp-clock .clk-hero-t .dim { color: var(--text2); font-size: 0.85rem; }+.napp-clock .clk-add { position: relative; margin-bottom: 10px; }+.napp-clock .clk-sug { position: absolute; z-index: 5; left: 0; right: 0; top: calc(100% + 4px); margin: 0; padding: 4px; list-style: none; background: var(--card); border: 1px solid var(--bd); border-radius: 8px; box-shadow: var(--shadow-md); }+.napp-clock .clk-sug[hidden] { display: none; }+.napp-clock .clk-sug li { display: flex; justify-content: space-between; gap: 10px; padding: 7px 10px; border-radius: 6px; cursor: pointer; font-size: 0.9rem; }+.napp-clock .clk-sug li span { color: var(--text2); font-size: 0.8rem; }+.napp-clock .clk-sug li.on, .napp-clock .clk-sug li:hover { background: var(--hover); }+.napp-clock .clk-sug li.none { color: var(--text2); cursor: default; }+.napp-clock .clk-zones { display: grid; grid-template-columns: repeat(auto-fill, minmax(230px, 1fr)); gap: 8px; }+.napp-clock .clk-zone { position: relative; display: grid; grid-template-columns: 1fr auto; gap: 2px 10px; padding: 12px 40px 12px 14px; border: 1px solid var(--bd); border-radius: 10px; background: var(--hover-half, var(--hover)); }+.napp-clock .clk-zone.night { background: linear-gradient(135deg, var(--hover-half, var(--hover)), #1b254a30); }+.napp-clock .clk-zone .l { display: flex; flex-direction: column; min-width: 0; }+.napp-clock .clk-zone .l b { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }+.napp-clock .clk-zone .r { text-align: right; display: flex; flex-direction: column; }+.napp-clock .clk-zone .t { font-size: 1.5rem; font-weight: 600; font-variant-numeric: tabular-nums; }+.napp-clock .clk-zone .dn { position: absolute; right: 12px; bottom: 12px; color: var(--text2); }+.napp-clock .clk-zone .clk-x { position: absolute; top: 4px; right: 4px; width: 26px; height: 26px; opacity: 0; transition: opacity 0.12s; }+.napp-clock .clk-zone:hover .clk-x, .napp-clock .clk-zone .clk-x:focus-visible { opacity: 1; }+/* alarms */+.napp-clock .clk-form { display: grid; gap: 10px; padding: 14px; border: 1px solid var(--bd); border-radius: 10px; margin-bottom: 12px; background: var(--hover-half, var(--hover)); }+.napp-clock .clk-form label, .napp-clock .clk-form legend { display: grid; gap: 4px; font-size: 0.82rem; color: var(--text2); }+.napp-clock .clk-form fieldset { border: 0; margin: 0; padding: 0; }+.napp-clock .clk-form .days { display: flex; gap: 6px; margin-top: 6px; }+.napp-clock .clk-day { width: 34px; height: 34px; border-radius: 50%; border: 1px solid var(--bd); background: transparent; color: var(--text); font: inherit; cursor: pointer; }+.napp-clock .clk-day:hover { background: var(--hover); }+.napp-clock .clk-day.on { background: var(--accent); border-color: var(--accent); color: #fff; }+.napp-clock .clk-actions { display: flex; justify-content: flex-end; gap: 8px; }+.napp-clock .clk-actions.center { justify-content: center; }+.napp-clock .clk-alist { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 6px; }+.napp-clock .clk-alarm { display: grid; grid-template-columns: auto 1fr auto auto auto; align-items: center; gap: 10px; padding: 12px 12px 12px 16px; border: 1px solid var(--bd); border-radius: 10px; background: var(--hover-half, var(--hover)); }+.napp-clock .clk-alarm.off .tm, .napp-clock .clk-alarm.off .inf { opacity: 0.5; }+.napp-clock .clk-alarm .tm span { font-size: 1.9rem; font-weight: 600; font-variant-numeric: tabular-nums; line-height: 1; }+.napp-clock .clk-alarm .tm small { display: block; }+.napp-clock .clk-alarm .inf { display: flex; flex-direction: column; min-width: 0; }+.napp-clock .clk-alarm .inf b { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }+.napp-clock .clk-switch { width: 42px; height: 22px; border-radius: 11px; border: 1px solid var(--text2); background: transparent; position: relative; cursor: pointer; padding: 0; transition: background 0.15s; }+.napp-clock .clk-switch::after { content: ''; position: absolute; top: 3px; left: 3px; width: 14px; height: 14px; border-radius: 50%; background: var(--text2); transition: transform 0.15s, background 0.15s; }+.napp-clock .clk-switch.on { background: var(--accent); border-color: var(--accent); }+.napp-clock .clk-switch.on::after { transform: translateX(20px); background: #fff; }+/* timers */+.napp-clock .clk-tform { display: grid; gap: 8px; margin-bottom: 14px; }+.napp-clock .clk-tform .clk-btn { justify-self: end; }+.napp-clock .clk-chips { display: flex; flex-wrap: wrap; gap: 6px; }+.napp-clock .clk-chip { border: 1px solid var(--bd); background: transparent; color: var(--text); border-radius: 999px; padding: 5px 12px; font: inherit; font-size: 0.85rem; cursor: pointer; }+.napp-clock .clk-chip:hover { background: var(--hover); border-color: var(--accent); }+.napp-clock .clk-tlist { display: grid; gap: 8px; }+.napp-clock .clk-timer { display: grid; grid-template-columns: 52px 1fr auto auto auto; gap: 10px; align-items: center; padding: 10px 12px; border: 1px solid var(--bd); border-radius: 10px; background: var(--hover-half, var(--hover)); }+.napp-clock .clk-timer .ring { width: 52px; height: 52px; transform: rotate(-90deg); }+.napp-clock .clk-timer .ring circle { fill: none; stroke-width: 3.5; }+.napp-clock .clk-timer .ring .bg { stroke: var(--bd); }+.napp-clock .clk-timer .ring .fg { stroke: var(--accent); stroke-linecap: round; transition: stroke-dashoffset 0.4s linear; }+.napp-clock .clk-timer .left { font-size: 1.8rem; font-weight: 600; font-variant-numeric: tabular-nums; line-height: 1.1; }+.napp-clock .clk-timer.paused .left { opacity: 0.55; }+.napp-clock .clk-timer.done { border-color: var(--accent); }+.napp-clock .clk-timer .inf b { font-weight: 500; color: var(--text2); font-size: 0.85rem; }+/* stopwatch */+.napp-clock .clk-sw { display: flex; flex-direction: column; align-items: center; gap: 18px; padding-top: 14px; }+.napp-clock .clk-swbig { font-size: 4rem; font-weight: 300; font-variant-numeric: tabular-nums; letter-spacing: 1px; }+.napp-clock .clk-laps { align-self: stretch; }+.napp-clock .clk-laplist { list-style: none; margin: 0; padding: 0; }+.napp-clock .clk-laplist li { display: grid; grid-template-columns: 1fr auto auto; gap: 18px; padding: 9px 8px; border-bottom: 1px solid var(--bd); font-variant-numeric: tabular-nums; }+.napp-clock .clk-laplist li span { color: var(--text2); }+.napp-clock .clk-laplist li.fast b { color: #3fb950; }+.napp-clock .clk-laplist li.slow b { color: #e5484d; }+.napp-clock .clk-laplist small { min-width: 80px; text-align: right; }+@media (max-width: 460px) { .napp-clock .clk-hero { flex-direction: column; text-align: center; } .napp-clock .clk-swbig { font-size: 3rem; } }+@media (prefers-reduced-motion: reduce) { .napp-clock * { animation: none !important; transition: none !important; } }diff --git a/src/desktop/os/apps/clock.js b/src/desktop/os/apps/clock.jsnew file mode 100644index 000000000..0e824b21b--- /dev/null+++ b/src/desktop/os/apps/clock.js@@ -0,0 +1,696 @@+// Clock: world clocks, alarms, timers and a stopwatch.+//+// Alarms and timers are driven by a module-level engine (alarm-logic.js scheduler) that starts the+// first time Clock opens and keeps running after the window closes. It runs while the three.ws+// page is open; it cannot wake a closed tab. A ring plays a synthesized WebAudio tone, raises a+// notification and reopens Clock so it can be dismissed or snoozed.+import './clock.css';+import { DAYS, nextAlarmTime, repeatLabel, untilLabel, formatDuration, parseDuration, stopwatch, lapExtremes, zoneOffsetMinutes, offsetLabel, relativeOffset, isValidZone, isDaytime, subscribeTick, checkAlarms, checkTimers } from './alarm-logic.js';++const K = { zones: 'tws:clock:zones', alarms: 'tws:clock:alarms', timers: 'tws:clock:timers', sw: 'tws:clock:stopwatch', tab: 'tws:clock:tab' };+const SNOOZE_MS = 10 * 60 * 1000;+const PRESETS = [['1 min', 60], ['3 min', 180], ['5 min', 300], ['10 min', 600], ['15 min', 900], ['30 min', 1800], ['1 hour', 3600]];+const LOCAL = Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC';++const uid = () => Math.random().toString(36).slice(2, 9);+const load = (store, k, d) => {+ try {+ const v = JSON.parse(store.get(k));+ return v ?? d;+ } catch {+ return d;+ }+};++// ---------------- engine (module level, outlives the window) ----------------++const engine = {+ ctx: null,+ alarms: [],+ timers: [],+ snoozes: [],+ ringing: [],+ lastNow: Date.now(),+ listeners: new Set(),+ audio: null,+ ringTimer: null,+ ringStop: null,+ started: false,+};++function persist() {+ engine.ctx.store.set(K.alarms, JSON.stringify(engine.alarms));+ engine.ctx.store.set(K.timers, JSON.stringify(engine.timers));+}+const changed = () => engine.listeners.forEach((fn) => fn());++function ensureAudio() {+ try {+ const AC = window.AudioContext || window.webkitAudioContext;+ if (!AC) return null;+ engine.audio ||= new AC();+ if (engine.audio.state === 'suspended') engine.audio.resume().catch(() => {});+ return engine.audio;+ } catch {+ return null;+ }+}++/** One ring cycle: four short beeps. */+function playRingCycle() {+ const ac = ensureAudio();+ if (!ac || ac.state !== 'running') return;+ const t0 = ac.currentTime + 0.02;+ for (let i = 0; i < 4; i++) {+ const t = t0 + i * 0.22;+ const osc = ac.createOscillator();+ const gain = ac.createGain();+ osc.type = 'sine';+ osc.frequency.value = i % 2 ? 988 : 784;+ gain.gain.setValueAtTime(0.0001, t);+ gain.gain.exponentialRampToValueAtTime(0.35, t + 0.02);+ gain.gain.exponentialRampToValueAtTime(0.0001, t + 0.18);+ osc.connect(gain).connect(ac.destination);+ osc.start(t);+ osc.stop(t + 0.2);+ }+}++function startRinging() {+ if (engine.ringTimer) return;+ playRingCycle();+ engine.ringTimer = setInterval(playRingCycle, 1400);+ engine.ringStop = setTimeout(() => dismissAll(), 90_000);+}+function stopRinging() {+ clearInterval(engine.ringTimer);+ clearTimeout(engine.ringStop);+ engine.ringTimer = engine.ringStop = null;+}++function ring(kind, item) {+ const label = item.label || (kind === 'alarm' ? 'Alarm' : 'Timer');+ engine.ringing.push({ rid: uid(), kind, id: item.id, label, h: item.h, m: item.m });+ const when = kind === 'alarm' && item.h != null ? `${String(item.h).padStart(2, '0')}:${String(item.m).padStart(2, '0')}` : formatDuration(item.total || 0);+ engine.ctx.notify({ title: kind === 'alarm' ? `Alarm ${when}` : 'Timer finished', body: label, app: 'clock' });+ engine.ctx.toast(kind === 'alarm' ? `Alarm: ${label}` : `Timer done: ${label}`);+ startRinging();+ engine.ctx.launchId('clock');+ changed();+}+function dismiss(rid) {+ engine.ringing = engine.ringing.filter((r) => r.rid !== rid);+ if (!engine.ringing.length) stopRinging();+ changed();+}+function dismissAll() {+ engine.ringing = [];+ stopRinging();+ changed();+}+function snooze(rid) {+ const r = engine.ringing.find((x) => x.rid === rid);+ if (!r) return;+ engine.snoozes.push({ id: uid(), label: r.label, endsAt: Date.now() + SNOOZE_MS });+ engine.ctx.toast(`Snoozed for ${SNOOZE_MS / 60000} minutes`);+ dismiss(rid);+}++function onTick(now) {+ let dirty = false;+ const a = checkAlarms(engine.alarms, now, engine.lastNow);+ engine.lastNow = now;+ if (a.fired.length) {+ engine.alarms = a.alarms;+ dirty = true;+ a.fired.forEach((x) => ring('alarm', x));+ }+ const t = checkTimers(engine.timers, now);+ if (t.fired.length) {+ engine.timers = t.timers;+ dirty = true;+ t.fired.forEach((x) => ring('timer', x));+ }+ const due = engine.snoozes.filter((s) => s.endsAt <= now);+ if (due.length) {+ engine.snoozes = engine.snoozes.filter((s) => s.endsAt > now);+ due.forEach((s) => ring('alarm', { id: s.id, label: `${s.label} (snoozed)` }));+ }+ if (dirty) persist();+}++function startEngine(ctx) {+ if (engine.started) {+ engine.ctx = ctx;+ return;+ }+ engine.started = true;+ engine.ctx = ctx;+ engine.alarms = load(ctx.store, K.alarms, []).filter((a) => a && Number.isInteger(a.h) && Number.isInteger(a.m));+ engine.timers = load(ctx.store, K.timers, []).filter((t) => t && t.total > 0);+ engine.lastNow = Date.now();+ // Browsers only allow audio after a gesture, so unlock it on the first interaction anywhere.+ const unlock = () => {+ ensureAudio();+ document.removeEventListener('pointerdown', unlock, true);+ document.removeEventListener('keydown', unlock, true);+ };+ document.addEventListener('pointerdown', unlock, true);+ document.addEventListener('keydown', unlock, true);+ subscribeTick(onTick);+ onTick(Date.now());+}++// ---------------- svg helpers ----------------++const svg = (body, size = 16, extra = '') => `<svg viewBox="0 0 24 24" width="${size}" height="${size}" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" ${extra}>${body}</svg>`;+const ICO = {+ play: svg('<path d="M7 4.5v15l12-7.5z" fill="currentColor"/>'),+ pause: svg('<path d="M8 5v14M16 5v14" stroke-width="3"/>'),+ reset: svg('<path d="M4 12a8 8 0 1 0 2.5-5.8M4 4v5h5"/>'),+ trash: svg('<path d="M4 7h16M10 7V4h4v3M6 7l1 13h10l1-13"/>'),+ plus: svg('<path d="M12 5v14M5 12h14"/>'),+ flag: svg('<path d="M6 21V4M6 5h12l-2.5 4L18 13H6"/>'),+ sun: svg('<circle cx="12" cy="12" r="4"/><path d="M12 2v2M12 20v2M2 12h2M20 12h2M4.9 4.9l1.4 1.4M17.7 17.7l1.4 1.4M19.1 4.9l-1.4 1.4M6.3 17.7l-1.4 1.4"/>', 14),+ moon: svg('<path d="M20 14.5A8 8 0 1 1 9.5 4 6.5 6.5 0 0 0 20 14.5z"/>', 14),+ edit: svg('<path d="M4 20h4L19 9l-4-4L4 16zM13.5 6.5l4 4"/>'),+ bell: svg('<path d="M6 17V11a6 6 0 0 1 12 0v6l1.5 2h-15zM10 21h4"/>', 40),+};++const hhmm = (h, m) => `${String(h).padStart(2, '0')}:${String(m).padStart(2, '0')}`;+const fmtTime12 = (h, m) => {+ const p = h >= 12 ? 'PM' : 'AM';+ return { t: `${h % 12 || 12}:${String(m).padStart(2, '0')}`, p };+};+const cityOf = (z) => (z.split('/').pop() || z).replace(/_/g, ' ');++function analogSvg() {+ let ticks = '';+ for (let i = 0; i < 60; i++) {+ const a = (i * 6 * Math.PI) / 180;+ const r1 = i % 5 === 0 ? 40 : 44;+ ticks += `<line x1="${50 + Math.sin(a) * r1}" y1="${50 - Math.cos(a) * r1}" x2="${50 + Math.sin(a) * 47}" y2="${50 - Math.cos(a) * 47}" class="${i % 5 === 0 ? 'big' : ''}"/>`;+ }+ return `<svg viewBox="0 0 100 100" class="clk-face" role="img" aria-label="Analog clock"><circle cx="50" cy="50" r="49" class="rim"/>${ticks}<line class="hh" x1="50" y1="50" x2="50" y2="28"/><line class="mh" x1="50" y1="50" x2="50" y2="16"/><line class="sh" x1="50" y1="56" x2="50" y2="12"/><circle cx="50" cy="50" r="2.6" class="pin"/></svg>`;+}++// ---------------- app ----------------++export function mount(host, ctx) {+ startEngine(ctx);+ const { h, esc, store } = ctx;+ host.classList.add('napp-clock');+ host.innerHTML = '';+ const root = h('div', 'clk');+ const tabs = h('div', 'clk-tabs');+ tabs.setAttribute('role', 'tablist');+ const panel = h('div', 'clk-panel');+ panel.setAttribute('role', 'tabpanel');+ const ringBox = h('div', 'clk-ringbox');+ ringBox.setAttribute('role', 'alert');+ root.append(ringBox, tabs, panel);+ host.append(root);++ const TAB_DEFS = [['world', 'World clock'], ['alarms', 'Alarms'], ['timer', 'Timer'], ['stopwatch', 'Stopwatch']];+ let tab = store.get(K.tab);+ if (!TAB_DEFS.some(([id]) => id === tab)) tab = 'world';+ let zones = load(store, K.zones, null);+ if (!Array.isArray(zones)) zones = ['Europe/London', 'America/New_York', 'Asia/Tokyo'];+ zones = zones.filter((z) => typeof z === 'string' && isValidZone(z));+ let sw = { ...stopwatch.fresh(), ...load(store, K.sw, {}) };+ if (!Array.isArray(sw.laps)) sw.laps = [];+ let editing = null; // alarm id, 'new', or null+ let rafId = 0;+ const tickers = new Set();++ for (const [id, label] of TAB_DEFS) {+ const b = h('button', 'clk-tab', label);+ b.type = 'button';+ b.id = `clk-tab-${id}`;+ b.setAttribute('role', 'tab');+ b.addEventListener('click', () => setTab(id));+ b.addEventListener('keydown', (e) => {+ const i = TAB_DEFS.findIndex(([x]) => x === tab);+ if (e.key === 'ArrowRight') setTab(TAB_DEFS[(i + 1) % 4][0], true);+ else if (e.key === 'ArrowLeft') setTab(TAB_DEFS[(i + 3) % 4][0], true);+ else return;+ e.preventDefault();+ });+ tabs.append(b);+ }+ function setTab(id, focus) {+ tab = id;+ store.set(K.tab, id);+ editing = null;+ for (const b of tabs.children) {+ const on = b.id === `clk-tab-${id}`;+ b.classList.toggle('on', on);+ b.setAttribute('aria-selected', String(on));+ b.tabIndex = on ? 0 : -1;+ if (on && focus) b.focus();+ }+ panel.setAttribute('aria-labelledby', `clk-tab-${id}`);+ render();+ }++ function render() {+ tickers.clear();+ cancelAnimationFrame(rafId);+ panel.replaceChildren();+ ({ world: renderWorld, alarms: renderAlarms, timer: renderTimers, stopwatch: renderStopwatch })[tab]();+ }++ // ---- ring banners (any tab) ----+ function renderRing() {+ ringBox.replaceChildren(+ ...engine.ringing.map((r) => {+ const row = h('div', 'clk-ring');+ row.innerHTML = `<span class="ico">${ICO.bell}</span><div><b>${esc(r.label)}</b><small>${r.kind === 'alarm' ? 'Alarm' : 'Timer finished'}</small></div>`;+ const sn = h('button', 'clk-btn', 'Snooze 10 min');+ sn.type = 'button';+ if (r.kind === 'alarm') sn.addEventListener('click', () => snooze(r.rid));+ else sn.hidden = true;+ const ds = h('button', 'clk-btn primary', 'Dismiss');+ ds.type = 'button';+ ds.addEventListener('click', () => dismiss(r.rid));+ row.append(sn, ds);+ return row;+ }),+ );+ ringBox.classList.toggle('on', engine.ringing.length > 0);+ }++ // ---------------- world ----------------+ function renderWorld() {+ const wrap = h('div', 'clk-world');+ const top = h('div', 'clk-hero');+ top.innerHTML = `${analogSvg()}<div class="clk-hero-t"><div class="big" data-k="local-t"></div><div class="sub" data-k="local-d"></div><div class="sub dim">${esc(cityOf(LOCAL))} (${esc(LOCAL)})</div></div>`;+ const face = top.querySelector('.clk-face');+ const add = h('form', 'clk-add');+ add.autocomplete = 'off';+ const input = h('input', 'clk-input');+ input.placeholder = 'Add a city or time zone, like Tokyo';+ input.setAttribute('aria-label', 'Add a city or time zone');+ input.setAttribute('role', 'combobox');+ input.setAttribute('aria-expanded', 'false');+ const sug = h('ul', 'clk-sug');+ sug.setAttribute('role', 'listbox');+ sug.hidden = true;+ add.append(input, sug);+ let all = [];+ try {+ all = Intl.supportedValuesOf('timeZone');+ } catch {+ all = [];+ }+ if (!all.includes('UTC')) all.push('UTC');+ let hi = -1;+ let matches = [];+ const pick = (z) => {+ if (!isValidZone(z)) return ctx.toast(`"${z}" is not a known time zone`);+ if (z === LOCAL || zones.includes(z)) ctx.toast('That clock is already on the list');+ else {+ zones.push(z);+ store.set(K.zones, JSON.stringify(zones));+ }+ render();+ };+ const showSug = () => {+ const q = input.value.trim().toLowerCase().replace(/\s+/g, '_');+ matches = q ? all.filter((z) => z.toLowerCase().includes(q)).slice(0, 8) : [];+ hi = matches.length ? 0 : -1;+ sug.replaceChildren(+ ...matches.map((z, i) => {+ const li = h('li', i === hi ? 'on' : '', `<b>${esc(cityOf(z))}</b><span>${esc(z)} · ${esc(offsetLabel(zoneOffsetMinutes(z)))}</span>`);+ li.setAttribute('role', 'option');+ li.addEventListener('mousedown', (e) => {+ e.preventDefault();+ pick(z);+ });+ return li;+ }),+ );+ if (q && !matches.length) sug.append(h('li', 'none', 'No matching time zone. Try a city like Paris or a name like Asia/Tokyo.'));+ sug.hidden = !q;+ input.setAttribute('aria-expanded', String(!sug.hidden));+ };+ input.addEventListener('input', showSug);+ input.addEventListener('blur', () => (sug.hidden = true));+ input.addEventListener('focus', showSug);+ input.addEventListener('keydown', (e) => {+ if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {+ if (!matches.length) return;+ hi = (hi + (e.key === 'ArrowDown' ? 1 : -1) + matches.length) % matches.length;+ [...sug.children].forEach((li, i) => li.classList.toggle('on', i === hi));+ e.preventDefault();+ } else if (e.key === 'Escape') sug.hidden = true;+ });+ add.addEventListener('submit', (e) => {+ e.preventDefault();+ const v = input.value.trim();+ if (hi >= 0 && matches[hi]) pick(matches[hi]);+ else if (v) pick(v);+ });+ const list = h('div', 'clk-zones');+ const rows = zones.map((z) => {+ const card = h('div', 'clk-zone');+ card.innerHTML = `<div class="l"><b>${esc(cityOf(z))}</b><small data-k="rel"></small></div><div class="r"><div class="t" data-k="t"></div><small data-k="d"></small></div><span class="dn" data-k="dn"></span>`;+ const rm = h('button', 'clk-x', ICO.trash);+ rm.type = 'button';+ rm.title = `Remove ${cityOf(z)}`;+ rm.setAttribute('aria-label', `Remove ${cityOf(z)}`);+ rm.addEventListener('click', () => {+ zones = zones.filter((x) => x !== z);+ store.set(K.zones, JSON.stringify(zones));+ render();+ });+ card.append(rm);+ list.append(card);+ return { z, card };+ });+ if (!rows.length) list.append(h('p', 'clk-empty', 'No other clocks yet. Add a city above to compare its time with yours.'));+ wrap.append(top, add, list);+ panel.append(wrap);+ const q = (el, k) => el.querySelector(`[data-k="${k}"]`);+ const update = () => {+ const now = new Date();+ q(top, 'local-t').textContent = now.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', second: '2-digit' });+ q(top, 'local-d').textContent = now.toLocaleDateString([], { weekday: 'long', month: 'long', day: 'numeric', year: 'numeric' });+ const s = now.getSeconds() + now.getMilliseconds() / 1000;+ const m = now.getMinutes() + s / 60;+ const hr = (now.getHours() % 12) + m / 60;+ face.querySelector('.sh').setAttribute('transform', `rotate(${s * 6} 50 50)`);+ face.querySelector('.mh').setAttribute('transform', `rotate(${m * 6} 50 50)`);+ face.querySelector('.hh').setAttribute('transform', `rotate(${hr * 30} 50 50)`);+ const localOff = -now.getTimezoneOffset();+ for (const { z, card } of rows) {+ const off = zoneOffsetMinutes(z, now);+ q(card, 't').textContent = now.toLocaleTimeString([], { timeZone: z, hour: '2-digit', minute: '2-digit' });+ q(card, 'd').textContent = now.toLocaleDateString([], { timeZone: z, weekday: 'short', month: 'short', day: 'numeric' });+ q(card, 'rel').textContent = `${offsetLabel(off)} · ${relativeOffset(off, localOff)}`;+ const day = isDaytime(z, now);+ const dn = q(card, 'dn');+ dn.innerHTML = day ? ICO.sun : ICO.moon;+ dn.title = day ? 'Daytime' : 'Night';+ card.classList.toggle('night', !day);+ }+ };+ update();+ tickers.add(update);+ }++ // ---------------- alarms ----------------+ function renderAlarms() {+ const wrap = h('div', 'clk-alarms');+ const head = h('div', 'clk-head');+ const sorted = [...engine.alarms].sort((a, b) => a.h * 60 + a.m - (b.h * 60 + b.m));+ const nextUp = engine.alarms.map((a) => nextAlarmTime(a)).filter(Boolean).sort((a, b) => a - b)[0];+ head.innerHTML = `<div><h2>Alarms</h2><small>${nextUp ? `Next alarm ${untilLabel(nextUp)}` : 'No alarms are set'}</small></div>`;+ const addBtn = h('button', 'clk-btn primary', `${ICO.plus} New alarm`);+ addBtn.type = 'button';+ addBtn.addEventListener('click', () => {+ editing = 'new';+ render();+ });+ head.append(addBtn);+ wrap.append(head);+ if (editing) wrap.append(alarmForm());+ if (!sorted.length && !editing) {+ const e = h('div', 'clk-emptybox', `<div class="ico">${ICO.bell}</div><b>No alarms yet</b><p>Add an alarm and it will ring with a sound and a notification while three.ws is open, even after you close this window.</p>`);+ wrap.append(e);+ }+ const list = h('ul', 'clk-alist');+ for (const a of sorted) {+ const li = h('li', `clk-alarm${a.on ? '' : ' off'}`);+ const t = fmtTime12(a.h, a.m);+ const nt = a.on ? nextAlarmTime(a) : null;+ li.innerHTML = `<div class="tm"><span>${hhmm(a.h, a.m)}</span><small>${t.t} ${t.p}</small></div><div class="inf"><b>${esc(a.label || 'Alarm')}</b><small>${esc(repeatLabel(a.days))}${nt ? ` · ${untilLabel(nt)}` : ''}</small></div>`;+ const sw2 = h('button', `clk-switch${a.on ? ' on' : ''}`);+ sw2.type = 'button';+ sw2.setAttribute('role', 'switch');+ sw2.setAttribute('aria-checked', String(a.on));+ sw2.setAttribute('aria-label', `${a.label || 'Alarm'} at ${hhmm(a.h, a.m)}`);+ sw2.addEventListener('click', () => {+ a.on = !a.on;+ persist();+ render();+ });+ const ed = h('button', 'clk-x', ICO.edit);+ ed.type = 'button';+ ed.title = 'Edit';+ ed.setAttribute('aria-label', `Edit alarm ${hhmm(a.h, a.m)}`);+ ed.addEventListener('click', () => {+ editing = a.id;+ render();+ });+ const rm = h('button', 'clk-x', ICO.trash);+ rm.type = 'button';+ rm.title = 'Delete';+ rm.setAttribute('aria-label', `Delete alarm ${hhmm(a.h, a.m)}`);+ rm.addEventListener('click', () => {+ engine.alarms = engine.alarms.filter((x) => x.id !== a.id);+ persist();+ render();+ });+ li.append(sw2, ed, rm);+ list.append(li);+ }+ wrap.append(list);+ panel.append(wrap);+ }+ function alarmForm() {+ const cur = engine.alarms.find((a) => a.id === editing);+ const d = new Date(Date.now() + 3600_000);+ const a = cur ? { ...cur, days: [...cur.days] } : { id: uid(), on: true, h: d.getHours(), m: 0, days: [], label: '' };+ const form = h('form', 'clk-form');+ form.innerHTML = `<label>Time<input type="time" class="clk-input" required value="${hhmm(a.h, a.m)}"></label><label>Label<input type="text" class="clk-input" maxlength="60" placeholder="Alarm" value="${esc(a.label || '')}"></label><fieldset><legend>Repeat</legend><div class="days"></div></fieldset>`;+ const timeIn = form.querySelector('input[type=time]');+ const labelIn = form.querySelector('input[type=text]');+ const daysEl = form.querySelector('.days');+ DAYS.forEach((name, i) => {+ const b = h('button', `clk-day${a.days.includes(i) ? ' on' : ''}`, name[0]);+ b.type = 'button';+ b.title = name;+ b.setAttribute('aria-label', name);+ b.setAttribute('aria-pressed', String(a.days.includes(i)));+ b.addEventListener('click', () => {+ a.days = a.days.includes(i) ? a.days.filter((x) => x !== i) : [...a.days, i];+ b.classList.toggle('on');+ b.setAttribute('aria-pressed', String(a.days.includes(i)));+ });+ daysEl.append(b);+ });+ const row = h('div', 'clk-actions');+ const cancel = h('button', 'clk-btn', 'Cancel');+ cancel.type = 'button';+ cancel.addEventListener('click', () => {+ editing = null;+ render();+ });+ const save = h('button', 'clk-btn primary', 'Save');+ save.type = 'submit';+ row.append(cancel, save);+ form.append(row);+ form.addEventListener('submit', (e) => {+ e.preventDefault();+ const [hh, mm] = timeIn.value.split(':').map(Number);+ if (!Number.isInteger(hh) || !Number.isInteger(mm)) return ctx.toast('Pick a time for the alarm');+ Object.assign(a, { h: hh, m: mm, on: true, label: labelIn.value.trim() });+ if (cur) engine.alarms = engine.alarms.map((x) => (x.id === a.id ? a : x));+ else engine.alarms.push(a);+ ensureAudio();+ persist();+ editing = null;+ ctx.toast(`Alarm set ${untilLabel(nextAlarmTime(a))}`);+ render();+ });+ queueMicrotask(() => timeIn.focus());+ return form;+ }++ // ---------------- timers ----------------+ function renderTimers() {+ const wrap = h('div', 'clk-timers');+ const head = h('div', 'clk-head');+ head.innerHTML = '<div><h2>Timer</h2><small>Run several at once. They keep counting if you close this window.</small></div>';+ wrap.append(head);+ const form = h('form', 'clk-tform');+ const chips = h('div', 'clk-chips');+ const startTimer = (sec, label) => {+ ensureAudio();+ engine.timers.push({ id: uid(), label: label || '', total: sec * 1000, left: sec * 1000, endsAt: Date.now() + sec * 1000, done: false });+ persist();+ render();+ };+ for (const [l, s] of PRESETS) {+ const b = h('button', 'clk-chip', l);+ b.type = 'button';+ b.addEventListener('click', () => startTimer(s));+ chips.append(b);+ }+ const dur = h('input', 'clk-input');+ dur.placeholder = 'Custom: 90, 1:30 or 1h 5m';+ dur.setAttribute('aria-label', 'Custom duration');+ const lab = h('input', 'clk-input');+ lab.placeholder = 'Label (optional)';+ lab.maxLength = 60;+ lab.setAttribute('aria-label', 'Timer label');+ const go = h('button', 'clk-btn primary', `${ICO.play} Start`);+ go.type = 'submit';+ form.append(chips, dur, lab, go);+ form.addEventListener('submit', (e) => {+ e.preventDefault();+ const ms = parseDuration(dur.value);+ if (!ms || ms < 1000) {+ dur.setCustomValidity('Enter a duration like 90, 1:30 or 1h 5m');+ dur.reportValidity();+ dur.setCustomValidity('');+ return;+ }+ startTimer(ms / 1000, lab.value.trim());+ });+ wrap.append(form);+ if (!engine.timers.length) wrap.append(h('div', 'clk-emptybox', '<b>No timers running</b><p>Pick a preset or type a custom duration to start one.</p>'));+ const list = h('div', 'clk-tlist');+ const cards = engine.timers.map((t) => {+ const card = h('div', `clk-timer${t.done ? ' done' : ''}`);+ card.innerHTML = `<svg viewBox="0 0 44 44" class="ring" aria-hidden="true"><circle cx="22" cy="22" r="19" class="bg"/><circle cx="22" cy="22" r="19" class="fg" stroke-dasharray="119.4" data-k="arc"/></svg><div class="inf"><b>${esc(t.label || formatDuration(t.total))}</b><div class="left" data-k="left"></div></div>`;+ const toggle = h('button', 'clk-btn round', t.endsAt ? ICO.pause : ICO.play);+ toggle.type = 'button';+ toggle.setAttribute('aria-label', t.endsAt ? 'Pause timer' : 'Start timer');+ toggle.disabled = t.done;+ toggle.addEventListener('click', () => {+ if (t.endsAt) {+ t.left = Math.max(0, t.endsAt - Date.now());+ t.endsAt = null;+ } else t.endsAt = Date.now() + t.left;+ ensureAudio();+ persist();+ render();+ });+ const reset = h('button', 'clk-x', ICO.reset);+ reset.type = 'button';+ reset.title = 'Restart';+ reset.setAttribute('aria-label', 'Restart timer');+ reset.addEventListener('click', () => {+ Object.assign(t, { left: t.total, endsAt: null, done: false });+ persist();+ render();+ });+ const rm = h('button', 'clk-x', ICO.trash);+ rm.type = 'button';+ rm.title = 'Delete';+ rm.setAttribute('aria-label', 'Delete timer');+ rm.addEventListener('click', () => {+ engine.timers = engine.timers.filter((x) => x.id !== t.id);+ persist();+ render();+ });+ card.append(toggle, reset, rm);+ list.append(card);+ return { t, card };+ });+ wrap.append(list);+ panel.append(wrap);+ const update = () => {+ const now = Date.now();+ for (const { t, card } of cards) {+ const left = t.endsAt ? Math.max(0, t.endsAt - now) : t.left;+ card.querySelector('[data-k=left]').textContent = t.done ? 'Time is up' : formatDuration(Math.ceil(left / 1000) * 1000);+ card.querySelector('[data-k=arc]').setAttribute('stroke-dashoffset', String(119.4 * (1 - (t.done ? 0 : left / t.total))));+ card.classList.toggle('paused', !t.endsAt && !t.done);+ }+ };+ update();+ tickers.add(update);+ }++ // ---------------- stopwatch ----------------+ function renderStopwatch() {+ const wrap = h('div', 'clk-sw');+ const big = h('div', 'clk-swbig');+ big.setAttribute('role', 'timer');+ const btns = h('div', 'clk-actions center');+ const lapB = h('button', 'clk-btn', `${ICO.flag} Lap`);+ lapB.type = 'button';+ const mainB = h('button', 'clk-btn primary big');+ mainB.type = 'button';+ const rstB = h('button', 'clk-btn', `${ICO.reset} Reset`);+ rstB.type = 'button';+ btns.append(lapB, mainB, rstB);+ const listWrap = h('div', 'clk-laps');+ wrap.append(big, btns, listWrap);+ panel.append(wrap);+ const saveSw = () => store.set(K.sw, JSON.stringify(sw));+ const draw = () => {+ big.textContent = formatDuration(stopwatch.now(sw), true);+ mainB.innerHTML = sw.running ? `${ICO.pause} Pause` : `${ICO.play} ${sw.elapsed ? 'Resume' : 'Start'}`;+ lapB.disabled = !sw.running;+ rstB.disabled = !sw.running && !sw.elapsed;+ };+ const drawLaps = () => {+ listWrap.replaceChildren();+ if (!sw.laps.length) {+ listWrap.append(h('p', 'clk-empty', 'Start the stopwatch, then tap Lap to record split times.'));+ return;+ }+ const ex = lapExtremes(sw.laps);+ const ol = h('ol', 'clk-laplist');+ for (const l of [...sw.laps].reverse()) {+ const tag = l.n === ex.fastest ? ' fast' : l.n === ex.slowest ? ' slow' : '';+ ol.append(h('li', tag.trim(), `<span>Lap ${l.n}</span><b>${formatDuration(l.split, true)}</b><small>${formatDuration(l.total, true)}</small>`));+ }+ listWrap.append(ol);+ };+ const loop = () => {+ draw();+ if (sw.running) rafId = requestAnimationFrame(loop);+ };+ mainB.addEventListener('click', () => {+ sw = sw.running ? stopwatch.pause(sw) : stopwatch.start(sw);+ saveSw();+ loop();+ });+ lapB.addEventListener('click', () => {+ sw = stopwatch.lap(sw);+ saveSw();+ drawLaps();+ });+ rstB.addEventListener('click', () => {+ sw = stopwatch.fresh();+ saveSw();+ cancelAnimationFrame(rafId);+ draw();+ drawLaps();+ });+ draw();+ drawLaps();+ if (sw.running) loop();+ }++ // ---------------- wiring ----------------+ let lastAlarmView = '';+ const refresh = () => {+ renderRing();+ if (tab === 'alarms' && !editing) render();+ else if (tab === 'timer') render();+ };+ engine.listeners.add(refresh);+ const unTick = subscribeTick(() => {+ tickers.forEach((fn) => fn());+ if (tab === 'alarms' && !editing) {+ const key = engine.alarms.map((a) => a.on).join();+ if (key !== lastAlarmView) {+ lastAlarmView = key;+ render();+ }+ }+ });+ setTab(tab);+ renderRing();+ return () => {+ engine.listeners.delete(refresh);+ unTick();+ cancelAnimationFrame(rafId);+ };+}diff --git a/src/desktop/os/apps/files.css b/src/desktop/os/apps/files.cssnew file mode 100644index 000000000..790b0a80a--- /dev/null+++ b/src/desktop/os/apps/files.css@@ -0,0 +1,731 @@+.napp-files {+ height: 100%;+ min-height: 0;+}+.napp-files .fx {+ position: relative;+ display: flex;+ flex-direction: column;+ height: 100%;+ min-height: 0;+ background: var(--card);+ color: var(--text);+ font-size: 13px;+ overflow: hidden;+ container-type: inline-size;+}+.napp-files .fx button {+ font: inherit;+ color: inherit;+}+.napp-files .fx button:disabled {+ opacity: 0.4;+ cursor: default;+}++/* top bar */+.napp-files .fx-top {+ display: flex;+ align-items: center;+ gap: 8px;+ padding: 8px 10px 4px;+}+.napp-files .fx-nav {+ display: flex;+ gap: 2px;+}+.napp-files .fx-btn {+ display: grid;+ place-items: center;+ width: 30px;+ height: 30px;+ border-radius: var(--siz-radius3, 6px);+}+.napp-files .fx-btn:not(:disabled):hover {+ background: var(--hover);+}+.napp-files .fx-btn:not(:disabled):active {+ background: var(--hover-b, var(--hover));+}+.napp-files .fx-addr {+ flex: 1;+ min-width: 0;+ display: flex;+ align-items: center;+ height: 30px;+ padding: 0 4px;+ border: 1px solid var(--bd);+ border-radius: var(--siz-radius3, 6px);+ background: var(--bg30, transparent);+ cursor: text;+}+.napp-files .fx-addr:focus-within {+ border-color: var(--accent);+}+.napp-files .fx-crumbs {+ display: flex;+ align-items: center;+ min-width: 0;+ overflow-x: auto;+ scrollbar-width: none;+ white-space: nowrap;+}+.napp-files .fx-crumbs::-webkit-scrollbar {+ display: none;+}+.napp-files .fx-crumb {+ padding: 3px 7px;+ border-radius: 5px;+ max-width: 200px;+ overflow: hidden;+ text-overflow: ellipsis;+}+.napp-files .fx-crumb:hover {+ background: var(--hover);+}+.napp-files .fx-crumb[aria-current] {+ font-weight: 600;+}+.napp-files .fx-chev {+ color: var(--text2);+ display: grid;+}+.napp-files .fx-addr-in {+ flex: 1;+ min-width: 0;+ height: 100%;+ padding: 0 6px;+ border: 0;+ outline: 0;+ background: transparent;+ color: var(--text);+ font: inherit;+}+.napp-files .fx-addr-in.bad {+ color: #e5484d;+}+.napp-files .fx-search {+ display: flex;+ align-items: center;+ gap: 6px;+ width: 200px;+ flex: none;+ height: 30px;+ padding: 0 8px;+ border: 1px solid var(--bd);+ border-radius: var(--siz-radius3, 6px);+ color: var(--text2);+}+.napp-files .fx-search:focus-within {+ border-color: var(--accent);+ color: var(--text);+}+.napp-files .fx-search input {+ flex: 1;+ min-width: 0;+ border: 0;+ outline: 0;+ background: transparent;+ color: var(--text);+ font: inherit;+}++/* command bar */+.napp-files .fx-cmd {+ display: flex;+ align-items: center;+ gap: 2px;+ padding: 4px 10px 6px;+ border-bottom: 1px solid var(--bd);+ overflow-x: auto;+ scrollbar-width: none;+}+.napp-files .fx-cb {+ display: flex;+ align-items: center;+ gap: 6px;+ height: 30px;+ padding: 0 9px;+ border-radius: var(--siz-radius3, 6px);+ white-space: nowrap;+}+.napp-files .fx-cb:not(:disabled):hover {+ background: var(--hover);+}+.napp-files .fx-cb:not(:disabled):active {+ background: var(--hover-b, var(--hover));+}+@container (max-width: 1000px) {+ .napp-files .fx-cb.sec span {+ display: none;+ }+}+.napp-files .fx-sep {+ width: 1px;+ height: 18px;+ background: var(--bd);+ margin: 0 5px;+}+.napp-files .fx-grow {+ flex: 1;+}+.napp-files .fx-views {+ display: flex;+ margin-left: 6px;+ padding: 2px;+ border: 1px solid var(--bd);+ border-radius: var(--siz-radius3, 6px);+}+.napp-files .fx-vb {+ display: grid;+ place-items: center;+ width: 28px;+ height: 24px;+ border-radius: 4px;+}+.napp-files .fx-vb:hover {+ background: var(--hover);+}+.napp-files .fx-vb.on {+ background: var(--accent);+ color: #fff;+}++/* body */+.napp-files .fx-body {+ flex: 1;+ min-height: 0;+ display: flex;+}+.napp-files .fx-side {+ flex: none;+ width: 190px;+ padding: 8px 6px;+ overflow-y: auto;+ border-right: 1px solid var(--bd);+ display: flex;+ flex-direction: column;+ gap: 1px;+}+@media (max-width: 640px) {+ .napp-files .fx-side {+ width: 52px;+ }+ .napp-files .fx-side .fx-nv span,+ .napp-files .fx-side .fx-nh,+ .napp-files .fx-side .fx-meter,+ .napp-files .fx-side .fx-count {+ display: none;+ }+}+.napp-files .fx-nh {+ padding: 10px 10px 4px;+ font-size: 11px;+ letter-spacing: 0.04em;+ text-transform: uppercase;+ color: var(--text2);+}+.napp-files .fx-nv {+ display: flex;+ align-items: center;+ gap: 10px;+ height: 30px;+ padding: 0 10px;+ border-radius: var(--siz-radius3, 6px);+ text-align: left;+ position: relative;+}+.napp-files .fx-nv span {+ flex: 1;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}+.napp-files .fx-nv:hover {+ background: var(--hover);+}+.napp-files .fx-nv.on {+ background: var(--hover-b, var(--hover));+}+.napp-files .fx-nv.on::before {+ content: '';+ position: absolute;+ left: 0;+ top: 7px;+ bottom: 7px;+ width: 3px;+ border-radius: 2px;+ background: var(--accent);+}+.napp-files .fx-count {+ font-style: normal;+ font-size: 11px;+ padding: 1px 6px;+ border-radius: 9px;+ background: var(--fill, var(--hover));+ color: var(--text2);+}+.napp-files .drop-hot {+ background: color-mix(in srgb, var(--accent) 28%, transparent) !important;+ outline: 1px solid var(--accent);+}+.napp-files .fx-meter {+ display: flex;+ flex-direction: column;+ gap: 4px;+ padding: 2px 10px 6px 36px;+ font-size: 11px;+ color: var(--text2);+}+.napp-files .fx-meter.big {+ padding: 0;+ margin-top: 6px;+ font-size: 12px;+}+.napp-files .fx-meter-bar {+ height: 5px;+ border-radius: 3px;+ background: var(--fill, var(--hover));+ overflow: hidden;+}+.napp-files .fx-meter.big .fx-meter-bar {+ height: 8px;+ width: 280px;+ max-width: 100%;+}+.napp-files .fx-meter-bar i {+ display: block;+ height: 100%;+ background: var(--accent);+ border-radius: 3px;+}+.napp-files .fx-meter-sub {+ opacity: 0.8;+}++/* main */+.napp-files .fx-main {+ position: relative;+ flex: 1;+ min-width: 0;+ display: flex;+ flex-direction: column;+}+.napp-files .fx-hdr {+ display: grid;+ grid-template-columns: 30px var(--cols);+ position: sticky;+ top: -6px;+ z-index: 2;+ margin: -6px -6px 4px;+ padding: 0 6px;+ background: var(--card);+ border-bottom: 1px solid var(--bd);+ font-size: 12px;+ color: var(--text2);+}+.napp-files .fx-hdr[hidden] {+ display: none;+}+.napp-files .fx-th {+ display: flex;+ align-items: center;+ gap: 4px;+ height: 28px;+ padding: 0 8px;+ text-align: left;+ overflow: hidden;+ white-space: nowrap;+}+.napp-files button.fx-th:hover {+ background: var(--hover);+ color: var(--text);+}+.napp-files .fx-th.r {+ justify-content: flex-end;+}+.napp-files .fx-caret {+ font-size: 8px;+}+.napp-files .fx-scroll {+ flex: 1;+ min-height: 0;+ overflow: auto;+ outline: 0;+ padding: 6px;+}+.napp-files .fx-scroll:focus-visible {+ box-shadow: inset 0 0 0 2px color-mix(in srgb, var(--accent) 45%, transparent);+}+.napp-files .fx-item {+ position: relative;+ display: flex;+ align-items: center;+ gap: 10px;+ min-width: 0;+ border-radius: var(--siz-radius3, 6px);+ border: 1px solid transparent;+ cursor: default;+ user-select: none;+ content-visibility: auto;+}+.napp-files .fx-item:hover {+ background: var(--hover);+}+.napp-files .fx-item.sel {+ background: color-mix(in srgb, var(--accent) 24%, transparent);+ border-color: color-mix(in srgb, var(--accent) 55%, transparent);+}+.napp-files .fx-scroll:focus-visible .fx-item.cur {+ outline: 1px dotted var(--text2);+}+.napp-files .fx-item.cut {+ opacity: 0.5;+}+.napp-files .fx-ic {+ display: grid;+ place-items: center;+ flex: none;+ color: var(--text2);+}+.napp-files .k-dir .fx-ic {+ color: #f0b429;+}+.napp-files .k-image .fx-ic {+ color: #3ecf8e;+}+.napp-files .k-audio .fx-ic {+ color: #b794f6;+}+.napp-files .k-video .fx-ic {+ color: #f472b6;+}+.napp-files .k-text .fx-ic {+ color: #60a5fa;+}+.napp-files .fx-name {+ min-width: 0;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}+.napp-files .fx-rename {+ min-width: 0;+ flex: 1;+ padding: 2px 4px;+ border: 1px solid var(--accent);+ border-radius: 4px;+ background: var(--bg);+ color: var(--text);+ font: inherit;+ outline: 0;+}++/* list */+.napp-files .v-list .fx-items {+ display: grid;+ grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));+ gap: 1px 6px;+}+.napp-files .v-list .fx-item {+ height: 32px;+ padding: 0 8px;+ contain-intrinsic-size: auto 32px;+}++/* details */+.napp-files .v-details .fx-item {+ display: grid;+ grid-template-columns: 30px var(--cols);+ height: 32px;+ gap: 0;+ padding: 0;+ contain-intrinsic-size: auto 32px;+}+.napp-files .v-details .fx-ic {+ justify-self: end;+}+.napp-files .v-details .fx-name,+.napp-files .v-details .fx-c {+ padding: 0 8px;+}+.napp-files .fx-c {+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ color: var(--text2);+ font-size: 12px;+}+.napp-files .fx-c.r {+ text-align: right;+}++/* large icons */+.napp-files .v-grid .fx-items {+ display: grid;+ grid-template-columns: repeat(auto-fill, minmax(104px, 1fr));+ gap: 6px;+}+.napp-files .v-grid .fx-item {+ flex-direction: column;+ align-items: center;+ justify-content: flex-start;+ gap: 6px;+ padding: 10px 6px 8px;+ height: 118px;+ text-align: center;+ contain-intrinsic-size: auto 118px;+}+.napp-files .v-grid .fx-ic {+ width: 72px;+ height: 60px;+ border-radius: 6px;+ overflow: hidden;+}+.napp-files .v-grid .fx-ic img {+ width: 100%;+ height: 100%;+ object-fit: cover;+ border-radius: 6px;+}+.napp-files .v-grid .fx-name {+ width: 100%;+ white-space: normal;+ display: -webkit-box;+ -webkit-line-clamp: 2;+ -webkit-box-orient: vertical;+ word-break: break-word;+ font-size: 12px;+}+.napp-files .v-grid .fx-rename {+ width: 100%;+ text-align: center;+}++/* storage card on This PC */+.napp-files .fx-pc {+ display: flex;+ align-items: center;+ gap: 14px;+ margin: 4px 4px 12px;+ padding: 14px 16px;+ border: 1px solid var(--bd);+ border-radius: 10px;+ background: var(--hover-half, transparent);+}+.napp-files .fx-pc > svg {+ color: var(--accent);+}++/* states */+.napp-files .fx-empty {+ display: flex;+ flex-direction: column;+ align-items: center;+ justify-content: center;+ gap: 6px;+ min-height: 220px;+ height: 80%;+ padding: 24px;+ text-align: center;+ color: var(--text2);+}+.napp-files .fx-empty h3 {+ margin: 8px 0 0;+ font-size: 15px;+ font-weight: 600;+ color: var(--text);+}+.napp-files .fx-empty p {+ margin: 0;+ max-width: 380px;+}+.napp-files .fx-empty.err svg {+ color: #e5484d;+}+.napp-files .fx-empty-act {+ display: flex;+ gap: 8px;+ margin-top: 12px;+}+.napp-files .fx-pill {+ height: 30px;+ padding: 0 14px;+ border: 1px solid var(--bd);+ border-radius: var(--siz-radius3, 6px);+ background: var(--hover);+}+.napp-files .fx-pill:hover {+ background: var(--hover-b, var(--hover));+}+.napp-files .fx-pill.primary {+ background: var(--accent);+ border-color: transparent;+ color: #fff;+}+.napp-files .fx-pill.danger {+ background: #d13438;+ border-color: transparent;+ color: #fff;+}+.napp-files .fx-skel {+ display: flex;+ flex-direction: column;+ gap: 6px;+ padding: 4px;+}+.napp-files .fx-skel-row {+ display: flex;+ align-items: center;+ gap: 12px;+ height: 30px;+}+.napp-files .fx-skel-row i,+.napp-files .fx-skel-row b {+ height: 14px;+ border-radius: 4px;+ background: linear-gradient(90deg, var(--hover) 25%, var(--hover-b, var(--hover)) 50%, var(--hover) 75%);+ background-size: 200% 100%;+ animation: fx-shim 1.2s linear infinite;+}+.napp-files .fx-skel-row i {+ width: 18px;+}+.napp-files .fx-skel-row b {+ flex: 1;+ max-width: 260px;+}+@keyframes fx-shim {+ to {+ background-position: -200% 0;+ }+}+@media (prefers-reduced-motion: reduce) {+ .napp-files .fx-skel-row i,+ .napp-files .fx-skel-row b {+ animation: none;+ }+}++.napp-files .fx-drop {+ position: absolute;+ inset: 8px;+ display: grid;+ place-items: center;+ border: 2px dashed var(--accent);+ border-radius: 10px;+ background: color-mix(in srgb, var(--accent) 14%, transparent);+ font-weight: 600;+ pointer-events: none;+ z-index: 4;+}+.napp-files .fx-drop[hidden] {+ display: none;+}++.napp-files .fx-status {+ flex: none;+ height: 26px;+ display: flex;+ align-items: center;+ padding: 0 14px;+ border-top: 1px solid var(--bd);+ font-size: 12px;+ color: var(--text2);+ white-space: pre;+}++/* context menu and dialogs */+.napp-files .fx-menu {+ position: absolute;+ z-index: 20;+ min-width: 210px;+ padding: 5px;+ border: 1px solid var(--bd);+ border-radius: 8px;+ background: var(--cm, var(--card));+ backdrop-filter: blur(16px);+ box-shadow: var(--shadow-md, 0 8px 32px rgba(0, 0, 0, 0.3));+}+.napp-files .fx-menu button {+ display: flex;+ align-items: center;+ gap: 8px;+ width: 100%;+ height: 30px;+ padding: 0 8px;+ border-radius: 5px;+ text-align: left;+}+.napp-files .fx-menu button:hover:not(:disabled),+.napp-files .fx-menu button:focus-visible {+ background: var(--hover-b, var(--hover));+ outline: 0;+}+.napp-files .fx-menu button:disabled {+ opacity: 0.4;+}+.napp-files .fx-menu button.danger .fx-ml {+ color: #e5484d;+}+.napp-files .fx-mi {+ display: grid;+ place-items: center;+ width: 16px;+ flex: none;+}+.napp-files .fx-ml {+ flex: 1;+}+.napp-files .fx-menu kbd {+ font: inherit;+ font-size: 11px;+ color: var(--text2);+}+.napp-files .fx-menu hr {+ border: 0;+ border-top: 1px solid var(--hr, var(--bd));+ margin: 4px 6px;+}+.napp-files .fx-modal {+ position: absolute;+ inset: 0;+ z-index: 30;+ display: grid;+ place-items: center;+ background: var(--bg50, rgba(0, 0, 0, 0.4));+}+.napp-files .fx-dlg {+ width: min(380px, 90%);+ padding: 18px;+ border: 1px solid var(--bd);+ border-radius: 10px;+ background: var(--card);+ box-shadow: var(--shadow-lg, 0 16px 64px rgba(0, 0, 0, 0.5));+}+.napp-files .fx-dlg h3 {+ margin: 0 0 8px;+ font-size: 15px;+}+.napp-files .fx-dlg p {+ margin: 0 0 12px;+ color: var(--text2);+}+.napp-files .fx-dlg-in {+ width: 100%;+ box-sizing: border-box;+ height: 32px;+ padding: 0 8px;+ margin-bottom: 12px;+ border: 1px solid var(--accent);+ border-radius: 6px;+ background: var(--bg);+ color: var(--text);+ font: inherit;+ outline: 0;+}+.napp-files .fx-dlg-act {+ display: flex;+ justify-content: flex-end;+ gap: 8px;+}diff --git a/src/desktop/os/apps/files.js b/src/desktop/os/apps/files.jsnew file mode 100644index 000000000..078defa3e--- /dev/null+++ b/src/desktop/os/apps/files.js@@ -0,0 +1,1264 @@+// File Explorer: the desktop's window onto the virtual file system (../fs.js).+import './files.css';+import * as fs from '../fs.js';++const HOME = '@home';++/* ---------- pure helpers (unit tested) ---------- */++/** "0 B", "812 B", "12 KB", "1.5 MB". */+export function formatSize(bytes) {+ const n = Number(bytes);+ if (!Number.isFinite(n) || n <= 0) return '0 B';+ if (n < 1024) return `${Math.round(n)} B`;+ const units = ['KB', 'MB', 'GB', 'TB'];+ let v = n / 1024;+ let i = 0;+ while (v >= 1024 && i < units.length - 1) {+ v /= 1024;+ i++;+ }+ const s = v < 10 ? v.toFixed(1).replace(/\.0$/, '') : String(Math.round(v));+ return `${s} ${units[i]}`;+}++/** Human type label for a node: "File folder", "PNG file", "File". */+export function typeLabel(node) {+ if (node.type === 'dir') return 'File folder';+ const e = fs.extOf(node.name);+ return e ? `${e.toUpperCase()} file` : 'File';+}++const collator = new Intl.Collator(undefined, { numeric: true, sensitivity: 'base' });++/**+ * Sort nodes without mutating the input. Folders always come first.+ * key: 'name' | 'date' | 'size' | 'type'; dir: 'asc' | 'desc'.+ */+export function sortNodes(nodes, { key = 'name', dir = 'asc' } = {}) {+ const sign = dir === 'desc' ? -1 : 1;+ const cmp = {+ name: (a, b) => collator.compare(a.name, b.name),+ date: (a, b) => (a.mtime || 0) - (b.mtime || 0) || collator.compare(a.name, b.name),+ size: (a, b) => (a.size || 0) - (b.size || 0) || collator.compare(a.name, b.name),+ type: (a, b) => collator.compare(typeLabel(a), typeLabel(b)) || collator.compare(a.name, b.name),+ }[key] || ((a, b) => collator.compare(a.name, b.name));+ return [...nodes].sort((a, b) => {+ if (a.type !== b.type) return a.type === 'dir' ? -1 : 1;+ return sign * cmp(a, b);+ });+}++/** Display name for a location: Home, This PC, Recycle Bin or the folder name. */+export function locationName(loc) {+ if (loc === HOME) return 'Home';+ if (loc === '/') return 'This PC';+ if (loc === fs.TRASH) return 'Recycle Bin';+ return fs.nameOf(loc) || 'This PC';+}++/** Breadcrumb trail for the address bar: [{ name, path }]. */+export function buildCrumbs(loc) {+ if (loc === HOME) return [{ name: 'Home', path: HOME }];+ const out = [{ name: 'This PC', path: '/' }];+ const p = fs.normalize(loc);+ if (p === '/') return out;+ let acc = '';+ for (const seg of p.split('/').filter(Boolean)) {+ acc += `/${seg}`;+ out.push({ name: acc === fs.TRASH ? 'Recycle Bin' : seg, path: acc });+ }+ return out;+}++/** Turn text typed in the address bar into a location ("home", "This PC\\Documents", "/Pictures/a"). */+export function parseAddress(input) {+ let s = String(input ?? '').trim().replace(/\\/g, '/');+ if (!s || /^this pc\/?$/i.test(s)) return '/';+ if (/^home\/?$/i.test(s)) return HOME;+ if (/^recycle bin\/?$/i.test(s)) return fs.TRASH;+ s = s.replace(/^this pc\//i, '/').replace(/^recycle bin(?=\/|$)/i, fs.TRASH);+ return fs.normalize(s);+}++/** Case-insensitive name filter. An empty query returns everything. */+export function filterByName(nodes, query) {+ const q = String(query || '').trim().toLowerCase();+ return q ? nodes.filter((n) => n.name.toLowerCase().includes(q)) : nodes;+}++/** Paths between `anchor` and `target` (inclusive) in display order, for shift-click. */+export function rangeSelect(order, anchor, target) {+ const a = order.indexOf(anchor);+ const b = order.indexOf(target);+ if (b < 0) return [];+ if (a < 0) return [target];+ return order.slice(Math.min(a, b), Math.max(a, b) + 1);+}++/** Next cursor index for an arrow/Home/End key. `cols` is 1 for list views. */+export function moveIndex(i, key, count, cols = 1) {+ if (!count) return -1;+ if (i < 0) return key === 'ArrowUp' || key === 'End' || key === 'ArrowLeft' ? count - 1 : 0;+ const step = { ArrowUp: -cols, ArrowDown: cols, ArrowLeft: cols > 1 ? -1 : 0, ArrowRight: cols > 1 ? 1 : 0 }[key];+ if (key === 'Home') return 0;+ if (key === 'End') return count - 1;+ if (step == null) return i;+ return Math.max(0, Math.min(count - 1, i + step));+}++/** Of `paths`, those that can legally be moved into `dest` (not already there, not into themselves). */+export function movablePaths(paths, dest) {+ const d = fs.normalize(dest);+ return paths.map(fs.normalize).filter((p) => fs.parentOf(p) !== d && d !== p && !d.startsWith(`${p}/`));+}++/** Total size of the selected files, and how many folders were among them. */+export function selectionSummary(nodes) {+ let bytes = 0;+ let dirs = 0;+ for (const n of nodes) n.type === 'dir' ? dirs++ : (bytes += n.size || 0);+ return { count: nodes.length, bytes, dirs };+}++/** Status-bar text for a listing. */+export function statusText(total, selected) {+ const items = `${total} ${total === 1 ? 'item' : 'items'}`;+ if (!selected.count) return items;+ const sel = `${selected.count} selected`;+ return selected.bytes ? `${items} ${sel} ${formatSize(selected.bytes)}` : `${items} ${sel}`;+}++/* ---------- module state shared by every Explorer window ---------- */++let clip = null; // { mode: 'copy' | 'cut', paths }++const GLYPHS = {+ 'fx-left': '<path d="M19 12H5M11 6l-6 6 6 6"/>',+ 'fx-right': '<path d="M5 12h14M13 6l6 6-6 6"/>',+ 'fx-up': '<path d="M12 19V5M6 11l6-6 6 6"/>',+ 'fx-cut': '<circle cx="6" cy="18" r="2.6"/><circle cx="18" cy="18" r="2.6"/><path d="M7.5 16 17 3M16.5 16 7 3"/>',+ 'fx-copy': '<rect x="8" y="8" width="12" height="12" rx="2"/><path d="M16 8V6a2 2 0 0 0-2-2H6a2 2 0 0 0-2 2v8a2 2 0 0 0 2 2h2"/>',+ 'fx-paste': '<rect x="5" y="4" width="14" height="17" rx="2"/><path d="M9 4V3h6v1M9 11h6M9 15h4"/>',+ 'fx-sort': '<path d="M7 4v16M3 16l4 4 4-4M17 20V4M13 8l4-4 4 4"/>',+ 'fx-file': '<path d="M6 3h8l5 5v13H6z"/><path d="M14 3v5h5"/>',+ 'fx-newfolder': '<path d="M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"/><path d="M12 11v5M9.5 13.5h5"/>',+ 'fx-newfile': '<path d="M6 3h8l5 5v13H6z"/><path d="M14 3v5h5M12 12v6M9 15h6"/>',+ 'fx-restore': '<path d="M4 12a8 8 0 1 0 3-6.2"/><path d="M4 4v4.5h4.5"/>',+ 'fx-drive': '<rect x="3" y="13" width="18" height="7" rx="2"/><path d="M5 13l2-8h10l2 8M7.5 16.5h.01M11 16.5h6"/>',+ 'fx-detail': '<path d="M4 6h16M4 12h16M4 18h16"/>',+ 'fx-tiles': '<rect x="4" y="4" width="7" height="7" rx="1.5"/><rect x="13" y="4" width="7" height="7" rx="1.5"/><rect x="4" y="13" width="7" height="7" rx="1.5"/><rect x="13" y="13" width="7" height="7" rx="1.5"/>',+};++const DIR_ICON = { Desktop: 'desktop', Pictures: 'image', Music: 'music', Videos: 'video', Downloads: 'download', Documents: 'note' };+const KIND_ICON = { text: 'note', image: 'image', audio: 'music', video: 'video', model: 'cube', other: 'fx-file' };++export function iconName(node) {+ if (node.type === 'dir') {+ if (node.path === fs.TRASH) return 'trash';+ return node.parent === '/' ? DIR_ICON[node.name] || 'folder' : 'folder';+ }+ return KIND_ICON[fs.kindOf(node.name)] || 'fx-file';+}++const dateFmt = new Intl.DateTimeFormat(undefined, { dateStyle: 'short', timeStyle: 'short' });+const fmtDate = (ms) => (ms ? dateFmt.format(ms) : '');++/* ---------- the app ---------- */++export function mount(host, ctx) {+ for (const [k, v] of Object.entries(GLYPHS)) ctx.registerGlyph(k, v);+ const { h, esc, icon } = ctx;++ const readJson = (k, d) => {+ try {+ return { ...d, ...JSON.parse(ctx.store.get(k) || '{}') };+ } catch {+ return d;+ }+ };+ const view0 = ctx.store.get('files:view');+ const st = {+ loc: HOME,+ hist: [],+ hi: -1,+ nodes: [],+ shown: [],+ sel: new Set(),+ cursor: null,+ anchor: null,+ view: ['list', 'details', 'grid'].includes(view0) ? view0 : 'details',+ sort: readJson('files:sort', { key: 'name', dir: 'asc' }),+ query: '',+ searching: false,+ loading: true,+ error: null,+ renaming: null,+ dirty: false,+ trashCount: 0,+ };+ let token = 0;+ let dead = false;+ const thumbs = new Map(); // path -> { mtime, url }+ const els = new Map(); // path -> element in the current listing++ const root = h('div', 'fx');+ root.innerHTML = `+ <div class="fx-top">+ <div class="fx-nav">+ <button class="fx-btn" data-act="back" title="Back (Alt+Left)" aria-label="Back">${icon('fx-left', 16)}</button>+ <button class="fx-btn" data-act="fwd" title="Forward (Alt+Right)" aria-label="Forward">${icon('fx-right', 16)}</button>+ <button class="fx-btn" data-act="up" title="Up (Backspace)" aria-label="Up one level">${icon('fx-up', 16)}</button>+ <button class="fx-btn" data-act="refresh" title="Refresh (F5)" aria-label="Refresh">${icon('reload', 16)}</button>+ </div>+ <div class="fx-addr" data-role="addr" title="Click to edit the address (Ctrl+L)"></div>+ <label class="fx-search">${icon('search', 14)}<input type="search" placeholder="Search" aria-label="Search this folder" spellcheck="false" autocomplete="off" /></label>+ </div>+ <div class="fx-cmd" role="toolbar" aria-label="File commands" data-role="cmd"></div>+ <div class="fx-body">+ <nav class="fx-side" aria-label="Navigation" data-role="side"></nav>+ <main class="fx-main">+ <div class="fx-scroll" tabindex="0" role="listbox" aria-multiselectable="true" aria-label="Files" data-role="scroll"></div>+ <div class="fx-drop" data-role="dropmsg" hidden></div>+ </main>+ </div>+ <div class="fx-status" role="status" data-role="status"></div>+ <input type="file" multiple hidden data-role="file" />`;+ host.append(root);+ const $ = (r) => root.querySelector(`[data-role="${r}"]`);+ const addr = $('addr');+ const cmd = $('cmd');+ const side = $('side');+ const hdr = h('div', 'fx-hdr');+ const scroll = $('scroll');+ const statusEl = $('status');+ const fileInput = $('file');+ const searchInput = root.querySelector('.fx-search input');+ const dropMsg = $('dropmsg');++ /* --- derived --- */+ const isDirLoc = (l) => l !== HOME && l !== '/';+ const inTrash = () => st.loc === fs.TRASH || st.loc.startsWith(`${fs.TRASH}/`);+ const trashRoot = () => st.loc === fs.TRASH;+ const canWrite = () => isDirLoc(st.loc) && !inTrash() && !st.searching;+ const uploadDir = () => (canWrite() ? st.loc : '/Downloads');+ const selNodes = () => st.shown.filter((n) => st.sel.has(n.path));+ const nodeAt = (p) => st.shown.find((n) => n.path === p);+ const err = (e) => ctx.toast(e?.message || 'Something went wrong');++ /* --- loading --- */+ async function fetchNodes(loc, query) {+ if (query) {+ const base = loc === HOME || loc === '/' ? '/' : loc;+ const all = await fs.walk(base);+ const keepTrash = inTrash();+ return filterByName(all.filter((n) => keepTrash || !n.path.startsWith(`${fs.TRASH}/`)), query);+ }+ if (loc === HOME) {+ const dirs = (await Promise.all(fs.DIRS.map((d) => fs.stat(`/${d}`)))).filter(Boolean);+ return [...dirs, ...(await fs.recentFiles(24))];+ }+ if (loc === '/') return (await fs.list('/')).filter((n) => n.path !== fs.TRASH);+ const node = await fs.stat(loc);+ if (!node) throw new Error(`"${loc}" does not exist.`);+ if (node.type !== 'dir') throw new Error(`"${loc}" is not a folder.`);+ return fs.list(loc);+ }++ async function load({ keepSel = false } = {}) {+ const my = ++token;+ st.dirty = false;+ const timer = setTimeout(() => {+ if (my === token && !dead) {+ st.loading = true;+ renderList();+ }+ }, 90);+ try {+ const nodes = await fetchNodes(st.loc, st.query.trim());+ if (my !== token || dead) return;+ st.nodes = nodes;+ st.error = null;+ st.searching = !!st.query.trim();+ const keep = new Set(nodes.map((n) => n.path));+ st.sel = keepSel ? new Set([...st.sel].filter((p) => keep.has(p))) : st.sel;+ applySort();+ } catch (e) {+ if (my !== token || dead) return;+ st.nodes = [];+ st.shown = [];+ st.error = e?.message || 'This location could not be read.';+ st.sel.clear();+ } finally {+ clearTimeout(timer);+ }+ if (my === token && !dead) {+ st.loading = false;+ renderAll();+ }+ }++ function applySort() {+ st.shown = sortNodes(st.nodes, st.sort);+ if (st.cursor && !nodeAt(st.cursor)) st.cursor = null;+ }++ async function go(loc, { push = true, select = null } = {}) {+ if (push) {+ st.hist = st.hist.slice(0, st.hi + 1);+ if (st.hist[st.hist.length - 1] !== loc) st.hist.push(loc);+ st.hi = st.hist.length - 1;+ }+ st.loc = loc;+ st.query = '';+ st.searching = false;+ searchInput.value = '';+ st.sel = new Set(select ? [select] : []);+ st.cursor = select;+ st.anchor = select;+ ctx.setTitle(locationName(loc));+ await load({ keepSel: !!select });+ if (select) els.get(select)?.scrollIntoView({ block: 'center' });+ }+ const goBack = () => st.hi > 0 && go(st.hist[--st.hi], { push: false });+ const goFwd = () => st.hi < st.hist.length - 1 && go(st.hist[++st.hi], { push: false });+ const goUp = () => {+ if (st.loc === HOME || st.loc === '/') return;+ go(fs.parentOf(st.loc));+ };++ /* --- rendering --- */+ function skeleton() {+ return `<div class="fx-skel" aria-busy="true" aria-label="Loading">${'<div class="fx-skel-row"><i></i><b></b></div>'.repeat(9)}</div>`;+ }++ const detailCols = () => (st.searching ? 'Location' : trashRoot() ? 'Original location' : '');++ function renderHeader() {+ if (st.view !== 'details' || st.error) {+ hdr.hidden = true;+ return;+ }+ hdr.hidden = false;+ const extra = detailCols();+ hdr.style.setProperty('--cols', extra ? 'minmax(160px,1fr) 150px 110px 80px minmax(120px,0.8fr)' : 'minmax(160px,1fr) 150px 110px 80px');+ const col = (key, label, cls = '') => {+ const on = st.sort.key === key;+ return `<button class="fx-th ${cls}" data-sort="${key}" aria-sort="${on ? (st.sort.dir === 'asc' ? 'ascending' : 'descending') : 'none'}">${label}${on ? `<span class="fx-caret">${st.sort.dir === 'asc' ? '▲' : '▼'}</span>` : ''}</button>`;+ };+ hdr.innerHTML = `<span class="fx-th-pad"></span>${col('name', 'Name')}${col('date', 'Date modified')}${col('type', 'Type')}${col('size', 'Size', 'r')}${extra ? `<span class="fx-th">${extra}</span>` : ''}`;+ }++ function storageHtml(big) {+ const u = st.usage;+ if (!u) return '';+ const pct = u.quota ? Math.max(1, Math.min(100, (u.used / u.quota) * 100)) : 0;+ const label = u.quota ? `${formatSize(u.used)} of ${formatSize(u.quota)} used` : `${formatSize(u.bytes)} in ${u.files} ${u.files === 1 ? 'file' : 'files'}`;+ return `<div class="fx-meter ${big ? 'big' : ''}"><div class="fx-meter-bar"${u.quota ? '' : ' hidden'}><i style="width:${pct.toFixed(1)}%"></i></div><span>${esc(label)}</span>${big && u.quota ? `<span class="fx-meter-sub">${esc(`${u.files} ${u.files === 1 ? 'file' : 'files'}, ${formatSize(u.bytes)} stored by this desktop`)}</span>` : ''}</div>`;+ }++ function itemHtml(n) {+ const loc = n.path;+ const extra = st.searching ? esc(fs.parentOf(loc)) : trashRoot() ? esc(n.trashedFrom ? fs.parentOf(n.trashedFrom) : '') : '';+ const kind = n.type === 'dir' ? 'dir' : fs.kindOf(n.name);+ const thumb = st.view === 'grid' && kind === 'image' ? ' data-thumb="1"' : '';+ const meta = st.view === 'details' ? `<span class="fx-c">${fmtDate(n.mtime)}</span><span class="fx-c">${esc(typeLabel(n))}</span><span class="fx-c r">${n.type === 'dir' ? '' : formatSize(n.size)}</span>${detailCols() ? `<span class="fx-c" title="${extra}">${extra}</span>` : ''}` : '';+ const tip = `${n.name}\n${typeLabel(n)}${n.type === 'dir' ? '' : `\nSize: ${formatSize(n.size)}`}\nModified: ${fmtDate(n.mtime)}`;+ return `<div class="fx-item k-${kind}${st.sel.has(loc) ? ' sel' : ''}${clip?.mode === 'cut' && clip.paths.includes(loc) ? ' cut' : ''}${st.cursor === loc ? ' cur' : ''}" role="option" aria-selected="${st.sel.has(loc)}" draggable="true" data-path="${esc(loc)}" data-type="${n.type}" title="${esc(tip)}"><span class="fx-ic"${thumb}>${icon(iconName(n), st.view === 'grid' ? 40 : 18)}</span><span class="fx-name">${esc(n.name)}</span>${meta}</div>`;+ }++ function emptyHtml() {+ if (st.searching) return `<div class="fx-empty">${icon('search', 40)}<h3>No results for “${esc(st.query.trim())}”</h3><p>Nothing in ${esc(locationName(st.loc))} matches that name. Check the spelling or try a shorter word.</p></div>`;+ if (trashRoot()) return `<div class="fx-empty">${icon('trash', 40)}<h3>The Recycle Bin is empty</h3><p>Files and folders you delete show up here until you empty it.</p></div>`;+ if (canWrite()) return `<div class="fx-empty">${icon('folder', 40)}<h3>This folder is empty</h3><p>Drop files here or use New.</p><div class="fx-empty-act"><button class="fx-pill" data-act="newfolder">New folder</button><button class="fx-pill" data-act="upload">Upload files</button></div></div>`;+ return `<div class="fx-empty">${icon('folder', 40)}<h3>Nothing here yet</h3><p>Open a folder such as Documents, then drop files here or use New.</p></div>`;+ }++ function renderList() {+ els.clear();+ scroll.className = `fx-scroll v-${st.view}`;+ scroll.removeAttribute('aria-busy');+ if (st.loading && !st.shown.length && !st.error) {+ scroll.innerHTML = skeleton();+ return;+ }+ if (st.error) {+ scroll.innerHTML = `<div class="fx-empty err">${icon('close', 40)}<h3>This location can’t be opened</h3><p>${esc(st.error)}</p><div class="fx-empty-act"><button class="fx-pill" data-act="refresh">Try again</button><button class="fx-pill" data-act="gohome">Go to Home</button></div></div>`;+ return;+ }+ const extra = detailCols();+ scroll.style.setProperty('--cols', extra ? 'minmax(160px,1fr) 150px 110px 80px minmax(120px,0.8fr)' : 'minmax(160px,1fr) 150px 110px 80px');+ const lead = st.loc === '/' ? `<div class="fx-pc">${icon('fx-drive', 34)}<div><b>Local storage</b>${storageHtml(true)}</div></div>` : '';+ scroll.innerHTML = st.shown.length ? `${lead}<div class="fx-items">${st.shown.map(itemHtml).join('')}</div>` : `${lead}${emptyHtml()}`;+ if (!hdr.hidden) scroll.prepend(hdr);+ for (const el of scroll.querySelectorAll('.fx-item')) els.set(el.dataset.path, el);+ observeThumbs();+ }++ function renderCmd() {+ const sel = selNodes();+ const one = sel.length === 1;+ const files = sel.filter((n) => n.type === 'file');+ const w = canWrite();+ const b = (act, ic, label, { dis = false, title = '', cls = '' } = {}) =>+ `<button class="fx-cb ${cls}" data-act="${act}" ${dis ? 'disabled' : ''} title="${esc(title || label)}" aria-label="${esc(label)}">${icon(ic, 16)}<span>${esc(label)}</span></button>`;+ const sep = '<i class="fx-sep"></i>';+ const viewBtn = (v, ic, label) => `<button class="fx-vb ${st.view === v ? 'on' : ''}" data-view="${v}" title="${label}" aria-label="${label}" aria-pressed="${st.view === v}">${icon(ic, 16)}</button>`;+ let left;+ if (trashRoot()) {+ left = `${b('restore', 'fx-restore', 'Restore', { dis: !sel.length, title: 'Restore the selected items' })}${b('purge', 'trash', 'Delete permanently', { dis: !sel.length })}${b('empty', 'trash', 'Empty Recycle Bin', { dis: !st.nodes.length })}`;+ } else {+ left = `${b('newfolder', 'fx-newfolder', 'New folder', { dis: !w, title: w ? 'New folder' : 'Open a folder to create items in it' })}${b('newfile', 'fx-newfile', 'New text document', { dis: !w })}${b('upload', 'upload', 'Upload', { title: `Upload files to ${locationName(uploadDir())}` })}${sep}${b('cut', 'fx-cut', 'Cut', { dis: !sel.length || inTrash(), cls: 'sec' })}${b('copy', 'fx-copy', 'Copy', { dis: !sel.length, cls: 'sec' })}${b('paste', 'fx-paste', 'Paste', { dis: !w || !clip, cls: 'sec' })}${b('rename', 'edit', 'Rename', { dis: !one || inTrash(), cls: 'sec' })}${b('delete', 'trash', 'Delete', { dis: !sel.length, cls: 'sec' })}${b('download', 'download', 'Download', { dis: !files.length, cls: 'sec' })}`;+ }+ cmd.innerHTML = `${left}<span class="fx-grow"></span>${b('sort', 'fx-sort', 'Sort', { title: 'Sort and order', cls: 'sec' })}<span class="fx-views" role="group" aria-label="View">${viewBtn('list', 'list', 'List')}${viewBtn('details', 'fx-detail', 'Details')}${viewBtn('grid', 'fx-tiles', 'Large icons')}</span>`;+ root.querySelector('[data-act="back"]').disabled = st.hi <= 0;+ root.querySelector('[data-act="fwd"]').disabled = st.hi >= st.hist.length - 1;+ root.querySelector('[data-act="up"]').disabled = st.loc === HOME || st.loc === '/';+ }++ function renderStatus() {+ statusEl.textContent = st.error ? '' : statusText(st.shown.length, selectionSummary(selNodes()));+ }++ function renderAddr() {+ if (addr.querySelector('input')) return;+ const crumbs = buildCrumbs(st.loc);+ addr.innerHTML = `<span class="fx-crumbs">${crumbs.map((c, i) => `${i ? `<span class="fx-chev" aria-hidden="true">${icon('chevron', 10)}</span>` : ''}<button class="fx-crumb" data-go="${esc(c.path)}" ${i === crumbs.length - 1 ? 'aria-current="page"' : ''}>${esc(c.name)}</button>`).join('')}</span>`;+ const c = addr.firstElementChild;+ c.scrollLeft = c.scrollWidth;+ }++ function renderSide() {+ const link = (path, ic, label, extra = '') =>+ `<button class="fx-nv${st.loc === path ? ' on' : ''}" data-go="${esc(path)}" ${isDirLoc(path) ? `data-drop="${esc(path)}"` : ''}>${icon(ic, 16)}<span>${esc(label)}</span>${extra}</button>`;+ side.innerHTML = `+ ${link(HOME, 'home', 'Home')}+ <div class="fx-nh">Quick access</div>+ ${fs.DIRS.map((d) => link(`/${d}`, DIR_ICON[d] || 'folder', d)).join('')}+ <div class="fx-nh">Devices</div>+ ${link('/', 'pc', 'This PC')}+ ${storageHtml(false)}+ <div class="fx-nh">Bin</div>+ <button class="fx-nv${trashRoot() ? ' on' : ''}" data-go="${fs.TRASH}" data-drop="${fs.TRASH}">${icon('trash', 16)}<span>Recycle Bin</span>${st.trashCount ? `<em class="fx-count">${st.trashCount}</em>` : ''}</button>`;+ }++ function renderAll() {+ renderAddr();+ renderHeader();+ renderList();+ renderCmd();+ renderStatus();+ renderSide();+ }++ function paintSelection() {+ for (const [p, el] of els) {+ const on = st.sel.has(p);+ el.classList.toggle('sel', on);+ el.classList.toggle('cur', st.cursor === p);+ el.classList.toggle('cut', clip?.mode === 'cut' && clip.paths.includes(p));+ el.setAttribute('aria-selected', on);+ }+ renderCmd();+ renderStatus();+ }++ /* --- thumbnails --- */+ let io = null;+ function observeThumbs() {+ io?.disconnect();+ const keep = new Set(st.shown.map((n) => n.path));+ for (const [p, t] of thumbs) {+ if (!keep.has(p)) {+ URL.revokeObjectURL(t.url);+ thumbs.delete(p);+ }+ }+ if (st.view !== 'grid') return;+ io = new IntersectionObserver(+ (entries) => {+ for (const e of entries) {+ if (!e.isIntersecting) continue;+ io.unobserve(e.target);+ setThumb(e.target.closest('.fx-item'));+ }+ },+ { root: scroll, rootMargin: '200px' },+ );+ for (const t of scroll.querySelectorAll('[data-thumb]')) io.observe(t);+ }+ async function setThumb(item) {+ if (!item) return;+ const p = item.dataset.path;+ const node = nodeAt(p);+ if (!node) return;+ let t = thumbs.get(p);+ if (!t || t.mtime !== node.mtime) {+ if (t) URL.revokeObjectURL(t.url);+ const url = await fs.urlFor(p).catch(() => null);+ if (!url) return;+ t = { mtime: node.mtime, url };+ thumbs.set(p, t);+ }+ if (dead || els.get(p) !== item) return;+ const box = item.querySelector('.fx-ic');+ const img = new Image();+ img.alt = '';+ img.decoding = 'async';+ img.onload = () => box.replaceChildren(img);+ img.src = t.url;+ }++ /* --- selection --- */+ function select(paths, { cursor = paths[paths.length - 1] ?? null, anchor } = {}) {+ st.sel = new Set(paths);+ st.cursor = cursor;+ if (anchor !== undefined) st.anchor = anchor;+ paintSelection();+ }+ function clickItem(p, e) {+ const order = st.shown.map((n) => n.path);+ if (e.shiftKey) select(rangeSelect(order, st.anchor ?? p, p), { cursor: p });+ else if (e.ctrlKey || e.metaKey) {+ const s = new Set(st.sel);+ s.has(p) ? s.delete(p) : s.add(p);+ select([...s], { cursor: p, anchor: p });+ } else select([p], { cursor: p, anchor: p });+ }++ /* --- menus and dialogs --- */+ let menu = null;+ let menuOff = null;+ function closeMenu() {+ menu?.remove();+ menu = null;+ menuOff?.();+ menuOff = null;+ }+ function showMenu(x, y, items, { from = null } = {}) {+ closeMenu();+ const m = h('div', 'fx-menu');+ m.setAttribute('role', 'menu');+ for (const it of items) {+ if (it === '-') {+ m.append(h('hr'));+ continue;+ }+ const b = h('button', it.danger ? 'danger' : '');+ b.setAttribute('role', 'menuitem');+ b.disabled = !!it.disabled;+ b.innerHTML = `<span class="fx-mi">${it.check ? icon('check', 14) : it.icon ? icon(it.icon, 15) : ''}</span><span class="fx-ml">${esc(it.label)}</span>${it.kbd ? `<kbd>${esc(it.kbd)}</kbd>` : ''}`;+ b.addEventListener('click', () => {+ closeMenu();+ it.run();+ });+ m.append(b);+ }+ root.append(m);+ const r = root.getBoundingClientRect();+ const mw = m.offsetWidth;+ const mh = m.offsetHeight;+ m.style.left = `${Math.max(4, Math.min(x - r.left, r.width - mw - 4))}px`;+ m.style.top = `${Math.max(4, Math.min(y - r.top, r.height - mh - 4))}px`;+ menu = m;+ m.querySelector('button:not(:disabled)')?.focus();+ const onDown = (e) => {+ if (!m.contains(e.target)) closeMenu();+ };+ const onKey = (e) => {+ if (e.key === 'Escape') {+ e.preventDefault();+ e.stopPropagation();+ closeMenu();+ (from || scroll).focus?.();+ } else if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {+ e.preventDefault();+ const bs = [...m.querySelectorAll('button:not(:disabled)')];+ const i = bs.indexOf(document.activeElement);+ bs[(i + (e.key === 'ArrowDown' ? 1 : -1) + bs.length) % bs.length]?.focus();+ }+ };+ document.addEventListener('pointerdown', onDown, true);+ root.addEventListener('keydown', onKey, true);+ root.addEventListener('wheel', closeMenu, { passive: true });+ menuOff = () => {+ document.removeEventListener('pointerdown', onDown, true);+ root.removeEventListener('keydown', onKey, true);+ root.removeEventListener('wheel', closeMenu);+ };+ }++ /** Small in-window dialog. Resolves to true/false, or the input text (null on cancel) when `input` is set. */+ function ask({ title, message = '', input = null, ok = 'OK', danger = false, cancel = 'Cancel' }) {+ return new Promise((resolve) => {+ const wrap = h('div', 'fx-modal');+ wrap.innerHTML = `<form class="fx-dlg" role="dialog" aria-modal="true" aria-label="${esc(title)}"><h3>${esc(title)}</h3>${message ? `<p>${esc(message)}</p>` : ''}${input != null ? '<input class="fx-dlg-in" spellcheck="false" autocomplete="off" />' : ''}<div class="fx-dlg-act"><button type="button" class="fx-pill" data-x="no">${esc(cancel)}</button><button type="submit" class="fx-pill ${danger ? 'danger' : 'primary'}">${esc(ok)}</button></div></form>`;+ root.append(wrap);+ const inp = wrap.querySelector('input');+ const done = (v) => {+ wrap.remove();+ scroll.focus();+ resolve(v);+ };+ if (inp) {+ inp.value = input;+ inp.focus();+ const dot = input.lastIndexOf('.');+ inp.setSelectionRange(0, dot > 0 ? dot : input.length);+ } else wrap.querySelector('[type=submit]').focus();+ wrap.addEventListener('submit', (e) => {+ e.preventDefault();+ done(inp ? inp.value.trim() : true);+ });+ wrap.querySelector('[data-x]').addEventListener('click', () => done(inp ? null : false));+ wrap.addEventListener('keydown', (e) => {+ e.stopPropagation();+ if (e.key === 'Escape') done(inp ? null : false);+ });+ wrap.addEventListener('pointerdown', (e) => e.target === wrap && done(inp ? null : false));+ });+ }++ /* --- operations --- */+ async function open(node) {+ if (node.type === 'dir') return go(node.path);+ try {+ await ctx.openPath(node.path);+ } catch (e) {+ err(e);+ }+ }+ function openSelection() {+ const sel = selNodes();+ if (!sel.length) return;+ const dir = sel.find((n) => n.type === 'dir');+ if (dir) open(dir);+ else sel.forEach(open);+ }++ async function makeItem(kind) {+ if (!canWrite()) return;+ try {+ const name = await fs.uniqueName(st.loc, kind === 'dir' ? 'New folder' : 'New Text Document.txt');+ const p = fs.join(st.loc, name);+ if (kind === 'dir') await fs.mkdir(p);+ else await fs.write(p, '', { mime: 'text/plain' });+ await load();+ select([p], { anchor: p });+ els.get(p)?.scrollIntoView({ block: 'nearest' });+ startRename(p);+ } catch (e) {+ err(e);+ }+ }++ function startRename(path) {+ const el = els.get(path);+ const node = nodeAt(path);+ if (!el || !node || inTrash()) return;+ const label = el.querySelector('.fx-name');+ const input = h('input', 'fx-rename');+ input.value = node.name;+ input.spellcheck = false;+ input.setAttribute('aria-label', 'New name');+ label.replaceWith(input);+ st.renaming = path;+ input.focus();+ const dot = node.type === 'file' ? node.name.lastIndexOf('.') : -1;+ input.setSelectionRange(0, dot > 0 ? dot : node.name.length);+ let finished = false;+ const finish = async (commit) => {+ if (finished) return;+ finished = true;+ st.renaming = null;+ const v = input.value.trim();+ if (commit && v && v !== node.name) {+ try {+ const np = await fs.rename(path, v);+ st.sel = new Set([np]);+ st.cursor = np;+ await load({ keepSel: true });+ scroll.focus();+ return;+ } catch (e) {+ err(e);+ }+ }+ if (st.dirty) await load({ keepSel: true });+ else {+ input.replaceWith(label);+ scroll.focus();+ }+ };+ input.addEventListener('keydown', (e) => {+ e.stopPropagation();+ if (e.key === 'Enter') finish(true);+ else if (e.key === 'Escape') finish(false);+ });+ input.addEventListener('blur', () => finish(true));+ input.addEventListener('click', (e) => e.stopPropagation());+ input.addEventListener('dblclick', (e) => e.stopPropagation());+ }++ function setClip(mode) {+ const paths = selNodes().map((n) => n.path);+ if (!paths.length) return;+ clip = { mode, paths };+ ctx.toast(`${paths.length} ${paths.length === 1 ? 'item' : 'items'} ${mode === 'cut' ? 'cut' : 'copied'}`);+ paintSelection();+ }+ async function paste() {+ if (!clip || !canWrite()) return;+ const { mode, paths } = clip;+ const made = [];+ let failed = 0;+ for (const src of paths) {+ try {+ if (mode === 'cut' && fs.parentOf(src) === st.loc) continue;+ const dest = fs.join(st.loc, await fs.uniqueName(st.loc, fs.nameOf(src)));+ mode === 'cut' ? await fs.move(src, dest) : await fs.copy(src, dest);+ made.push(dest);+ } catch (e) {+ failed++;+ err(e);+ }+ }+ if (mode === 'cut') clip = null;+ await load();+ if (made.length) select(made, { anchor: made[0] });+ if (made.length && !failed) ctx.toast(`${mode === 'cut' ? 'Moved' : 'Pasted'} ${made.length} ${made.length === 1 ? 'item' : 'items'}`);+ }++ async function remove(permanent = false) {+ const sel = selNodes();+ if (!sel.length) return;+ const perm = permanent || inTrash();+ if (perm) {+ const msg = sel.length === 1 ? `"${sel[0].name}" will be permanently deleted. This can't be undone.` : `These ${sel.length} items will be permanently deleted. This can't be undone.`;+ if (!(await ask({ title: 'Delete permanently?', message: msg, ok: 'Delete', danger: true }))) return;+ }+ const idx = Math.max(0, st.shown.findIndex((n) => n.path === sel[0].path));+ let n = 0;+ for (const node of sel) {+ try {+ await (perm ? fs.purge(node.path) : fs.remove(node.path));+ n++;+ } catch (e) {+ err(e);+ }+ }+ st.sel.clear();+ await load();+ const next = st.shown[Math.min(idx, st.shown.length - 1)];+ if (next) select([next.path], { anchor: next.path });+ if (n) ctx.toast(perm ? `Deleted ${n} ${n === 1 ? 'item' : 'items'} permanently` : `Moved ${n} ${n === 1 ? 'item' : 'items'} to the Recycle Bin`);+ }++ async function restoreSel() {+ let n = 0;+ let last = null;+ for (const node of selNodes()) {+ try {+ last = await fs.restore(node.path);+ n++;+ } catch (e) {+ err(e);+ }+ }+ st.sel.clear();+ await load();+ refreshSide();+ if (n) ctx.toast(n === 1 ? `Restored to ${fs.parentOf(last)}` : `Restored ${n} items`);+ }+ async function emptyBin() {+ const count = st.nodes.length;+ if (!count) return;+ if (!(await ask({ title: 'Empty the Recycle Bin?', message: `${count} ${count === 1 ? 'item' : 'items'} will be permanently deleted. This can't be undone.`, ok: 'Empty Recycle Bin', danger: true }))) return;+ try {+ await fs.emptyTrash();+ ctx.toast('Recycle Bin emptied');+ } catch (e) {+ err(e);+ }+ await load();+ }++ async function download() {+ for (const node of selNodes().filter((n) => n.type === 'file')) {+ try {+ const f = await fs.read(node.path);+ if (!f) continue;+ const url = URL.createObjectURL(f.blob);+ const a = h('a');+ a.href = url;+ a.download = node.name;+ root.append(a);+ a.click();+ a.remove();+ setTimeout(() => URL.revokeObjectURL(url), 4000);+ } catch (e) {+ err(e);+ }+ }+ }++ async function uploadFiles(files, dir = uploadDir()) {+ const list = [...files];+ if (!list.length) return;+ const done = [];+ for (const f of list) {+ try {+ done.push(await fs.importFile(f, dir));+ } catch (e) {+ err(e);+ }+ }+ if (done.length) {+ ctx.toast(`Uploaded ${done.length} ${done.length === 1 ? 'file' : 'files'} to ${locationName(dir)}`);+ if (dir === st.loc) {+ await load();+ select(done, { anchor: done[0] });+ }+ }+ }++ async function moveInto(paths, dest, copy = false) {+ const ok = copy ? paths : movablePaths(paths, dest);+ if (!ok.length) return;+ let n = 0;+ for (const p of ok) {+ try {+ if (dest === fs.TRASH) {+ await fs.remove(p);+ } else {+ const to = fs.join(dest, await fs.uniqueName(dest, fs.nameOf(p)));+ copy ? await fs.copy(p, to) : await fs.move(p, to);+ }+ n++;+ } catch (e) {+ err(e);+ }+ }+ if (n) ctx.toast(`${copy ? 'Copied' : 'Moved'} ${n} ${n === 1 ? 'item' : 'items'} to ${locationName(dest)}`);+ await load();+ }++ /* --- menus --- */+ function sortMenu(x, y, from) {+ const key = (k, label) => ({ label, check: st.sort.key === k, run: () => setSort({ key: k }) });+ showMenu(x, y, [+ key('name', 'Name'),+ key('date', 'Date modified'),+ key('type', 'Type'),+ key('size', 'Size'),+ '-',+ { label: 'Ascending', check: st.sort.dir === 'asc', run: () => setSort({ dir: 'asc' }) },+ { label: 'Descending', check: st.sort.dir === 'desc', run: () => setSort({ dir: 'desc' }) },+ ], { from });+ }+ function setSort(patch) {+ st.sort = { ...st.sort, ...patch };+ ctx.store.set('files:sort', JSON.stringify(st.sort));+ applySort();+ renderHeader();+ renderList();+ paintSelection();+ }+ function setView(v) {+ if (st.view === v) return;+ st.view = v;+ ctx.store.set('files:view', v);+ renderHeader();+ renderList();+ paintSelection();+ if (st.cursor) els.get(st.cursor)?.scrollIntoView({ block: 'nearest' });+ }++ function itemMenu(x, y) {+ const sel = selNodes();+ const one = sel.length === 1;+ const files = sel.filter((n) => n.type === 'file');+ if (trashRoot()) {+ return showMenu(x, y, [+ { label: 'Restore', icon: 'fx-restore', run: restoreSel },+ { label: 'Delete permanently', icon: 'trash', danger: true, kbd: 'Del', run: () => remove(true) },+ ]);+ }+ showMenu(x, y, [+ { label: one && sel[0].type === 'dir' ? 'Open folder' : 'Open', icon: 'external', kbd: 'Enter', run: openSelection },+ ...(inTrash() ? [] : [+ '-',+ { label: 'Cut', icon: 'fx-cut', kbd: 'Ctrl+X', run: () => setClip('cut') },+ { label: 'Copy', icon: 'fx-copy', kbd: 'Ctrl+C', run: () => setClip('copy') },+ { label: 'Rename', icon: 'edit', kbd: 'F2', disabled: !one, run: () => startRename(sel[0].path) },+ ]),+ { label: 'Download', icon: 'download', disabled: !files.length, run: download },+ '-',+ { label: inTrash() || st.searching && sel.some((n) => n.path.startsWith(fs.TRASH)) ? 'Delete permanently' : 'Delete', icon: 'trash', kbd: 'Del', danger: true, run: () => remove(false) },+ ]);+ }+ function backgroundMenu(x, y) {+ const w = canWrite();+ if (trashRoot()) {+ return showMenu(x, y, [+ { label: 'Empty Recycle Bin', icon: 'trash', disabled: !st.nodes.length, run: emptyBin },+ '-',+ { label: 'Refresh', icon: 'reload', kbd: 'F5', run: () => load({ keepSel: true }) },+ ]);+ }+ showMenu(x, y, [+ { label: 'List', check: st.view === 'list', run: () => setView('list') },+ { label: 'Details', check: st.view === 'details', run: () => setView('details') },+ { label: 'Large icons', check: st.view === 'grid', run: () => setView('grid') },+ '-',+ { label: 'Sort by', icon: 'fx-sort', run: () => sortMenu(x, y) },+ { label: 'Refresh', icon: 'reload', kbd: 'F5', run: () => load({ keepSel: true }) },+ '-',+ { label: 'New folder', icon: 'fx-newfolder', disabled: !w, run: () => makeItem('dir') },+ { label: 'New text document', icon: 'fx-newfile', disabled: !w, run: () => makeItem('file') },+ { label: 'Paste', icon: 'fx-paste', kbd: 'Ctrl+V', disabled: !w || !clip, run: paste },+ { label: 'Upload files', icon: 'upload', run: () => fileInput.click() },+ ]);+ }++ /* --- events --- */+ const actions = {+ back: goBack,+ fwd: goFwd,+ up: goUp,+ refresh: () => load({ keepSel: true }),+ gohome: () => go(HOME),+ newfolder: () => makeItem('dir'),+ newfile: () => makeItem('file'),+ upload: () => fileInput.click(),+ cut: () => setClip('cut'),+ copy: () => setClip('copy'),+ paste,+ rename: () => st.sel.size === 1 && startRename([...st.sel][0]),+ delete: () => remove(false),+ download,+ restore: restoreSel,+ purge: () => remove(true),+ empty: emptyBin,+ };++ root.addEventListener('click', (e) => {+ const t = e.target;+ const act = t.closest('[data-act]');+ if (act && !act.disabled) {+ if (act.dataset.act === 'sort') {+ const r = act.getBoundingClientRect();+ sortMenu(r.left, r.bottom + 4, act);+ } else actions[act.dataset.act]?.();+ return;+ }+ const vb = t.closest('[data-view]');+ if (vb) return setView(vb.dataset.view);+ const th = t.closest('[data-sort]');+ if (th) return setSort({ key: th.dataset.sort, dir: st.sort.key === th.dataset.sort && st.sort.dir === 'asc' ? 'desc' : 'asc' });+ const nav = t.closest('[data-go]');+ if (nav) return go(nav.dataset.go);+ if (t.closest('.fx-addr') && !addr.querySelector('input')) return editAddr();+ const item = t.closest('.fx-item');+ if (item && scroll.contains(item)) {+ scroll.focus({ preventScroll: true });+ return clickItem(item.dataset.path, e);+ }+ if (scroll.contains(t) && !t.closest('button')) {+ scroll.focus({ preventScroll: true });+ if (!e.ctrlKey && !e.shiftKey) select([], { cursor: null });+ }+ });+ scroll.addEventListener('dblclick', (e) => {+ const item = e.target.closest('.fx-item');+ if (!item || e.target.closest('input')) return;+ const node = nodeAt(item.dataset.path);+ if (node) open(node);+ });+ root.addEventListener('contextmenu', (e) => {+ if (e.target.closest('input')) return;+ if (!scroll.contains(e.target) && !e.target.closest('.fx-pc')) return;+ e.preventDefault();+ const item = e.target.closest('.fx-item');+ if (item) {+ if (!st.sel.has(item.dataset.path)) select([item.dataset.path], { anchor: item.dataset.path });+ itemMenu(e.clientX, e.clientY);+ } else {+ if (st.sel.size) select([], { cursor: null });+ backgroundMenu(e.clientX, e.clientY);+ }+ });+ root.addEventListener('auxclick', (e) => {+ if (e.button === 3) {+ e.preventDefault();+ goBack();+ } else if (e.button === 4) {+ e.preventDefault();+ goFwd();+ }+ });+ fileInput.addEventListener('change', async () => {+ const files = [...fileInput.files];+ fileInput.value = '';+ await uploadFiles(files);+ });++ // Search+ let searchTimer = 0;+ const runSearch = () => {+ clearTimeout(searchTimer);+ st.query = searchInput.value;+ st.sel.clear();+ load();+ };+ searchInput.addEventListener('input', () => {+ clearTimeout(searchTimer);+ searchTimer = setTimeout(runSearch, 220);+ });+ searchInput.addEventListener('keydown', (e) => {+ e.stopPropagation();+ if (e.key === 'Enter') runSearch();+ if (e.key === 'Escape') {+ searchInput.value = '';+ runSearch();+ scroll.focus();+ }+ if (e.key === 'ArrowDown') {+ e.preventDefault();+ scroll.focus();+ if (st.shown[0]) select([st.shown[0].path], { anchor: st.shown[0].path });+ }+ });++ // Address bar editing+ function editAddr() {+ if (addr.querySelector('input')) return;+ const input = h('input', 'fx-addr-in');+ input.value = st.loc === HOME ? 'Home' : st.loc;+ input.spellcheck = false;+ input.setAttribute('aria-label', 'Address');+ addr.replaceChildren(input);+ input.focus();+ input.select();+ let finished = false;+ const finish = async (commit) => {+ if (finished) return;+ if (commit) {+ const target = parseAddress(input.value);+ if (target !== st.loc) {+ const ok = target === HOME || target === '/' || (await fs.stat(target))?.type === 'dir';+ if (!ok) {+ input.classList.add('bad');+ input.title = `"${input.value}" is not a folder on this PC.`;+ ctx.toast(`Can't find a folder at "${input.value}"`);+ return;+ }+ finished = true;+ addr.replaceChildren();+ await go(target);+ return;+ }+ }+ finished = true;+ addr.replaceChildren();+ renderAddr();+ scroll.focus();+ };+ input.addEventListener('keydown', (e) => {+ e.stopPropagation();+ if (e.key === 'Enter') finish(true);+ if (e.key === 'Escape') finish(false);+ });+ input.addEventListener('blur', () => finish(false));+ }++ // Keyboard+ root.addEventListener('keydown', (e) => {+ const t = e.target;+ if (t.matches('input, textarea')) return;+ const mod = e.ctrlKey || e.metaKey;+ const k = e.key;+ if (e.altKey && k === 'ArrowLeft') return e.preventDefault(), goBack();+ if (e.altKey && k === 'ArrowRight') return e.preventDefault(), goFwd();+ if (e.altKey && k === 'ArrowUp') return e.preventDefault(), goUp();+ if (mod && k.toLowerCase() === 'l') return e.preventDefault(), editAddr();+ if (mod && k.toLowerCase() === 'f') return e.preventDefault(), searchInput.focus();+ if (k === 'F5') return e.preventDefault(), load({ keepSel: true });+ if (!scroll.contains(t) && t !== scroll) return;+ if (mod && k.toLowerCase() === 'a') return e.preventDefault(), select(st.shown.map((n) => n.path), { cursor: st.cursor, anchor: st.shown[0]?.path });+ if (mod && k.toLowerCase() === 'c') return e.preventDefault(), setClip('copy');+ if (mod && k.toLowerCase() === 'x') return e.preventDefault(), inTrash() || setClip('cut');+ if (mod && k.toLowerCase() === 'v') return e.preventDefault(), paste();+ if (k === 'F2') return e.preventDefault(), actions.rename();+ if (k === 'Delete') return e.preventDefault(), remove(e.shiftKey);+ if (k === 'Backspace') return e.preventDefault(), goUp();+ if (k === 'Enter') return e.preventDefault(), openSelection();+ if (k === 'Escape' && st.sel.size) return select([], { cursor: null });+ if (k === ' ' && mod && st.cursor) {+ e.preventDefault();+ const s = new Set(st.sel);+ s.has(st.cursor) ? s.delete(st.cursor) : s.add(st.cursor);+ return select([...s], { cursor: st.cursor, anchor: st.cursor });+ }+ if (['ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight', 'Home', 'End'].includes(k)) {+ e.preventDefault();+ const order = st.shown.map((n) => n.path);+ let cols = 1;+ if (st.view === 'grid' && els.size) {+ const first = els.values().next().value;+ cols = Math.max(1, [...els.values()].filter((el) => el.offsetTop === first.offsetTop).length);+ }+ const i = moveIndex(order.indexOf(st.cursor), k, order.length, cols);+ if (i < 0) return;+ const p = order[i];+ if (e.shiftKey) select(rangeSelect(order, st.anchor ?? p, p), { cursor: p });+ else select([p], { cursor: p, anchor: p });+ els.get(p)?.scrollIntoView({ block: 'nearest' });+ return;+ }+ if (k.length === 1 && !mod && !e.altKey) {+ const q = k.toLowerCase();+ const order = st.shown;+ const start = Math.max(0, order.findIndex((n) => n.path === st.cursor) + 1);+ const hit = [...order.slice(start), ...order.slice(0, start)].find((n) => n.name.toLowerCase().startsWith(q));+ if (hit) {+ select([hit.path], { cursor: hit.path, anchor: hit.path });+ els.get(hit.path)?.scrollIntoView({ block: 'nearest' });+ }+ }+ });++ // Drag and drop: items between folders, and real files from the OS+ root.addEventListener('dragstart', (e) => {+ const item = e.target.closest?.('.fx-item');+ if (!item) return;+ const p = item.dataset.path;+ if (!st.sel.has(p)) select([p], { anchor: p });+ const paths = [...st.sel];+ e.dataTransfer.setData('application/x-tws-paths', JSON.stringify(paths));+ e.dataTransfer.setData('text/plain', paths.map(fs.nameOf).join('\n'));+ e.dataTransfer.effectAllowed = 'copyMove';+ });+ const dropTargetOf = (e) => {+ const side = e.target.closest?.('[data-drop]');+ if (side) return side.dataset.drop;+ const item = e.target.closest?.('.fx-item[data-type="dir"]');+ if (item && !inTrash()) return item.dataset.path;+ return null;+ };+ const hasFiles = (e) => [...(e.dataTransfer?.types || [])].includes('Files');+ const hasInternal = (e) => [...(e.dataTransfer?.types || [])].includes('application/x-tws-paths');+ let hot = null;+ const setHot = (el) => {+ if (hot === el) return;+ hot?.classList.remove('drop-hot');+ hot = el;+ hot?.classList.add('drop-hot');+ };+ root.addEventListener('dragover', (e) => {+ const ext = hasFiles(e);+ if (!ext && !hasInternal(e)) return;+ const target = dropTargetOf(e);+ const zone = e.target.closest?.('[data-drop], .fx-item[data-type="dir"]');+ if (!target && !canWrite() && !ext) return;+ e.preventDefault();+ e.dataTransfer.dropEffect = ext ? 'copy' : e.ctrlKey ? 'copy' : 'move';+ setHot(zone && target ? zone : null);+ if (ext) {+ dropMsg.hidden = false;+ dropMsg.textContent = `Drop to upload to ${locationName(target || uploadDir())}`;+ }+ });+ root.addEventListener('dragleave', (e) => {+ if (!root.contains(e.relatedTarget)) {+ setHot(null);+ dropMsg.hidden = true;+ }+ });+ root.addEventListener('drop', async (e) => {+ const ext = hasFiles(e);+ const internal = hasInternal(e);+ if (!ext && !internal) return;+ e.preventDefault();+ const target = dropTargetOf(e);+ setHot(null);+ dropMsg.hidden = true;+ if (internal) {+ let paths = [];+ try {+ paths = JSON.parse(e.dataTransfer.getData('application/x-tws-paths'));+ } catch {+ return;+ }+ const dest = target || (canWrite() ? st.loc : null);+ if (dest) await moveInto(paths, dest, e.ctrlKey && dest !== fs.TRASH);+ return;+ }+ const files = [];+ let skipped = 0;+ for (const it of e.dataTransfer.items || []) {+ if (it.kind !== 'file') continue;+ if (it.webkitGetAsEntry?.()?.isDirectory) skipped++;+ else if (it.getAsFile()) files.push(it.getAsFile());+ }+ if (skipped) ctx.toast('Folders can\'t be dropped yet. Drop the files inside them instead.');+ const dest = target && target !== fs.TRASH ? target : uploadDir();+ await uploadFiles(files.length || skipped ? files : [...e.dataTransfer.files], dest);+ });++ /* --- live refresh --- */+ let refreshTimer = 0;+ const unsub = fs.subscribe(() => {+ clearTimeout(refreshTimer);+ refreshTimer = setTimeout(() => {+ if (dead) return;+ refreshSide();+ if (st.renaming) st.dirty = true;+ else load({ keepSel: true });+ }, 80);+ });+ async function refreshSide() {+ try {+ const [u, trash] = await Promise.all([fs.usage(), fs.list(fs.TRASH)]);+ const est = (await navigator.storage?.estimate?.().catch(() => null)) || {};+ if (dead) return;+ st.usage = { ...u, used: est.usage || 0, quota: est.quota || 0 };+ st.trashCount = trash.length;+ renderSide();+ const pc = scroll.querySelector('.fx-pc > div');+ if (pc) pc.innerHTML = `<b>Local storage</b>${storageHtml(true)}`;+ } catch {+ /* the sidebar simply keeps its previous numbers */+ }+ }++ /* --- launch args --- */+ async function applyArg(arg) {+ if (!arg || typeof arg !== 'string') return go(HOME);+ const p = parseAddress(arg);+ if (p === HOME || p === '/') return go(p);+ const node = await fs.stat(p);+ if (!node) {+ ctx.toast(`"${arg}" does not exist`);+ return go(HOME);+ }+ if (node.type === 'dir') return go(p);+ return go(fs.parentOf(p), { select: p });+ }+ ctx.onArg((a) => applyArg(a));++ renderAll();+ refreshSide();+ applyArg(ctx.arg).then(() => scroll.focus({ preventScroll: true }));++ return () => {+ dead = true;+ clearTimeout(searchTimer);+ clearTimeout(refreshTimer);+ unsub();+ closeMenu();+ io?.disconnect();+ for (const t of thumbs.values()) URL.revokeObjectURL(t.url);+ thumbs.clear();+ };+}diff --git a/src/desktop/os/apps/media.css b/src/desktop/os/apps/media.cssnew file mode 100644index 000000000..47360a566--- /dev/null+++ b/src/desktop/os/apps/media.css@@ -0,0 +1,65 @@+.napp-media { height: 100%; background: var(--card); color: var(--text); }+.napp-media .md { height: 100%; display: flex; flex-direction: column; outline: 0; min-height: 0; }+.napp-media .md-body { position: relative; flex: 1; min-height: 0; display: flex; }+.napp-media .md-stage { position: relative; flex: 1; min-width: 0; background: #08090c; display: flex; align-items: center; justify-content: center; overflow: hidden; }+.napp-media .md-video { width: 100%; height: 100%; object-fit: contain; display: none; background: #000; }+.napp-media .md-stage[data-kind=video] .md-video { display: block; }+.napp-media .md-stage[data-kind=audio] .md-video { display: block; position: absolute; width: 1px; height: 1px; opacity: 0; pointer-events: none; }+.napp-media .md-vis { display: none; position: absolute; inset: 0; width: 100%; height: 100%; }+.napp-media .md-stage[data-kind=audio] .md-vis { display: block; }+.napp-media .md-empty { text-align: center; max-width: 340px; padding: 24px; color: #c8ccd4; }+.napp-media .md-stage:not([data-kind=none]) .md-empty { display: none; }+.napp-media .md-empty-ico { color: var(--accent); margin-bottom: 8px; display: flex; justify-content: center; }+.napp-media .md-empty h3 { margin: 0 0 6px; font-size: 17px; }+.napp-media .md-empty p { margin: 0 0 14px; color: #8e95a3; font-size: 13px; line-height: 1.5; }+.napp-media .md-drop { display: none; position: absolute; inset: 10px; border: 2px dashed var(--accent); border-radius: 12px; align-items: center; justify-content: center; color: #fff; background: rgba(0,0,0,.55); font-size: 16px; pointer-events: none; }+.napp-media .md-stage.drop .md-drop { display: flex; }+.napp-media .md-import { position: absolute; left: 12px; top: 12px; display: flex; gap: 10px; align-items: center; padding: 6px 6px 6px 12px; border-radius: 999px; background: rgba(0,0,0,.6); color: #fff; font-size: 12px; backdrop-filter: blur(8px); }+.napp-media .md-import[hidden] { display: none; }+.napp-media .md-btn { padding: 7px 14px; border-radius: 6px; background: var(--hover); border: 1px solid var(--bd); color: var(--text); }+.napp-media .md-btn.pri { background: var(--accent); border-color: var(--accent); color: #fff; }+.napp-media .md-btn:hover { filter: brightness(1.12); }+.napp-media .md-btn:active { filter: brightness(.9); }+.napp-media .md-list { width: 250px; flex: none; border-left: 1px solid var(--bd); overflow-y: auto; background: var(--card); }+.napp-media .md.no-list .md-list { display: none; }+.napp-media .md-lh { display: flex; justify-content: space-between; padding: 10px 12px; color: var(--text2); position: sticky; top: 0; background: var(--card); border-bottom: 1px solid var(--bd); }+.napp-media .md-lempty { padding: 16px 14px; color: var(--text2); font-size: 12.5px; line-height: 1.5; }+.napp-media .md-item { display: flex; width: 100%; align-items: center; gap: 10px; padding: 8px 12px; text-align: left; }+.napp-media .md-item:hover { background: var(--hover); }+.napp-media .md-item.on { background: color-mix(in srgb, var(--accent) 20%, transparent); }+.napp-media .md-ii { color: var(--accent); flex: none; display: flex; }+.napp-media .md-in { flex: 1; min-width: 0; display: flex; flex-direction: column; }+.napp-media .md-in b, .napp-media .md-in small { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-weight: 500; }+.napp-media .md-in small { color: var(--text2); font-size: 11px; }+.napp-media .md-item em { font-style: normal; color: var(--text2); font-size: 11px; flex: none; }+.napp-media .md-bar { flex: none; border-top: 1px solid var(--bd); padding: 6px 12px 10px; background: var(--card); }+.napp-media .md-seekrow { display: flex; align-items: center; gap: 10px; }+.napp-media .md-t { font-variant-numeric: tabular-nums; color: var(--text2); font-size: 12px; min-width: 40px; }+.napp-media .md-t[data-t=dur] { text-align: right; }+.napp-media input[type=range] { -webkit-appearance: none; appearance: none; height: 4px; border-radius: 2px; background: var(--fill, #8884); cursor: pointer; margin: 0; }+.napp-media .md-seek { flex: 1; background: linear-gradient(to right, var(--accent) var(--p, 0%), var(--fill, #8884) var(--p, 0%)); }+.napp-media input[type=range]::-webkit-slider-thumb { -webkit-appearance: none; width: 12px; height: 12px; border-radius: 50%; background: var(--text); border: 0; }+.napp-media input[type=range]::-moz-range-thumb { width: 12px; height: 12px; border-radius: 50%; background: var(--text); border: 0; }+.napp-media input[type=range]:disabled { opacity: .4; cursor: default; }+.napp-media input[type=range]:focus-visible { outline: 2px solid var(--accent); outline-offset: 4px; }+.napp-media .md-ctl { display: grid; grid-template-columns: 1fr auto 1fr; align-items: center; gap: 8px; margin-top: 4px; }+.napp-media .md-now { min-width: 0; display: flex; flex-direction: column; }+.napp-media .md-now b, .napp-media .md-now small { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }+.napp-media .md-now small { color: var(--text2); font-size: 11px; }+.napp-media .md-main, .napp-media .md-side { display: flex; align-items: center; gap: 4px; }+.napp-media .md-side { justify-content: flex-end; }+.napp-media .md-ib { position: relative; width: 34px; height: 34px; border-radius: 8px; display: inline-flex; align-items: center; justify-content: center; color: var(--text); }+.napp-media .md-ib:hover { background: var(--hover); }+.napp-media .md-ib:active { background: var(--hover-b, var(--hover)); transform: scale(.94); }+.napp-media .md-ib.on { color: var(--accent); }+.napp-media .md-ib[hidden] { display: none; }+.napp-media .md-play { width: 42px; height: 42px; border-radius: 50%; background: var(--accent); color: #fff; }+.napp-media .md-play:hover { background: var(--accent); filter: brightness(1.12); }+.napp-media .md-one { position: absolute; right: 4px; bottom: 3px; font-size: 9px; font-style: normal; font-weight: 700; color: var(--accent); }+.napp-media .md-vol { width: 80px; }+.napp-media .md-speed { background: var(--hover); color: var(--text); border: 1px solid var(--bd); border-radius: 6px; padding: 4px 6px; font: inherit; }+@media (max-width: 640px) {+ .napp-media .md-list { position: absolute; inset: 0 0 auto auto; height: 60%; z-index: 2; }+ .napp-media .md-ctl { grid-template-columns: 1fr; justify-items: center; }+ .napp-media .md-vol { width: 60px; }+}diff --git a/src/desktop/os/apps/media.js b/src/desktop/os/apps/media.jsnew file mode 100644index 000000000..c18b1fa44--- /dev/null+++ b/src/desktop/os/apps/media.js@@ -0,0 +1,591 @@+// Media Player: audio and video from the virtual file system or the computer,+// a queue built from /Music and /Videos, a WebAudio visualizer for audio, and+// Media Session hardware-key support.+import './media.css';+import {+ mediaKind, titleFromName, formatTime, SPEEDS, clamp, buildOrder, nextIndex, prevIndex, buildLibrary, updateResume,+} from './playlist-logic.js';++const POS_KEY = 'tws:media:pos';+const PREF_KEY = 'tws:media:prefs';++export function mount(host, ctx) {+ const { h, esc, fs } = ctx;+ ctx.registerGlyph('m-shuffle', '<path d="M3 7h3c3 0 4 2 6 5s3 5 6 5h3M3 17h3c1.5 0 2.5-.6 3.4-1.6M14.6 8.6C15.5 7.6 16.5 7 18 7h3M18 4l3 3-3 3M18 14l3 3-3 3"/>');+ ctx.registerGlyph('m-repeat', '<path d="M4 11V9a3 3 0 0 1 3-3h13M17 3l3 3-3 3M20 13v2a3 3 0 0 1-3 3H4M7 21l-3-3 3-3"/>');+ ctx.registerGlyph('m-mute', '<path d="M4 9h3.5L12 5v14l-4.5-4H4zM16 9.5l5 5M21 9.5l-5 5"/>');+ ctx.registerGlyph('m-pip', '<rect x="3" y="5" width="18" height="14" rx="2"/><rect x="12" y="11" width="7" height="5" rx="1"/>');++ let prefs = { volume: 0.8, muted: false, speed: 1, repeat: 'off', shuffle: false, list: true };+ try {+ prefs = { ...prefs, ...JSON.parse(ctx.store.get(PREF_KEY) || '{}') };+ } catch {+ /* defaults */+ }+ const savePrefs = () => ctx.store.set(PREF_KEY, JSON.stringify(prefs));+ let resume = {};+ try {+ resume = JSON.parse(ctx.store.get(POS_KEY) || '{}') || {};+ } catch {+ resume = {};+ }++ const root = h('div', 'md');+ root.tabIndex = 0;+ root.innerHTML = `+ <div class="md-body">+ <div class="md-stage" data-kind="none">+ <video class="md-video" playsinline preload="metadata"></video>+ <canvas class="md-vis"></canvas>+ <div class="md-empty">+ <div class="md-empty-ico">${ctx.icon('music', 40)}</div>+ <h3>Nothing playing</h3>+ <p>Add music or video to your Music and Videos folders in File Explorer (upload or drag files in), or use <b>Add</b> to play files from your computer. You can also drop files here.</p>+ <button class="md-btn pri" data-a="add">Add files</button>+ </div>+ <div class="md-drop">Drop to play</div>+ </div>+ <aside class="md-list" aria-label="Play queue"></aside>+ </div>+ <div class="md-bar">+ <div class="md-seekrow"><span class="md-t" data-t="cur">0:00</span><input class="md-seek" type="range" min="0" max="1000" value="0" aria-label="Seek" disabled><span class="md-t" data-t="dur">0:00</span></div>+ <div class="md-ctl">+ <div class="md-now"><b data-now="title">-</b><small data-now="sub"></small></div>+ <div class="md-main">+ <button class="md-ib" data-a="shuffle" title="Shuffle" aria-pressed="false">${ctx.icon('m-shuffle', 18)}</button>+ <button class="md-ib" data-a="prev" title="Previous (Shift+P)">${ctx.icon('prev', 20)}</button>+ <button class="md-ib md-play" data-a="play" title="Play (Space)">${ctx.icon('play', 22)}</button>+ <button class="md-ib" data-a="next" title="Next (Shift+N)">${ctx.icon('next', 20)}</button>+ <button class="md-ib" data-a="repeat" title="Repeat: off">${ctx.icon('m-repeat', 18)}<i class="md-one" hidden>1</i></button>+ </div>+ <div class="md-side">+ <select class="md-speed" aria-label="Playback speed">${SPEEDS.map((s) => `<option value="${s}">${s}x</option>`).join('')}</select>+ <button class="md-ib" data-a="mute" title="Mute (M)">${ctx.icon('volume', 18)}</button>+ <input class="md-vol" type="range" min="0" max="100" aria-label="Volume">+ <button class="md-ib" data-a="pip" title="Picture in picture" hidden>${ctx.icon('m-pip', 18)}</button>+ <button class="md-ib" data-a="fs" title="Fullscreen (F)">${ctx.icon('fullscreen', 18)}</button>+ <button class="md-ib" data-a="add" title="Add files">${ctx.icon('plus', 18)}</button>+ <button class="md-ib" data-a="list" title="Queue">${ctx.icon('list', 18)}</button>+ </div>+ </div>+ </div>+ <input type="file" accept="audio/*,video/*,.mp3,.wav,.ogg,.m4a,.flac,.mp4,.webm,.mov,.mkv" multiple hidden>`;+ host.append(root);+ const $ = (s) => root.querySelector(s);+ const stage = $('.md-stage');+ const video = $('.md-video');+ const vis = $('.md-vis');+ const listEl = $('.md-list');+ const seek = $('.md-seek');+ const vol = $('.md-vol');+ const fileIn = $('input[type=file]');+ const playBtn = $('[data-a=play]');++ let library = [];+ let extras = []; // opened by path from elsewhere, or picked from the computer+ let queue = [];+ let order = [];+ let cur = -1;+ let objUrl = null;+ let disposed = false;+ let seeking = false;+ let lastSave = 0;++ const setIcon = (btn, name, size) => {+ const old = btn.querySelector('svg');+ const tmp = h('span', null, ctx.icon(name, size));+ old ? old.replaceWith(tmp.firstElementChild) : btn.prepend(tmp.firstElementChild);+ };++ /* ---------------- queue ---------------- */+ function rebuildQueue() {+ const playing = queue[cur]?.id;+ queue = [...library, ...extras.filter((e) => !library.some((l) => l.path && l.path === e.path))];+ cur = playing ? queue.findIndex((q) => q.id === playing) : -1;+ order = buildOrder(queue.length, { shuffle: prefs.shuffle, current: cur });+ renderList();+ }+ async function loadLibrary() {+ try {+ const [m, v] = await Promise.all([fs.list('/Music'), fs.list('/Videos')]);+ library = buildLibrary([...m, ...v]);+ } catch {+ library = [];+ }+ if (!disposed) rebuildQueue();+ }+ function renderList() {+ const items = queue.map((q, i) => `+ <button class="md-item${i === cur ? ' on' : ''}" data-i="${i}">+ <span class="md-ii">${ctx.icon(q.kind === 'video' ? 'video' : 'music', 16)}</span>+ <span class="md-in"><b>${esc(titleFromName(q.name))}</b><small>${q.file ? 'From your computer' : esc(q.path.replace(/\/[^/]*$/, '') || '/')}</small></span>+ ${resume[q.path] ? `<em title="Resumes at ${formatTime(resume[q.path])}">${formatTime(resume[q.path])}</em>` : ''}+ </button>`);+ listEl.innerHTML = `<div class="md-lh"><b>Queue</b><span>${queue.length}</span></div>${+ queue.length ? `<div class="md-items">${items.join('')}</div>` : '<p class="md-lempty">Your Music and Videos folders are empty. Upload files in File Explorer or press Add.</p>'+ }`;+ }+ listEl.addEventListener('click', (e) => {+ const b = e.target.closest('[data-i]');+ if (b) playIndex(+b.dataset.i);+ });++ /* ---------------- playback ---------------- */+ let audioCtx = null;+ let analyser = null;+ function ensureAudioGraph() {+ if (audioCtx) return;+ try {+ audioCtx = new (window.AudioContext || window.webkitAudioContext)();+ const src = audioCtx.createMediaElementSource(video);+ analyser = audioCtx.createAnalyser();+ analyser.fftSize = 2048;+ analyser.smoothingTimeConstant = 0.8;+ src.connect(analyser);+ analyser.connect(audioCtx.destination);+ } catch {+ audioCtx = null;+ analyser = null;+ }+ }++ async function blobFor(item) {+ if (item.file) return item.file;+ const f = await fs.read(item.path);+ if (!f) throw new Error(`${item.name} no longer exists`);+ return f.blob;+ }++ async function playIndex(i, { startAt } = {}) {+ const item = queue[i];+ if (!item) return;+ cur = i;+ if (prefs.shuffle) order = buildOrder(queue.length, { shuffle: true, current: i });+ renderList();+ stage.dataset.kind = item.kind;+ ctx.setTitle(`${titleFromName(item.name)} - Media Player`);+ try {+ const blob = await blobFor(item);+ if (disposed || queue[cur] !== item) return;+ const url = URL.createObjectURL(blob);+ const prev = objUrl;+ objUrl = url;+ video.src = url;+ if (prev) URL.revokeObjectURL(prev);+ const at = startAt ?? resume[item.path] ?? 0;+ video.addEventListener('loadedmetadata', () => {+ if (at && at < video.duration - 5) video.currentTime = at;+ }, { once: true });+ ensureAudioGraph();+ await audioCtx?.resume?.();+ await video.play();+ } catch (err) {+ if (err?.name === 'NotAllowedError') return;+ ctx.toast(`Could not play ${item.name}: ${err.message || 'unsupported format'}`);+ }+ setSession(item);+ syncUi();+ updateImportBar();+ }++ function playNext(auto = false) {+ const n = nextIndex(order, cur, { repeat: prefs.repeat, auto });+ if (n == null) return;+ if (n === cur) {+ video.currentTime = 0;+ video.play().catch(() => {});+ } else playIndex(n, { startAt: 0 });+ }+ function playPrev() {+ if (video.currentTime > 3) {+ video.currentTime = 0;+ return;+ }+ const p = prevIndex(order, cur, { repeat: prefs.repeat });+ if (p != null) playIndex(p, { startAt: 0 });+ }+ const toggle = () => {+ if (cur < 0) {+ if (queue.length) playIndex(0);+ else fileIn.click();+ return;+ }+ video.paused ? (audioCtx?.resume?.(), video.play().catch(() => {})) : video.pause();+ };++ function saveResume(force) {+ const item = queue[cur];+ if (!item?.path || !video.duration) return;+ const now = Date.now();+ if (!force && now - lastSave < 3000) return;+ lastSave = now;+ resume = updateResume(resume, item.path, video.currentTime, video.duration);+ ctx.store.set(POS_KEY, JSON.stringify(resume));+ }++ /* ---------------- UI sync ---------------- */+ function syncUi() {+ const item = queue[cur];+ setIcon(playBtn, video.paused ? 'play' : 'pause', 22);+ playBtn.title = video.paused ? 'Play (Space)' : 'Pause (Space)';+ $('[data-now=title]').textContent = item ? titleFromName(item.name) : '-';+ $('[data-now=sub]').textContent = item ? (item.file ? 'From your computer' : item.path) : '';+ $('[data-a=shuffle]').setAttribute('aria-pressed', String(prefs.shuffle));+ $('[data-a=shuffle]').classList.toggle('on', prefs.shuffle);+ const rep = $('[data-a=repeat]');+ rep.classList.toggle('on', prefs.repeat !== 'off');+ rep.title = `Repeat: ${prefs.repeat}`;+ $('.md-one').hidden = prefs.repeat !== 'one';+ const muted = video.muted || video.volume === 0;+ setIcon($('[data-a=mute]'), muted ? 'm-mute' : 'volume', 18);+ $('[data-a=pip]').hidden = !(document.pictureInPictureEnabled && item?.kind === 'video');+ root.classList.toggle('no-list', !prefs.list);+ seek.disabled = !item;+ }+ function syncTime() {+ const d = video.duration;+ $('[data-t=cur]').textContent = formatTime(video.currentTime);+ $('[data-t=dur]').textContent = formatTime(d);+ if (!seeking && Number.isFinite(d) && d > 0) seek.value = String((video.currentTime / d) * 1000);+ seek.style.setProperty('--p', `${(Number(seek.value) / 10).toFixed(1)}%`);+ if ('mediaSession' in navigator && Number.isFinite(d) && d > 0) {+ try {+ navigator.mediaSession.setPositionState({ duration: d, position: clamp(video.currentTime, 0, d), playbackRate: video.playbackRate });+ } catch {+ /* position state is optional */+ }+ }+ }++ video.addEventListener('timeupdate', () => {+ syncTime();+ saveResume(false);+ });+ video.addEventListener('durationchange', syncTime);+ video.addEventListener('play', () => {+ syncUi();+ startVis();+ if ('mediaSession' in navigator) navigator.mediaSession.playbackState = 'playing';+ });+ video.addEventListener('pause', () => {+ syncUi();+ saveResume(true);+ if ('mediaSession' in navigator) navigator.mediaSession.playbackState = 'paused';+ });+ video.addEventListener('ended', () => {+ const item = queue[cur];+ if (item?.path) {+ resume = updateResume(resume, item.path, 0, video.duration);+ ctx.store.set(POS_KEY, JSON.stringify(resume));+ }+ renderList();+ playNext(true);+ });+ video.addEventListener('error', () => {+ if (!video.src) return;+ const item = queue[cur];+ ctx.toast(`${item ? item.name : 'This file'} could not be played. The format may not be supported by this browser.`);+ });+ video.addEventListener('dblclick', () => toggleFs());+ video.addEventListener('click', toggle);++ seek.addEventListener('input', () => {+ seeking = true;+ if (Number.isFinite(video.duration)) $('[data-t=cur]').textContent = formatTime((seek.value / 1000) * video.duration);+ seek.style.setProperty('--p', `${(seek.value / 10).toFixed(1)}%`);+ });+ seek.addEventListener('change', () => {+ if (Number.isFinite(video.duration)) video.currentTime = (seek.value / 1000) * video.duration;+ seeking = false;+ });+ vol.value = String(Math.round(prefs.volume * 100));+ video.volume = prefs.volume;+ video.muted = prefs.muted;+ video.playbackRate = prefs.speed;+ $('.md-speed').value = String(prefs.speed);+ vol.addEventListener('input', () => {+ video.volume = vol.value / 100;+ video.muted = false;+ prefs.volume = video.volume;+ prefs.muted = false;+ savePrefs();+ syncUi();+ });+ $('.md-speed').addEventListener('change', (e) => {+ prefs.speed = +e.target.value;+ video.playbackRate = prefs.speed;+ savePrefs();+ });++ function toggleFs() {+ if (document.fullscreenElement) document.exitFullscreen?.();+ else (queue[cur]?.kind === 'video' ? stage : root).requestFullscreen?.().catch(() => ctx.toast('Fullscreen is not available here'));+ }+ root.addEventListener('click', (e) => {+ const a = e.target.closest('[data-a]')?.dataset.a;+ if (!a) return;+ if (a === 'play') toggle();+ else if (a === 'next') playNext(false);+ else if (a === 'prev') playPrev();+ else if (a === 'shuffle') {+ prefs.shuffle = !prefs.shuffle;+ order = buildOrder(queue.length, { shuffle: prefs.shuffle, current: cur });+ savePrefs();+ syncUi();+ } else if (a === 'repeat') {+ prefs.repeat = { off: 'all', all: 'one', one: 'off' }[prefs.repeat];+ savePrefs();+ syncUi();+ } else if (a === 'mute') {+ video.muted = !video.muted;+ prefs.muted = video.muted;+ savePrefs();+ syncUi();+ } else if (a === 'pip') {+ if (document.pictureInPictureElement) document.exitPictureInPicture();+ else video.requestPictureInPicture?.().catch(() => ctx.toast('Picture in picture is not available for this file'));+ } else if (a === 'fs') toggleFs();+ else if (a === 'add') fileIn.click();+ else if (a === 'list') {+ prefs.list = !prefs.list;+ savePrefs();+ syncUi();+ } else if (a === 'import') importCurrent();+ });++ root.addEventListener('keydown', (e) => {+ if (e.target.matches('select') || e.ctrlKey || e.metaKey || e.altKey) return;+ const onRange = e.target.matches('input[type=range]');+ const k = e.key;+ if (k === ' ' && !e.target.matches('button')) {+ e.preventDefault();+ toggle();+ } else if (k === 'ArrowLeft' && !onRange) {+ e.preventDefault();+ video.currentTime = Math.max(0, video.currentTime - 5);+ } else if (k === 'ArrowRight' && !onRange) {+ e.preventDefault();+ if (Number.isFinite(video.duration)) video.currentTime = Math.min(video.duration, video.currentTime + 5);+ } else if ((k === 'ArrowUp' || k === 'ArrowDown') && !onRange) {+ e.preventDefault();+ vol.value = String(clamp(+vol.value + (k === 'ArrowUp' ? 5 : -5), 0, 100));+ vol.dispatchEvent(new Event('input'));+ } else if (k.toLowerCase() === 'm') {+ video.muted = !video.muted;+ prefs.muted = video.muted;+ savePrefs();+ syncUi();+ } else if (k.toLowerCase() === 'f') toggleFs();+ else if (k === 'N') playNext(false);+ else if (k === 'P') playPrev();+ });++ /* ---------------- adding media ---------------- */+ function addFiles(files, { play = true } = {}) {+ const ok = [...files].filter((f) => mediaKind(f.name, f.type));+ if (!ok.length) {+ if (files.length) ctx.toast('Those files are not audio or video that the player understands');+ return;+ }+ const first = extras.length;+ for (const f of ok) extras.push({ id: `local:${f.name}:${f.size}:${f.lastModified}:${Math.random().toString(36).slice(2, 6)}`, file: f, name: f.name, kind: mediaKind(f.name, f.type), path: null });+ const firstId = extras[first].id;+ rebuildQueue();+ if (play) playIndex(queue.findIndex((q) => q.id === firstId));+ }+ fileIn.addEventListener('change', () => {+ addFiles(fileIn.files);+ fileIn.value = '';+ });+ ['dragenter', 'dragover'].forEach((t) => stage.addEventListener(t, (e) => {+ if (!e.dataTransfer?.types?.includes('Files')) return;+ e.preventDefault();+ stage.classList.add('drop');+ }));+ ['dragleave', 'drop'].forEach((t) => stage.addEventListener(t, () => stage.classList.remove('drop')));+ stage.addEventListener('drop', (e) => {+ if (!e.dataTransfer?.files?.length) return;+ e.preventDefault();+ addFiles(e.dataTransfer.files);+ });++ const importBar = h('div', 'md-import', '');+ importBar.hidden = true;+ stage.append(importBar);+ function updateImportBar() {+ const item = queue[cur];+ importBar.hidden = !item?.file;+ if (item?.file) importBar.innerHTML = `<span>Playing from your computer</span><button class="md-btn pri" data-a="import">Add to library</button>`;+ }+ async function importCurrent() {+ const item = queue[cur];+ if (!item?.file) return;+ try {+ const dir = item.kind === 'video' ? '/Videos' : '/Music';+ const path = await fs.importFile(item.file, dir);+ extras = extras.filter((e) => e !== item);+ ctx.toast(`Added to ${dir}`);+ await loadLibrary();+ cur = queue.findIndex((q) => q.path === path);+ renderList();+ syncUi();+ updateImportBar();+ root.focus();+ } catch (err) {+ ctx.toast(`Could not add to library: ${err.message}`);+ }+ }++ async function openPath(path) {+ if (typeof path !== 'string' || !path) return;+ const st = await fs.stat(path);+ if (!st || st.type !== 'file') {+ ctx.toast(`${path} was not found`);+ return;+ }+ const kind = mediaKind(st.name, st.mime);+ if (!kind) {+ ctx.toast(`${st.name} is not an audio or video file`);+ return;+ }+ if (!library.some((l) => l.path === st.path) && !extras.some((e) => e.path === st.path)) {+ extras.push({ id: st.path, path: st.path, name: st.name, kind, size: st.size });+ rebuildQueue();+ }+ await playIndex(queue.findIndex((q) => q.path === st.path));+ }++ /* ---------------- Media Session ---------------- */+ function setSession(item) {+ if (!('mediaSession' in navigator) || !item) return;+ try {+ navigator.mediaSession.metadata = new MediaMetadata({ title: titleFromName(item.name), artist: 'three.ws Media Player', album: item.file ? 'Your computer' : item.path.replace(/\/[^/]*$/, '') || '/' });+ } catch {+ /* metadata is optional */+ }+ }+ const sessionHandlers = {+ play: () => toggle(),+ pause: () => video.pause(),+ previoustrack: () => playPrev(),+ nexttrack: () => playNext(false),+ seekbackward: (d) => (video.currentTime = Math.max(0, video.currentTime - (d?.seekOffset || 10))),+ seekforward: (d) => (video.currentTime = Math.min(video.duration || 0, video.currentTime + (d?.seekOffset || 10))),+ seekto: (d) => (video.currentTime = d.seekTime),+ stop: () => {+ video.pause();+ video.currentTime = 0;+ },+ };+ if ('mediaSession' in navigator) {+ for (const [k, fn] of Object.entries(sessionHandlers)) {+ try {+ navigator.mediaSession.setActionHandler(k, fn);+ } catch {+ /* action not supported here */+ }+ }+ }++ /* ---------------- visualizer ---------------- */+ let raf = 0;+ function startVis() {+ if (raf || !analyser) return;+ raf = requestAnimationFrame(drawVis);+ }+ const bins = { f: null, t: null };+ function drawVis() {+ raf = 0;+ if (disposed) return;+ const item = queue[cur];+ if (!analyser || item?.kind !== 'audio' || (video.paused && !video.seeking && lastDrawIdle > 20)) return;+ raf = requestAnimationFrame(drawVis);+ if (document.visibilityState !== 'visible' || root.offsetParent === null) return;+ lastDrawIdle = video.paused ? lastDrawIdle + 1 : 0;+ const dpr = window.devicePixelRatio || 1;+ const w = vis.clientWidth;+ const hgt = vis.clientHeight;+ if (!w || !hgt) return;+ if (vis.width !== Math.round(w * dpr) || vis.height !== Math.round(hgt * dpr)) {+ vis.width = Math.round(w * dpr);+ vis.height = Math.round(hgt * dpr);+ }+ bins.f ||= new Uint8Array(analyser.frequencyBinCount);+ bins.t ||= new Uint8Array(analyser.fftSize);+ analyser.getByteFrequencyData(bins.f);+ analyser.getByteTimeDomainData(bins.t);+ const g = vis.getContext('2d');+ g.setTransform(dpr, 0, 0, dpr, 0, 0);+ g.clearRect(0, 0, w, hgt);+ const cs = getComputedStyle(root);+ const c1 = cs.getPropertyValue('--accent').trim() || '#4cc2ff';+ const c2 = cs.getPropertyValue('--accent-2').trim() || '#ad6eca';+ const n = Math.min(64, Math.floor(w / 10));+ const bw = w / n;+ const gr = g.createLinearGradient(0, hgt, 0, 0);+ gr.addColorStop(0, c1);+ gr.addColorStop(1, c2);+ g.fillStyle = gr;+ const usable = Math.floor(bins.f.length * 0.7);+ for (let i = 0; i < n; i++) {+ const lo = Math.floor(Math.pow(i / n, 1.8) * usable);+ const hi = Math.max(lo + 1, Math.floor(Math.pow((i + 1) / n, 1.8) * usable));+ let m = 0;+ for (let j = lo; j < hi; j++) m = Math.max(m, bins.f[j]);+ const bh = (m / 255) * hgt * 0.62;+ g.globalAlpha = 0.9;+ g.fillRect(i * bw + 1, hgt * 0.72 - bh, bw - 2, bh);+ }+ g.globalAlpha = 1;+ g.strokeStyle = c1;+ g.lineWidth = 2;+ g.beginPath();+ const wy = hgt * 0.86;+ for (let i = 0; i < bins.t.length; i += 4) {+ const x = (i / bins.t.length) * w;+ const y = wy + ((bins.t[i] - 128) / 128) * hgt * 0.1;+ i ? g.lineTo(x, y) : g.moveTo(x, y);+ }+ g.stroke();+ }+ let lastDrawIdle = 0;+ video.addEventListener('play', () => (lastDrawIdle = 0));++ /* ---------------- start ---------------- */+ const unsub = fs.subscribe((paths) => {+ if (paths.some((p) => p === '/Music' || p === '/Videos' || p === '/')) loadLibrary();+ });+ ctx.onArg((a) => openPath(a));+ document.addEventListener('fullscreenchange', syncUi);++ syncUi();+ renderList();+ requestAnimationFrame(() => root.focus({ preventScroll: true }));+ loadLibrary().then(() => {+ if (typeof ctx.arg === 'string' && ctx.arg) openPath(ctx.arg);+ });++ return () => {+ disposed = true;+ saveResume(true);+ unsub();+ document.removeEventListener('fullscreenchange', syncUi);+ cancelAnimationFrame(raf);+ video.pause();+ video.removeAttribute('src');+ video.load();+ if (objUrl) URL.revokeObjectURL(objUrl);+ objUrl = null;+ audioCtx?.close?.().catch(() => {});+ if ('mediaSession' in navigator) {+ for (const k of Object.keys(sessionHandlers)) {+ try {+ navigator.mediaSession.setActionHandler(k, null);+ } catch {+ /* unsupported action */+ }+ }+ navigator.mediaSession.metadata = null;+ }+ };+}diff --git a/src/desktop/os/apps/notepad.css b/src/desktop/os/apps/notepad.cssnew file mode 100644index 000000000..6bbdbc1f9--- /dev/null+++ b/src/desktop/os/apps/notepad.css@@ -0,0 +1,387 @@+.napp-notepad {+ height: 100%;+ min-height: 0;+}+.napp-notepad .np {+ position: relative;+ display: flex;+ flex-direction: column;+ height: 100%;+ min-height: 0;+ background: var(--card);+ color: var(--text);+ font-size: 13px;+ overflow: hidden;+ container-type: inline-size;+}+.napp-notepad .np button {+ font: inherit;+ color: inherit;+}+.napp-notepad .np button:disabled {+ opacity: 0.4;+ cursor: default;+}+.napp-notepad .np-bar {+ display: flex;+ align-items: center;+ gap: 2px;+ padding: 6px 8px;+ border-bottom: 1px solid var(--bd);+ overflow-x: auto;+ scrollbar-width: none;+}+.napp-notepad .np-b {+ display: flex;+ align-items: center;+ gap: 6px;+ height: 28px;+ padding: 0 9px;+ border-radius: var(--siz-radius3, 6px);+ white-space: nowrap;+}+.napp-notepad .np-b.ic {+ width: 28px;+ padding: 0;+ justify-content: center;+}+.napp-notepad .np-b:not(:disabled):hover {+ background: var(--hover);+}+.napp-notepad .np-b:not(:disabled):active {+ background: var(--hover-b, var(--hover));+}+.napp-notepad .np-b[aria-pressed='true'] {+ background: color-mix(in srgb, var(--accent) 26%, transparent);+}+@container (max-width: 640px) {+ .napp-notepad .np-bar .np-b:not(.ic) span {+ display: none;+ }+ .napp-notepad .np-bar [data-act='saveas'] span,+ .napp-notepad .np-bar [data-act='goto'] span {+ display: inline;+ }+}+.napp-notepad .np-sep {+ width: 1px;+ height: 16px;+ margin: 0 4px;+ background: var(--bd);+}+.napp-notepad .np-grow {+ flex: 1;+}++.napp-notepad .np-tabs {+ display: flex;+ align-items: flex-end;+ gap: 2px;+ padding: 4px 8px 0;+ overflow-x: auto;+ scrollbar-width: thin;+ border-bottom: 1px solid var(--bd);+}+.napp-notepad .np-tab {+ display: flex;+ align-items: center;+ gap: 6px;+ flex: 0 1 180px;+ min-width: 96px;+ height: 30px;+ padding: 0 6px 0 12px;+ border-radius: 7px 7px 0 0;+ border: 1px solid transparent;+ border-bottom: 0;+ color: var(--text2);+ cursor: default;+ user-select: none;+}+.napp-notepad .np-tab:hover {+ background: var(--hover);+}+.napp-notepad .np-tab.on {+ background: var(--bg);+ border-color: var(--bd);+ color: var(--text);+ margin-bottom: -1px;+ height: 31px;+}+.napp-notepad .np-tn {+ flex: 1;+ min-width: 0;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}+.napp-notepad .np-dot {+ width: 7px;+ height: 7px;+ border-radius: 50%;+ background: var(--accent);+ flex: none;+}+.napp-notepad .np-dot[hidden] {+ display: none;+}+.napp-notepad .np-x,+.napp-notepad .np-add {+ display: grid;+ place-items: center;+ flex: none;+ width: 22px;+ height: 22px;+ border-radius: 5px;+ opacity: 0.7;+}+.napp-notepad .np-add {+ margin: 0 0 4px 2px;+ width: 26px;+ height: 26px;+}+.napp-notepad .np-x:hover,+.napp-notepad .np-add:hover {+ background: var(--hover-b, var(--hover));+ opacity: 1;+}++.napp-notepad .np-find {+ display: flex;+ flex-direction: column;+ gap: 6px;+ padding: 8px;+ border-bottom: 1px solid var(--bd);+ background: var(--hover-half, transparent);+}+.napp-notepad .np-find[hidden] {+ display: none;+}+.napp-notepad .np-rep {+ display: none;+}+.napp-notepad .np-find.with-rep .np-rep {+ display: flex;+}+.napp-notepad .np-row {+ display: flex;+ align-items: center;+ gap: 4px;+}+.napp-notepad .np-fi,+.napp-notepad .np-ri,+.napp-notepad .np-in {+ flex: 1;+ min-width: 0;+ height: 28px;+ padding: 0 8px;+ border: 1px solid var(--bd);+ border-radius: 6px;+ background: var(--bg);+ color: var(--text);+ font: inherit;+ outline: 0;+}+.napp-notepad .np-fi:focus,+.napp-notepad .np-ri:focus,+.napp-notepad .np-in:focus {+ border-color: var(--accent);+}+.napp-notepad .np-count {+ min-width: 72px;+ text-align: right;+ font-size: 12px;+ color: var(--text2);+}+.napp-notepad .np-count.none {+ color: #e5484d;+}+.napp-notepad .np-b.case {+ width: 30px;+ padding: 0;+ justify-content: center;+ font-weight: 600;+}++.napp-notepad .np-edit {+ position: relative;+ flex: 1;+ min-height: 0;+ background: var(--bg);+}+.napp-notepad .np-ta {+ position: absolute;+ inset: 0;+ width: 100%;+ height: 100%;+ box-sizing: border-box;+ padding: 10px 14px;+ border: 0;+ outline: 0;+ resize: none;+ background: transparent;+ color: var(--text);+ font-family: ui-monospace, 'Cascadia Code', Consolas, 'SF Mono', Menlo, monospace;+ line-height: 1.5;+ tab-size: 4;+ caret-color: var(--accent);+}+.napp-notepad .np-ta[hidden] {+ display: none;+}+.napp-notepad .np-ta.nowrap {+ white-space: pre;+ overflow-wrap: normal;+}+.napp-notepad .np-ta::selection {+ background: color-mix(in srgb, var(--accent) 45%, transparent);+}++.napp-notepad .np-status {+ display: flex;+ align-items: center;+ gap: 18px;+ height: 26px;+ padding: 0 14px;+ border-top: 1px solid var(--bd);+ font-size: 12px;+ color: var(--text2);+ white-space: nowrap;+}++/* dialogs */+.napp-notepad .np-modal {+ position: absolute;+ inset: 0;+ z-index: 30;+ display: grid;+ place-items: center;+ background: var(--bg50, rgba(0, 0, 0, 0.4));+}+.napp-notepad .np-dlg {+ width: min(400px, 92%);+ box-sizing: border-box;+ padding: 18px;+ border: 1px solid var(--bd);+ border-radius: 10px;+ background: var(--card);+ box-shadow: var(--shadow-lg, 0 16px 64px rgba(0, 0, 0, 0.5));+}+.napp-notepad .np-dlg h3 {+ margin: 0 0 8px;+ font-size: 15px;+}+.napp-notepad .np-dlg p {+ margin: 0 0 14px;+ color: var(--text2);+}+.napp-notepad .np-dlg .np-in {+ width: 100%;+ margin-bottom: 12px;+ height: 32px;+}+.napp-notepad .np-dlg-act {+ display: flex;+ justify-content: flex-end;+ gap: 8px;+}+.napp-notepad .np-pill {+ height: 30px;+ padding: 0 14px;+ border: 1px solid var(--bd);+ border-radius: var(--siz-radius3, 6px);+ background: var(--hover);+}+.napp-notepad .np-pill:not(:disabled):hover {+ background: var(--hover-b, var(--hover));+}+.napp-notepad .np-pill.primary {+ background: var(--accent);+ border-color: transparent;+ color: #fff;+}+.napp-notepad .np-pill.danger {+ background: #d13438;+ border-color: transparent;+ color: #fff;+}+.napp-notepad .np-fd {+ width: min(520px, 94%);+}+.napp-notepad .np-fd-bar {+ display: flex;+ align-items: center;+ gap: 6px;+ margin-bottom: 8px;+}+.napp-notepad .np-fd-path {+ flex: 1;+ min-width: 0;+ display: flex;+ align-items: center;+ gap: 2px;+ height: 28px;+ padding: 0 6px;+ border: 1px solid var(--bd);+ border-radius: 6px;+ overflow-x: auto;+ scrollbar-width: none;+ white-space: nowrap;+ color: var(--text2);+}+.napp-notepad .np-fd-path button {+ padding: 2px 5px;+ border-radius: 4px;+ color: var(--text);+}+.napp-notepad .np-fd-path button:hover {+ background: var(--hover);+}+.napp-notepad .np-fd-list {+ height: 230px;+ margin-bottom: 10px;+ padding: 4px;+ overflow-y: auto;+ border: 1px solid var(--bd);+ border-radius: 6px;+ background: var(--bg);+ outline: 0;+}+.napp-notepad .np-fd-list:focus-visible {+ border-color: var(--accent);+}+.napp-notepad .np-fd-row {+ display: flex;+ align-items: center;+ gap: 10px;+ height: 30px;+ padding: 0 8px;+ border-radius: 5px;+ cursor: default;+ outline: 0;+}+.napp-notepad .np-fd-row span {+ flex: 1;+ min-width: 0;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}+.napp-notepad .np-fd-row svg {+ flex: none;+ color: var(--text2);+}+.napp-notepad .np-fd-row[data-type='dir'] svg {+ color: #f0b429;+}+.napp-notepad .np-fd-row:hover {+ background: var(--hover);+}+.napp-notepad .np-fd-row.sel,+.napp-notepad .np-fd-row:focus-visible {+ background: color-mix(in srgb, var(--accent) 26%, transparent);+}+.napp-notepad .np-fd-empty {+ padding: 40px 16px;+ text-align: center;+ color: var(--text2);+}diff --git a/src/desktop/os/apps/notepad.js b/src/desktop/os/apps/notepad.jsnew file mode 100644index 000000000..28ce77a16--- /dev/null+++ b/src/desktop/os/apps/notepad.js@@ -0,0 +1,794 @@+// Notepad: tabbed plain-text editor backed by the virtual file system (../fs.js).+import './notepad.css';+import * as fs from '../fs.js';++/* ---------- pure helpers (unit tested) ---------- */++/** Start offsets of every match of `query` in `text`. */+export function findMatches(text, query, caseSensitive = false) {+ if (!query) return [];+ const hay = caseSensitive ? text : text.toLowerCase();+ const needle = caseSensitive ? query : query.toLowerCase();+ const out = [];+ for (let i = hay.indexOf(needle); i !== -1; i = hay.indexOf(needle, i + needle.length)) out.push(i);+ return out;+}++/** Replace every match. Returns { text, count }. */+export function replaceAll(text, query, replacement, caseSensitive = false) {+ const hits = findMatches(text, query, caseSensitive);+ if (!hits.length) return { text, count: 0 };+ let out = '';+ let last = 0;+ for (const i of hits) {+ out += text.slice(last, i) + replacement;+ last = i + query.length;+ }+ return { text: out + text.slice(last), count: hits.length };+}++/** Index in `matches` of the first match at or after `pos`, wrapping to 0. -1 when there are none. */+export function nextMatchIndex(matches, pos, backwards = false) {+ if (!matches.length) return -1;+ if (backwards) {+ for (let i = matches.length - 1; i >= 0; i--) if (matches[i] < pos) return i;+ return matches.length - 1;+ }+ const i = matches.findIndex((m) => m >= pos);+ return i < 0 ? 0 : i;+}++/** 1-based line and column of a caret offset. */+export function lineCol(text, pos) {+ const head = text.slice(0, Math.max(0, pos));+ const line = head.split('\n').length;+ return { line, col: pos - (head.lastIndexOf('\n') + 1) + 1 };+}++/** Offset of the start of 1-based `line`, clamped to the last line. */+export function offsetOfLine(text, line) {+ let off = 0;+ for (let n = 1; n < line; n++) {+ const i = text.indexOf('\n', off);+ if (i < 0) return off;+ off = i + 1;+ }+ return off;+}++export const countLines = (text) => text.split('\n').length;++export const MIN_SIZE = 8;+export const MAX_SIZE = 48;+export const DEFAULT_SIZE = 14;+export const clampSize = (n) => Math.max(MIN_SIZE, Math.min(MAX_SIZE, Math.round(n)));+export const zoomPercent = (size) => Math.round((size / DEFAULT_SIZE) * 100);++/** Window title for a document. */+export const titleFor = (name, dirty) => `${dirty ? '*' : ''}${name} - Notepad`;++/** A usable file name from what the user typed: trims, adds .txt when there is no extension. */+export function fileNameFrom(input) {+ const n = String(input || '').trim();+ if (!n) return '';+ return fs.extOf(n) ? n : `${n}.txt`;+}++/** Validate drafts read back from storage. Anything malformed is dropped. */+export function parseDrafts(raw) {+ try {+ const list = JSON.parse(raw || '[]');+ if (!Array.isArray(list)) return [];+ return list+ .filter((d) => d && typeof d.id === 'string' && typeof d.text === 'string' && typeof d.name === 'string')+ .map((d) => ({ id: d.id, name: d.name, text: d.text, path: typeof d.path === 'string' ? d.path : null }));+ } catch {+ return [];+ }+}++/* ---------- the app ---------- */++const GLYPHS = {+ 'np-new': '<path d="M6 3h8l5 5v13H6z"/><path d="M14 3v5h5M12 12v6M9 15h6"/>',+ 'np-open': '<path d="M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v1H7l-4 8z"/><path d="M3 18l4-8h16l-3 8z"/>',+ 'np-save': '<path d="M5 3h11l4 4v14H5z"/><path d="M8 3v5h7V3M8 21v-7h8v7"/>',+ 'np-find': '<circle cx="10.5" cy="10.5" r="6"/><path d="m15 15 6 6"/>',+ 'np-wrap': '<path d="M4 6h16M4 12h13a3 3 0 0 1 0 6h-4M4 18h5"/><path d="m13 15-3 3 3 3"/>',+ 'np-plus': '<circle cx="11" cy="11" r="7"/><path d="m16 16 5 5M11 8v6M8 11h6"/>',+ 'np-minus': '<circle cx="11" cy="11" r="7"/><path d="m16 16 5 5M8 11h6"/>',+ 'np-up': '<path d="M12 19V5M6 11l6-6 6 6"/>',+ 'np-down': '<path d="M12 5v14M6 13l6 6 6-6"/>',+ 'np-x': '<path d="M6 6l12 12M18 6 6 18"/>',+};++const DRAFTS_KEY = 'notepad:drafts';+const PREFS_KEY = 'notepad:prefs';+let uid = 0;++export function mount(host, ctx) {+ for (const [k, v] of Object.entries(GLYPHS)) ctx.registerGlyph(k, v);+ const { h, esc, icon } = ctx;++ let prefs = { wrap: true, size: DEFAULT_SIZE };+ try {+ prefs = { ...prefs, ...JSON.parse(ctx.store.get(PREFS_KEY) || '{}') };+ prefs.size = clampSize(prefs.size);+ } catch {+ /* defaults */+ }+ const savePrefs = () => ctx.store.set(PREFS_KEY, JSON.stringify(prefs));++ const root = h('div', 'np');+ root.innerHTML = `+ <div class="np-bar" role="toolbar" aria-label="Notepad commands">+ <button class="np-b" data-act="new" title="New tab (Ctrl+N)">${icon('np-new', 16)}<span>New</span></button>+ <button class="np-b" data-act="open" title="Open from your files (Ctrl+O)">${icon('np-open', 16)}<span>Open</span></button>+ <button class="np-b" data-act="computer" title="Open a file from this computer">${icon('upload', 16)}<span>From computer</span></button>+ <button class="np-b" data-act="save" title="Save (Ctrl+S)">${icon('np-save', 16)}<span>Save</span></button>+ <button class="np-b" data-act="saveas" title="Save as (Ctrl+Shift+S)"><span>Save as</span></button>+ <i class="np-sep"></i>+ <button class="np-b" data-act="find" title="Find and replace (Ctrl+F, Ctrl+H)">${icon('np-find', 16)}<span>Find</span></button>+ <button class="np-b" data-act="goto" title="Go to line (Ctrl+G)"><span>Go to line</span></button>+ <span class="np-grow"></span>+ <button class="np-b" data-act="wrap" aria-pressed="false" title="Word wrap">${icon('np-wrap', 16)}<span>Wrap</span></button>+ <button class="np-b ic" data-act="zout" title="Zoom out (Ctrl+-)" aria-label="Zoom out">${icon('np-minus', 16)}</button>+ <button class="np-b ic" data-act="zin" title="Zoom in (Ctrl++)" aria-label="Zoom in">${icon('np-plus', 16)}</button>+ </div>+ <div class="np-tabs" role="tablist" aria-label="Open documents"></div>+ <div class="np-find" hidden>+ <div class="np-row">+ <input class="np-fi" placeholder="Find" aria-label="Find" spellcheck="false" />+ <span class="np-count" aria-live="polite"></span>+ <button class="np-b ic" data-act="prev" title="Previous (Shift+F3)" aria-label="Previous match">${icon('np-up', 14)}</button>+ <button class="np-b ic" data-act="next" title="Next (F3)" aria-label="Next match">${icon('np-down', 14)}</button>+ <button class="np-b case" data-act="case" aria-pressed="false" title="Match case">Aa</button>+ <button class="np-b ic" data-act="closefind" title="Close (Esc)" aria-label="Close find">${icon('np-x', 14)}</button>+ </div>+ <div class="np-row np-rep">+ <input class="np-ri" placeholder="Replace with" aria-label="Replace with" spellcheck="false" />+ <button class="np-b" data-act="replace">Replace</button>+ <button class="np-b" data-act="replaceall">Replace all</button>+ </div>+ </div>+ <div class="np-edit"></div>+ <div class="np-status" role="status">+ <span data-s="pos"></span><span data-s="chars"></span><span class="np-grow"></span><span data-s="zoom"></span><span>UTF-8</span>+ </div>+ <input type="file" hidden accept="text/*,.txt,.md,.json,.js,.css,.html,.csv,.xml,.log" multiple />`;+ host.append(root);+ const q = (s) => root.querySelector(s);+ const tabsEl = q('.np-tabs');+ const editEl = q('.np-edit');+ const findBar = q('.np-find');+ const findIn = q('.np-fi');+ const repIn = q('.np-ri');+ const countEl = q('.np-count');+ const fileInput = q('input[type=file]');+ let caseSens = false;+ let dead = false;++ /** @type {{id:string,path:string|null,name:string,saved:string,ta:HTMLTextAreaElement}[]} */+ const docs = [];+ let cur = null;++ const isDirty = (d) => d.ta.value !== d.saved;+ const err = (e) => ctx.toast(e?.message || 'Something went wrong');++ /* --- drafts --- */+ function flushDrafts() {+ const list = docs.filter(isDirty).map((d) => ({ id: d.id, path: d.path, name: d.name, text: d.ta.value }));+ if (list.length) ctx.store.set(DRAFTS_KEY, JSON.stringify(list));+ else ctx.store.del(DRAFTS_KEY);+ }+ let draftTimer = 0;+ const scheduleDrafts = () => {+ clearTimeout(draftTimer);+ draftTimer = setTimeout(flushDrafts, 350);+ };+ const onHide = () => flushDrafts();+ window.addEventListener('pagehide', onHide);++ /* --- documents --- */+ function addDoc({ path = null, name = 'Untitled.txt', text = '', saved = text, activate = true } = {}) {+ const ta = h('textarea', 'np-ta');+ ta.value = text;+ ta.spellcheck = false;+ ta.setAttribute('aria-label', name);+ ta.hidden = true;+ const d = { id: `d${Date.now().toString(36)}${uid++}`, path, name, saved, ta };+ applyView(ta);+ ta.addEventListener('input', () => {+ updateTab(d);+ updateStatus();+ scheduleDrafts();+ if (!findBar.hidden) updateCount();+ });+ for (const ev of ['keyup', 'click', 'select', 'focus']) ta.addEventListener(ev, updateStatus);+ ta.addEventListener('keydown', (e) => {+ if (e.key === 'Tab' && !e.ctrlKey && !e.altKey && !e.metaKey) {+ e.preventDefault();+ if (!document.execCommand('insertText', false, '\t')) {+ ta.setRangeText('\t', ta.selectionStart, ta.selectionEnd, 'end');+ ta.dispatchEvent(new Event('input'));+ }+ }+ });+ ta.addEventListener('wheel', (e) => {+ if (!e.ctrlKey) return;+ e.preventDefault();+ setSize(prefs.size + (e.deltaY < 0 ? 1 : -1));+ }, { passive: false });+ editEl.append(ta);+ docs.push(d);+ if (activate) activateDoc(d);+ else renderTabs();+ return d;+ }++ function applyView(ta) {+ ta.style.fontSize = `${prefs.size}px`;+ ta.wrap = prefs.wrap ? 'soft' : 'off';+ ta.classList.toggle('nowrap', !prefs.wrap);+ }+ function applyViewAll() {+ docs.forEach((d) => applyView(d.ta));+ q('[data-act="wrap"]').setAttribute('aria-pressed', prefs.wrap);+ updateStatus();+ }+ function setSize(n) {+ prefs.size = clampSize(n);+ savePrefs();+ applyViewAll();+ }++ function activateDoc(d) {+ cur = d;+ for (const x of docs) x.ta.hidden = x !== d;+ renderTabs();+ updateStatus();+ updateTitle();+ d.ta.focus();+ if (!findBar.hidden) updateCount();+ }++ function renderTabs() {+ tabsEl.innerHTML = '';+ for (const d of docs) {+ const dirty = isDirty(d);+ const t = h('div', `np-tab${d === cur ? ' on' : ''}`);+ t.dataset.id = d.id;+ t.setAttribute('role', 'tab');+ t.setAttribute('aria-selected', d === cur);+ t.tabIndex = d === cur ? 0 : -1;+ t.title = d.path || d.name;+ t.innerHTML = `<span class="np-tn">${esc(d.name)}</span><span class="np-dot" ${dirty ? '' : 'hidden'} title="Unsaved changes"></span><button class="np-x" aria-label="Close ${esc(d.name)}" tabindex="-1">${icon('np-x', 12)}</button>`;+ tabsEl.append(t);+ }+ const add = h('button', 'np-add');+ add.dataset.act = 'new';+ add.setAttribute('aria-label', 'New tab');+ add.title = 'New tab';+ add.innerHTML = icon('plus', 14);+ tabsEl.append(add);+ }+ function updateTab(d) {+ const t = tabsEl.querySelector(`[data-id="${d.id}"]`);+ if (!t) return;+ t.querySelector('.np-tn').textContent = d.name;+ t.querySelector('.np-dot').hidden = !isDirty(d);+ t.title = d.path || d.name;+ if (d === cur) updateTitle();+ }+ function updateTitle() {+ if (cur) ctx.setTitle(titleFor(cur.name, isDirty(cur)));+ }+ function updateStatus() {+ if (!cur) return;+ const ta = cur.ta;+ const { line, col } = lineCol(ta.value, ta.selectionStart);+ const sel = ta.selectionEnd - ta.selectionStart;+ q('[data-s="pos"]').textContent = `Ln ${line}, Col ${col}${sel ? ` (${sel} selected)` : ''}`;+ q('[data-s="chars"]').textContent = `${ta.value.length.toLocaleString()} ${ta.value.length === 1 ? 'character' : 'characters'}`;+ q('[data-s="zoom"]').textContent = `${zoomPercent(prefs.size)}%`;+ }++ /* --- open / save --- */+ const openCommon = async (path) => {+ const existing = docs.find((d) => d.path === path);+ if (existing) return activateDoc(existing);+ const node = await fs.stat(path);+ if (!node || node.type !== 'file') throw new Error(`"${path}" could not be opened.`);+ const text = await fs.readText(path);+ const only = docs.length === 1 && !docs[0].path && !isDirty(docs[0]) && !docs[0].ta.value;+ const d = addDoc({ path, name: node.name, text: text ?? '' });+ if (only) closeDoc(docs[0], true);+ return d;+ };+ async function openPath(path) {+ try {+ await openCommon(path);+ } catch (e) {+ err(e);+ }+ }++ async function saveDoc(d, as = false) {+ let path = d.path;+ if (!path || as) {+ const chosen = await fileDialog({ mode: 'save', name: d.name, dir: d.path ? fs.parentOf(d.path) : '/Documents' });+ if (!chosen) return false;+ path = chosen;+ }+ try {+ const text = d.ta.value;+ const node = await fs.write(path, text, { mime: fs.mimeOf(path) === 'application/octet-stream' ? 'text/plain' : fs.mimeOf(path) });+ d.path = path;+ d.name = node.name;+ d.saved = text;+ d.ta.setAttribute('aria-label', d.name);+ updateTab(d);+ updateTitle();+ flushDrafts();+ ctx.toast(`Saved ${d.name}`);+ return true;+ } catch (e) {+ err(e);+ return false;+ }+ }++ async function closeDoc(d, force = false) {+ if (!force && isDirty(d)) {+ activateDoc(d);+ const r = await choose({+ title: `Save changes to ${d.name}?`,+ message: 'Your changes will be lost if you do not save them.',+ buttons: [+ ['save', 'Save', 'primary'],+ ['discard', "Don't save", 'danger'],+ ['cancel', 'Cancel', ''],+ ],+ });+ if (r === 'cancel' || r == null) return false;+ if (r === 'save' && !(await saveDoc(d))) return false;+ }+ const i = docs.indexOf(d);+ docs.splice(i, 1);+ d.ta.remove();+ if (!docs.length) addDoc();+ else if (cur === d) activateDoc(docs[Math.min(i, docs.length - 1)]);+ else renderTabs();+ flushDrafts();+ return true;+ }++ /* --- dialogs --- */+ function choose({ title, message = '', buttons }) {+ return new Promise((resolve) => {+ const wrap = h('div', 'np-modal');+ wrap.innerHTML = `<div class="np-dlg" role="dialog" aria-modal="true" aria-label="${esc(title)}"><h3>${esc(title)}</h3>${message ? `<p>${esc(message)}</p>` : ''}<div class="np-dlg-act">${buttons.map(([id, label, cls]) => `<button class="np-pill ${cls}" data-id="${id}">${esc(label)}</button>`).join('')}</div></div>`;+ root.append(wrap);+ const done = (v) => {+ wrap.remove();+ cur?.ta.focus();+ resolve(v);+ };+ wrap.addEventListener('click', (e) => {+ const b = e.target.closest('[data-id]');+ if (b) done(b.dataset.id);+ else if (e.target === wrap) done(null);+ });+ wrap.addEventListener('keydown', (e) => {+ e.stopPropagation();+ if (e.key === 'Escape') done(null);+ });+ wrap.querySelector('.primary, .danger, button').focus();+ });+ }++ function promptLine() {+ return new Promise((resolve) => {+ const wrap = h('div', 'np-modal');+ const lines = countLines(cur.ta.value);+ wrap.innerHTML = `<form class="np-dlg" role="dialog" aria-modal="true" aria-label="Go to line"><h3>Go to line</h3><input class="np-in" type="number" min="1" max="${lines}" placeholder="Line number (1 to ${lines})" aria-label="Line number" /><div class="np-dlg-act"><button type="button" class="np-pill" data-x>Cancel</button><button class="np-pill primary">Go</button></div></form>`;+ root.append(wrap);+ const inp = wrap.querySelector('input');+ inp.focus();+ const done = (v) => {+ wrap.remove();+ cur.ta.focus();+ resolve(v);+ };+ wrap.addEventListener('submit', (e) => {+ e.preventDefault();+ const n = parseInt(inp.value, 10);+ done(Number.isFinite(n) ? n : null);+ });+ wrap.querySelector('[data-x]').addEventListener('click', () => done(null));+ wrap.addEventListener('keydown', (e) => {+ e.stopPropagation();+ if (e.key === 'Escape') done(null);+ });+ });+ }++ /** In-app open/save dialog over the virtual file system. Resolves to a path or null. */+ function fileDialog({ mode, name = 'Untitled.txt', dir = '/Documents' }) {+ return new Promise((resolve) => {+ let loc = dir;+ const wrap = h('div', 'np-modal');+ wrap.innerHTML = `<div class="np-dlg np-fd" role="dialog" aria-modal="true" aria-label="${mode === 'save' ? 'Save as' : 'Open'}">+ <h3>${mode === 'save' ? 'Save as' : 'Open a file'}</h3>+ <div class="np-fd-bar"><button class="np-b ic" data-up aria-label="Up one level" title="Up">${icon('np-up', 14)}</button><div class="np-fd-path"></div><button class="np-b" data-newdir title="New folder">${icon('plus', 14)}<span>Folder</span></button></div>+ <div class="np-fd-list" role="listbox" tabindex="0"></div>+ ${mode === 'save' ? '<input class="np-in" aria-label="File name" spellcheck="false" />' : ''}+ <div class="np-dlg-act"><button class="np-pill" data-x>Cancel</button><button class="np-pill primary" data-ok>${mode === 'save' ? 'Save' : 'Open'}</button></div></div>`;+ root.append(wrap);+ const list = wrap.querySelector('.np-fd-list');+ const pathEl = wrap.querySelector('.np-fd-path');+ const nameIn = wrap.querySelector('input');+ const okBtn = wrap.querySelector('[data-ok]');+ let picked = null;+ const done = (v) => {+ wrap.remove();+ cur?.ta.focus();+ resolve(v);+ };+ const crumbs = () => {+ let acc = '';+ const segs = loc === '/' ? [] : loc.split('/').filter(Boolean);+ pathEl.innerHTML = `<button data-go="/">This PC</button>${segs.map((s) => `<span>/</span><button data-go="${esc((acc += `/${s}`))}">${esc(s)}</button>`).join('')}`;+ };+ const show = async (to) => {+ try {+ const nodes = to === '/' ? (await fs.list('/')).filter((n) => n.path !== fs.TRASH) : await fs.list(to);+ loc = to;+ picked = null;+ crumbs();+ const rows = nodes.filter((n) => n.type === 'dir' || mode === 'save' || fs.kindOf(n.name) === 'text' || fs.kindOf(n.name) === 'other');+ list.innerHTML = rows.length+ ? rows.map((n) => `<div class="np-fd-row" role="option" tabindex="-1" data-path="${esc(n.path)}" data-type="${n.type}">${icon(n.type === 'dir' ? 'folder' : 'note', 16)}<span>${esc(n.name)}</span></div>`).join('')+ : `<div class="np-fd-empty">${loc === '/' ? 'No folders.' : 'This folder is empty.'}${mode === 'save' ? ' Type a name below to save here.' : ''}</div>`;+ updateOk();+ } catch (e) {+ err(e);+ }+ };+ const updateOk = () => {+ okBtn.disabled = mode === 'save' ? !fileNameFrom(nameIn.value) || loc === '/' : !picked;+ };+ const confirm = async () => {+ if (mode === 'open') return picked && done(picked);+ const n = fileNameFrom(nameIn.value);+ if (!n || loc === '/') return;+ const p = fs.join(loc, n);+ const ex = await fs.stat(p);+ if (ex?.type === 'dir') return err(new Error('A folder with that name already exists.'));+ if (ex) {+ const r = await choose({ title: 'Replace file?', message: `${n} already exists in this folder. Do you want to replace it?`, buttons: [['yes', 'Replace', 'danger'], ['no', 'Cancel', '']] });+ if (r !== 'yes') return;+ }+ done(p);+ };+ wrap.addEventListener('click', async (e) => {+ const go = e.target.closest('[data-go]');+ if (go) return show(go.dataset.go);+ if (e.target.closest('[data-up]')) return loc !== '/' && show(fs.parentOf(loc));+ if (e.target.closest('[data-x]') || e.target === wrap) return done(null);+ if (e.target.closest('[data-ok]')) return confirm();+ if (e.target.closest('[data-newdir]')) {+ if (loc === '/') return;+ try {+ const nm = await fs.uniqueName(loc, 'New folder');+ await fs.mkdir(fs.join(loc, nm));+ await show(loc);+ } catch (x) {+ err(x);+ }+ return;+ }+ const row = e.target.closest('.np-fd-row');+ if (!row) return;+ list.querySelectorAll('.sel').forEach((r) => r.classList.remove('sel'));+ row.classList.add('sel');+ if (row.dataset.type === 'dir') {+ picked = null;+ } else {+ picked = row.dataset.path;+ if (nameIn) nameIn.value = fs.nameOf(picked);+ }+ updateOk();+ });+ wrap.addEventListener('dblclick', (e) => {+ const row = e.target.closest('.np-fd-row');+ if (!row) return;+ if (row.dataset.type === 'dir') show(row.dataset.path);+ else {+ picked = row.dataset.path;+ confirm();+ }+ });+ wrap.addEventListener('keydown', (e) => {+ e.stopPropagation();+ if (e.key === 'Escape') return done(null);+ if (e.key === 'Enter' && e.target !== wrap.querySelector('[data-x]')) {+ e.preventDefault();+ const focused = document.activeElement?.closest?.('.np-fd-row');+ if (focused?.dataset.type === 'dir') return show(focused.dataset.path);+ if (focused && mode === 'open') picked = focused.dataset.path;+ confirm();+ }+ if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {+ const rows = [...list.querySelectorAll('.np-fd-row')];+ if (!rows.length) return;+ e.preventDefault();+ const i = rows.indexOf(document.activeElement);+ const next = rows[Math.max(0, Math.min(rows.length - 1, i + (e.key === 'ArrowDown' ? 1 : -1)))];+ next.focus();+ next.click();+ }+ });+ if (nameIn) {+ nameIn.value = name;+ nameIn.addEventListener('input', updateOk);+ }+ show(loc).then(() => {+ if (nameIn) {+ nameIn.focus();+ const dot = name.lastIndexOf('.');+ nameIn.setSelectionRange(0, dot > 0 ? dot : name.length);+ } else list.focus();+ });+ });+ }++ /* --- find / replace --- */+ function matches() {+ return cur ? findMatches(cur.ta.value, findIn.value, caseSens) : [];+ }+ function updateCount() {+ const m = matches();+ if (!findIn.value) countEl.textContent = '';+ else if (!m.length) countEl.textContent = 'No results';+ else {+ const pos = cur.ta.selectionStart;+ const i = m.findIndex((x) => x === pos && cur.ta.selectionEnd - pos === findIn.value.length);+ countEl.textContent = i >= 0 ? `${i + 1} of ${m.length}` : `${m.length} ${m.length === 1 ? 'match' : 'matches'}`;+ }+ countEl.classList.toggle('none', !!findIn.value && !m.length);+ }+ function selectMatch(backwards = false) {+ const m = matches();+ if (!m.length) return updateCount();+ const ta = cur.ta;+ const pos = backwards ? ta.selectionStart : ta.selectionEnd > ta.selectionStart ? ta.selectionStart + 1 : ta.selectionStart;+ const at = m[nextMatchIndex(m, pos, backwards)];+ ta.focus();+ ta.setSelectionRange(at, at + findIn.value.length);+ updateStatus();+ updateCount();+ }+ function openFind(replace = false) {+ findBar.hidden = false;+ findBar.classList.toggle('with-rep', replace);+ const sel = cur.ta.value.slice(cur.ta.selectionStart, cur.ta.selectionEnd);+ if (sel && !sel.includes('\n')) findIn.value = sel;+ (replace && findIn.value ? repIn : findIn).focus();+ findIn.select?.();+ updateCount();+ }+ function closeFind() {+ findBar.hidden = true;+ cur?.ta.focus();+ }+ function replaceCurrent() {+ const ta = cur.ta;+ const sel = ta.value.slice(ta.selectionStart, ta.selectionEnd);+ const hit = caseSens ? sel === findIn.value : sel.toLowerCase() === findIn.value.toLowerCase();+ if (hit && findIn.value) {+ ta.focus();+ if (!document.execCommand('insertText', false, repIn.value)) {+ ta.setRangeText(repIn.value, ta.selectionStart, ta.selectionEnd, 'end');+ ta.dispatchEvent(new Event('input'));+ }+ }+ selectMatch();+ }+ function replaceEverything() {+ if (!findIn.value) return;+ const ta = cur.ta;+ const r = replaceAll(ta.value, findIn.value, repIn.value, caseSens);+ if (!r.count) return updateCount();+ ta.focus();+ ta.select();+ if (!document.execCommand('insertText', false, r.text)) {+ ta.value = r.text;+ ta.dispatchEvent(new Event('input'));+ }+ ctx.toast(`Replaced ${r.count} ${r.count === 1 ? 'match' : 'matches'}`);+ findIn.focus();+ updateCount();+ }+ findIn.addEventListener('input', () => {+ if (findIn.value) {+ const ta = cur.ta;+ const m = matches();+ if (m.length) {+ const at = m[nextMatchIndex(m, ta.selectionStart)];+ ta.focus();+ ta.setSelectionRange(at, at + findIn.value.length);+ findIn.focus({ preventScroll: true });+ }+ }+ updateCount();+ });+ findIn.addEventListener('keydown', (e) => {+ if (e.key === 'Enter') {+ e.preventDefault();+ selectMatch(e.shiftKey);+ }+ });+ repIn.addEventListener('keydown', (e) => {+ if (e.key === 'Enter') {+ e.preventDefault();+ replaceCurrent();+ }+ });+ findBar.addEventListener('keydown', (e) => {+ if (e.key === 'Escape') {+ e.stopPropagation();+ closeFind();+ }+ });++ async function gotoLine() {+ const n = await promptLine();+ if (n == null) return;+ const ta = cur.ta;+ const off = offsetOfLine(ta.value, n);+ ta.focus();+ ta.setSelectionRange(off, off);+ const lh = parseFloat(getComputedStyle(ta).lineHeight) || prefs.size * 1.5;+ ta.scrollTop = Math.max(0, (Math.min(n, countLines(ta.value)) - 3) * lh);+ updateStatus();+ }++ function openFromComputer() {+ fileInput.click();+ }+ fileInput.addEventListener('change', async () => {+ const files = [...fileInput.files];+ fileInput.value = '';+ for (const f of files) {+ try {+ const text = await f.text();+ const only = docs.length === 1 && !docs[0].path && !isDirty(docs[0]) && !docs[0].ta.value;+ addDoc({ name: f.name, text, saved: '' });+ if (only) closeDoc(docs[0], true);+ } catch (e) {+ err(e);+ }+ }+ });++ /* --- commands and keys --- */+ const act = {+ new: () => addDoc(),+ open: async () => {+ const p = await fileDialog({ mode: 'open', dir: cur?.path ? fs.parentOf(cur.path) : '/Documents' });+ if (p) openPath(p);+ },+ computer: openFromComputer,+ save: () => saveDoc(cur),+ saveas: () => saveDoc(cur, true),+ find: () => openFind(false),+ goto: gotoLine,+ wrap: () => {+ prefs.wrap = !prefs.wrap;+ savePrefs();+ applyViewAll();+ },+ zin: () => setSize(prefs.size + 2),+ zout: () => setSize(prefs.size - 2),+ next: () => selectMatch(false),+ prev: () => selectMatch(true),+ case: () => {+ caseSens = !caseSens;+ q('[data-act="case"]').setAttribute('aria-pressed', caseSens);+ updateCount();+ },+ closefind: closeFind,+ replace: replaceCurrent,+ replaceall: replaceEverything,+ };+ root.addEventListener('click', (e) => {+ const b = e.target.closest('[data-act]');+ if (b) return act[b.dataset.act]?.();+ const t = e.target.closest('.np-tab');+ if (!t) return;+ const d = docs.find((x) => x.id === t.dataset.id);+ if (!d) return;+ if (e.target.closest('.np-x')) closeDoc(d);+ else activateDoc(d);+ });+ tabsEl.addEventListener('auxclick', (e) => {+ const t = e.target.closest('.np-tab');+ if (e.button === 1 && t) closeDoc(docs.find((x) => x.id === t.dataset.id));+ });+ tabsEl.addEventListener('keydown', (e) => {+ const i = docs.indexOf(cur);+ if (e.key === 'ArrowRight') activateDoc(docs[(i + 1) % docs.length]);+ else if (e.key === 'ArrowLeft') activateDoc(docs[(i - 1 + docs.length) % docs.length]);+ else return;+ tabsEl.querySelector('.np-tab.on')?.focus();+ });+ root.addEventListener('keydown', (e) => {+ const mod = e.ctrlKey || e.metaKey;+ const k = e.key.toLowerCase();+ if (mod && k === 's') return e.preventDefault(), saveDoc(cur, e.shiftKey);+ if (mod && k === 'n') return e.preventDefault(), addDoc();+ if (mod && k === 'o') return e.preventDefault(), act.open();+ if (mod && k === 'w') return e.preventDefault(), closeDoc(cur);+ if (mod && k === 'f') return e.preventDefault(), openFind(false);+ if (mod && k === 'h') return e.preventDefault(), openFind(true);+ if (mod && k === 'g') return e.preventDefault(), gotoLine();+ if (mod && (k === '=' || k === '+')) return e.preventDefault(), act.zin();+ if (mod && k === '-') return e.preventDefault(), act.zout();+ if (mod && k === '0') return e.preventDefault(), setSize(DEFAULT_SIZE);+ if (mod && e.key === 'Tab') {+ e.preventDefault();+ return activateDoc(docs[(docs.indexOf(cur) + (e.shiftKey ? -1 : 1) + docs.length) % docs.length]);+ }+ if (e.key === 'F3') return e.preventDefault(), findIn.value ? selectMatch(e.shiftKey) : openFind(false);+ });++ // Dropped text files from the real OS open as tabs.+ root.addEventListener('dragover', (e) => {+ if ([...(e.dataTransfer?.types || [])].includes('Files')) e.preventDefault();+ });+ root.addEventListener('drop', async (e) => {+ const files = [...(e.dataTransfer?.files || [])];+ if (!files.length) return;+ e.preventDefault();+ for (const f of files) {+ try {+ addDoc({ name: f.name, text: await f.text(), saved: '' });+ } catch (x) {+ err(x);+ }+ }+ });++ /* --- startup: restore drafts, then honour the launch argument --- */+ async function restore() {+ for (const dr of parseDrafts(ctx.store.get(DRAFTS_KEY))) {+ let saved = '';+ if (dr.path) saved = (await fs.readText(dr.path).catch(() => null)) ?? '';+ addDoc({ id: dr.id, path: dr.path, name: dr.name, text: dr.text, saved, activate: false });+ }+ if (docs.length) ctx.toast('Restored your unsaved notes');+ }+ async function applyArg(arg) {+ if (typeof arg !== 'string' || !arg) return;+ await openPath(fs.normalize(arg));+ }+ ctx.onArg(applyArg);++ q('[data-act="wrap"]').setAttribute('aria-pressed', prefs.wrap);+ renderTabs();+ restore()+ .then(() => applyArg(ctx.arg))+ .then(() => {+ if (dead) return;+ if (!docs.length) addDoc();+ else if (!cur) activateDoc(docs[docs.length - 1]);+ });++ return () => {+ dead = true;+ clearTimeout(draftTimer);+ flushDrafts();+ window.removeEventListener('pagehide', onHide);+ };+}diff --git a/src/desktop/os/apps/paint-logic.js b/src/desktop/os/apps/paint-logic.jsnew file mode 100644index 000000000..2d7a1d8e2--- /dev/null+++ b/src/desktop/os/apps/paint-logic.js@@ -0,0 +1,148 @@+// Pure helpers for Paint: scanline flood fill, undo/redo history, colour parsing and shape maths.+// Works on plain { data: Uint8ClampedArray, width, height } so it runs under Node as well as in the browser.++/** "#rrggbb" or "#rgb" to [r, g, b], or null. */+export function hexToRgb(hex) {+ const m = /^#?([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(String(hex).trim());+ if (!m) return null;+ let s = m[1];+ if (s.length === 3) s = [...s].map((c) => c + c).join('');+ const n = parseInt(s, 16);+ return [(n >> 16) & 255, (n >> 8) & 255, n & 255];+}+export const rgbToHex = (r, g, b) => `#${[r, g, b].map((v) => Math.max(0, Math.min(255, Math.round(v))).toString(16).padStart(2, '0')).join('')}`;++const near = (d, i, t, tol) => Math.abs(d[i] - t[0]) <= tol && Math.abs(d[i + 1] - t[1]) <= tol && Math.abs(d[i + 2] - t[2]) <= tol && Math.abs(d[i + 3] - t[3]) <= tol;++/**+ * Scanline flood fill. Replaces the connected region around (x, y) whose colour is within `tolerance`+ * (0 to 255 per channel) of the start pixel with `rgb`, blended by `opacity` (0 to 1).+ * Mutates image.data and returns the number of pixels changed.+ */+export function floodFill(image, x, y, rgb, { tolerance = 0, opacity = 1 } = {}) {+ const { data, width, height } = image;+ x = Math.floor(x);+ y = Math.floor(y);+ if (x < 0 || y < 0 || x >= width || y >= height) return 0;+ const si = (y * width + x) * 4;+ const target = [data[si], data[si + 1], data[si + 2], data[si + 3]];+ const visited = new Uint8Array(width * height);+ const match = (px, py) => !visited[py * width + px] && near(data, (py * width + px) * 4, target, tolerance);+ let changed = 0;+ const stack = [[x, y]];+ while (stack.length) {+ const [sx, sy] = stack.pop();+ if (!match(sx, sy)) continue;+ let l = sx;+ while (l > 0 && match(l - 1, sy)) l--;+ let r = sx;+ while (r < width - 1 && match(r + 1, sy)) r++;+ for (let px = l; px <= r; px++) {+ const p = sy * width + px;+ visited[p] = 1;+ const i = p * 4;+ data[i] = Math.round(data[i] * (1 - opacity) + rgb[0] * opacity);+ data[i + 1] = Math.round(data[i + 1] * (1 - opacity) + rgb[1] * opacity);+ data[i + 2] = Math.round(data[i + 2] * (1 - opacity) + rgb[2] * opacity);+ data[i + 3] = Math.round(data[i + 3] * (1 - opacity) + 255 * opacity);+ changed++;+ }+ for (const ny of [sy - 1, sy + 1]) {+ if (ny < 0 || ny >= height) continue;+ let inRun = false;+ for (let px = l; px <= r; px++) {+ if (match(px, ny)) {+ if (!inRun) stack.push([px, ny]);+ inRun = true;+ } else inRun = false;+ }+ }+ }+ return changed;+}++/** Undo/redo over snapshots (anything with .data.length). Bounded by count and total bytes. */+export class History {+ constructor({ maxCount = 60, maxBytes = 256 * 1024 * 1024 } = {}) {+ this.maxCount = maxCount;+ this.maxBytes = maxBytes;+ this.undoStack = [];+ this.redoStack = [];+ }+ static size(s) {+ return s?.data?.length || 0;+ }+ /** Record the state BEFORE a change. Clears redo. */+ push(snapshot) {+ this.undoStack.push(snapshot);+ this.redoStack = [];+ this.trim();+ }+ trim() {+ let bytes = this.undoStack.reduce((n, s) => n + History.size(s), 0);+ while (this.undoStack.length > 1 && (this.undoStack.length > this.maxCount || bytes > this.maxBytes)) bytes -= History.size(this.undoStack.shift());+ }+ get canUndo() {+ return this.undoStack.length > 0;+ }+ get canRedo() {+ return this.redoStack.length > 0;+ }+ /** Step back: pass the CURRENT state, get the previous one (or null). */+ undo(current) {+ if (!this.undoStack.length) return null;+ this.redoStack.push(current);+ return this.undoStack.pop();+ }+ redo(current) {+ if (!this.redoStack.length) return null;+ this.undoStack.push(current);+ return this.redoStack.pop();+ }+ clear() {+ this.undoStack = [];+ this.redoStack = [];+ }+}++export const ZOOM_STEPS = [0.1, 0.25, 0.33, 0.5, 0.67, 0.75, 1, 1.25, 1.5, 2, 3, 4, 6, 8];+export const clampZoom = (z) => Math.max(0.1, Math.min(8, z));+/** Next zoom stop above (dir 1) or below (dir -1) `z`. */+export function stepZoom(z, dir) {+ if (dir > 0) return ZOOM_STEPS.find((s) => s > z + 1e-6) ?? ZOOM_STEPS[ZOOM_STEPS.length - 1];+ return [...ZOOM_STEPS].reverse().find((s) => s < z - 1e-6) ?? ZOOM_STEPS[0];+}+/** Largest zoom (at most 1) at which a w by h canvas fits a box. */+export const fitZoom = (w, h, boxW, boxH) => clampZoom(Math.min(1, boxW / w, boxH / h));++/**+ * Constrain the drag from (x0, y0) to (x1, y1): lines snap to 45 degree steps, boxes to squares/circles.+ */+export function constrain(kind, x0, y0, x1, y1) {+ const dx = x1 - x0;+ const dy = y1 - y0;+ if (kind === 'line') {+ const a = Math.round(Math.atan2(dy, dx) / (Math.PI / 4)) * (Math.PI / 4);+ const len = Math.hypot(dx, dy);+ return [x0 + Math.cos(a) * len, y0 + Math.sin(a) * len];+ }+ const m = Math.max(Math.abs(dx), Math.abs(dy));+ return [x0 + Math.sign(dx || 1) * m, y0 + Math.sign(dy || 1) * m];+}++/** Brush width for a pointer: mouse is constant, pens scale with pressure (0 to 1). */+export function pressureWidth(size, pointerType, pressure) {+ if (pointerType !== 'pen' || !(pressure > 0)) return size;+ return Math.max(0.5, size * (0.25 + pressure * 1.5));+}++/** Clamp a canvas dimension to a sane range. */+export const clampDim = (n) => Math.max(1, Math.min(8192, Math.round(Number(n) || 0)));++/** Output format for a file name: png, jpeg or webp. Defaults to png. */+export function formatForName(name) {+ const e = String(name).split('.').pop().toLowerCase();+ if (e === 'jpg' || e === 'jpeg') return { ext: e, mime: 'image/jpeg' };+ if (e === 'webp') return { ext: 'webp', mime: 'image/webp' };+ return { ext: 'png', mime: 'image/png' };+}diff --git a/src/desktop/os/apps/paint.css b/src/desktop/os/apps/paint.cssnew file mode 100644index 000000000..ee562b141--- /dev/null+++ b/src/desktop/os/apps/paint.css@@ -0,0 +1,58 @@+.napp-paint { display: flex; flex-direction: column; min-height: 0; background: var(--card); color: var(--text); }+.napp-paint .pt { position: relative; flex: 1; display: flex; flex-direction: column; min-height: 0; outline: none; }+.napp-paint .pt-row { display: flex; align-items: center; gap: 4px; padding: 5px 8px; border-bottom: 1px solid var(--bd); flex-wrap: wrap; }+.napp-paint .pt-opts { gap: 12px; }+.napp-paint .pt-grow { flex: 1; }+.napp-paint .pt-sep { width: 1px; height: 22px; background: var(--bd); margin: 0 4px; }+.napp-paint .pt-ab, .napp-paint .pt-tool, .napp-paint .pt-zb { display: inline-flex; align-items: center; gap: 6px; border: 1px solid transparent; background: transparent; color: var(--text); border-radius: 6px; padding: 5px 9px; font: inherit; font-size: 0.82rem; cursor: pointer; }+.napp-paint .pt-ab.icon, .napp-paint .pt-tool { padding: 6px; }+.napp-paint .pt-ab:hover:not(:disabled), .napp-paint .pt-tool:hover, .napp-paint .pt-zb:hover { background: var(--hover); }+.napp-paint .pt-ab:active:not(:disabled), .napp-paint .pt-tool:active, .napp-paint .pt-zb:active { transform: scale(0.95); }+.napp-paint .pt-ab:disabled { opacity: 0.35; cursor: default; }+.napp-paint .pt-ab.dirty { color: var(--accent); }+.napp-paint .pt-tool.on { background: var(--accent); color: #fff; }+.napp-paint button:focus-visible, .napp-paint select:focus-visible, .napp-paint input:focus-visible, .napp-paint .pt:focus-visible { outline: 2px solid var(--accent); outline-offset: 1px; }+.napp-paint .pt-field { display: inline-flex; align-items: center; gap: 6px; font-size: 0.78rem; color: var(--text2); }+.napp-paint .pt-field[hidden] { display: none; }+.napp-paint .pt-rng { display: inline-flex; align-items: center; gap: 6px; }+.napp-paint .pt-rng input { width: 90px; accent-color: var(--accent); }+.napp-paint .pt-rng output { min-width: 30px; font-variant-numeric: tabular-nums; color: var(--text); }+.napp-paint .pt-sel, .napp-paint .pt-in { background: var(--hover); color: var(--text); border: 1px solid var(--bd); border-radius: 6px; padding: 5px 8px; font: inherit; font-size: 0.85rem; }+.napp-paint .pt-cur { width: 28px; height: 28px; border-radius: 6px; border: 2px solid var(--bd); box-shadow: inset 0 0 0 1px #0003; }+.napp-paint .pt-swatches { display: grid; grid-template-columns: repeat(10, 18px); gap: 3px; }+.napp-paint .pt-sw { width: 18px; height: 18px; border-radius: 4px; border: 1px solid #0004; padding: 0; cursor: pointer; }+.napp-paint .pt-sw:hover { transform: scale(1.15); }+.napp-paint .pt-sw.on { outline: 2px solid var(--accent); outline-offset: 1px; }+.napp-paint .pt-color { width: 34px; height: 28px; padding: 0; border: 1px solid var(--bd); border-radius: 6px; background: transparent; cursor: pointer; }+.napp-paint .pt-view { flex: 1; min-height: 0; overflow: auto; background: var(--hover); padding: 20px; display: grid; }+.napp-paint .pt-view.drop { outline: 3px dashed var(--accent); outline-offset: -8px; }+.napp-paint .pt-sheet { position: relative; margin: auto; box-shadow: 0 2px 14px #0005; background: #fff; flex: none; }+.napp-paint .pt-cv, .napp-paint .pt-ov { position: absolute; inset: 0; width: 100%; height: 100%; touch-action: none; image-rendering: pixelated; }+.napp-paint .pt-ov { pointer-events: none; image-rendering: auto; }+.napp-paint .pt-text { position: absolute; min-width: 80px; background: transparent; border: 1px dashed var(--accent); padding: 0; margin: 0; resize: none; overflow: hidden; line-height: 1.2; outline: none; }+.napp-paint .pt-status { display: flex; align-items: center; gap: 16px; padding: 4px 10px; border-top: 1px solid var(--bd); font-size: 0.76rem; color: var(--text2); font-variant-numeric: tabular-nums; }+.napp-paint .pt-status .pos { min-width: 90px; }+.napp-paint .pt-status .msg { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }+.napp-paint .pt-status .grow { flex: 1; }+.napp-paint .pt-zoom { display: inline-flex; align-items: center; gap: 4px; }+.napp-paint .pt-zoom input { width: 110px; accent-color: var(--accent); }+.napp-paint .pt-zoom .z { min-width: 40px; text-align: right; }+.napp-paint .pt-zb { padding: 2px 7px; }+.napp-paint .pt-dialog { position: absolute; inset: 0; z-index: 10; display: grid; place-items: center; background: #0006; }+.napp-paint .pt-dialog[hidden] { display: none; }+.napp-paint .pt-card { background: var(--card); color: var(--text); border: 1px solid var(--bd); border-radius: 10px; padding: 18px; width: min(380px, 92%); display: flex; flex-direction: column; gap: 10px; box-shadow: 0 12px 40px #0008; }+.napp-paint .pt-card h3 { margin: 0; font-size: 1rem; }+.napp-paint .pt-card label { display: flex; flex-direction: column; gap: 4px; font-size: 0.8rem; color: var(--text2); }+.napp-paint .pt-card .pt-chk { flex-direction: row; align-items: center; gap: 8px; }+.napp-paint .pt-two { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; }+.napp-paint .pt-presets { display: flex; flex-wrap: wrap; gap: 6px; }+.napp-paint .pt-chip { border: 1px solid var(--bd); background: var(--hover); color: var(--text); border-radius: 999px; padding: 4px 10px; font: inherit; font-size: 0.78rem; cursor: pointer; }+.napp-paint .pt-chip:hover { border-color: var(--accent); }+.napp-paint .pt-hint { margin: 0; font-size: 0.8rem; color: var(--text2); }+.napp-paint .pt-warn { margin: 0; font-size: 0.8rem; color: #e5484d; }+.napp-paint .pt-warn[hidden] { display: none; }+.napp-paint .pt-btns { display: flex; justify-content: flex-end; gap: 8px; margin-top: 4px; }+.napp-paint .pt-btn { border: 1px solid var(--bd); background: var(--hover); color: var(--text); border-radius: 6px; padding: 7px 16px; font: inherit; cursor: pointer; }+.napp-paint .pt-btn.primary { background: var(--accent); border-color: var(--accent); color: #fff; font-weight: 600; }+.napp-paint .pt-btn:hover { filter: brightness(1.1); }+@media (max-width: 640px) { .napp-paint .pt-ab span { display: none; } .napp-paint .pt-swatches { grid-template-columns: repeat(10, 22px); } .napp-paint .pt-sw { width: 22px; height: 22px; } }diff --git a/src/desktop/os/apps/paint.js b/src/desktop/os/apps/paint.jsnew file mode 100644index 000000000..f5f2feb6d--- /dev/null+++ b/src/desktop/os/apps/paint.js@@ -0,0 +1,977 @@+// Paint: a canvas editor with pen, pencil, brush, eraser, shapes, fill, eyedropper and text,+// undo/redo, zoom, resize, open/save through the virtual file system, clipboard and download.+import './paint.css';+import { floodFill, History, hexToRgb, rgbToHex, stepZoom, fitZoom, constrain, pressureWidth, clampDim, formatForName, clampZoom } from './paint-logic.js';++const svg = (b, s = 18) => `<svg viewBox="0 0 24 24" width="${s}" height="${s}" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">${b}</svg>`;+const TOOLS = [+ ['pen', 'Pen', 'P', svg('<path d="M4 20l1-4L16 5l3 3L8 19zM14 7l3 3"/>')],+ ['pencil', 'Pencil', 'N', svg('<path d="M4 20l1-4 11-11 3 3L8 19z"/><path d="M4 20h4" stroke-width="3"/>')],+ ['brush', 'Brush', 'B', svg('<path d="M14 4l6 6-8 8c-1 1-2.5 1.5-4 1.5-2 0-3.5 1-4.5 1.5.5-1.5 1.5-3 1.5-5 0-1.5.5-3 1.5-4z"/>')],+ ['eraser', 'Eraser', 'E', svg('<path d="M4 16l9-10 7 7-6 6H8zM9 11l6 6M12 20h8"/>')],+ ['fill', 'Fill', 'F', svg('<path d="M5 12l7-8 7 7-7 8zM4 20h6M19 14c1 1.5 2 2.5 2 4a2 2 0 0 1-4 0c0-1.5 1-2.5 2-4z"/>')],+ ['picker', 'Eyedropper', 'I', svg('<path d="M20 4a2.5 2.5 0 0 0-3.5 0L14 6.5 17.5 10 20 7.5A2.5 2.5 0 0 0 20 4zM13 8l-8 8v4h4l8-8z"/>')],+ ['text', 'Text', 'T', svg('<path d="M5 5h14M12 5v14M9 19h6"/>')],+ ['line', 'Line', 'L', svg('<path d="M5 19L19 5"/>')],+ ['rect', 'Rectangle', 'R', svg('<rect x="4" y="6" width="16" height="12" rx="1"/>')],+ ['ellipse', 'Ellipse', 'O', svg('<ellipse cx="12" cy="12" rx="8" ry="6"/>')],+];+const ACTION_ICONS = {+ new: svg('<path d="M6 3h9l4 4v14H6zM14 3v5h5M12 11v6M9 14h6"/>'),+ open: svg('<path d="M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v1H3zM3 10h19l-2 8H5z"/>'),+ save: svg('<path d="M5 4h11l3 3v13H5zM8 4v5h7V4M8 20v-6h8v6"/>'),+ undo: svg('<path d="M9 7L4 12l5 5M4 12h10a6 6 0 0 1 0 12h-2" transform="translate(0 -3)"/>'),+ redo: svg('<path d="M15 7l5 5-5 5M20 12H10a6 6 0 0 0 0 12h2" transform="translate(0 -3)"/>'),+ copy: svg('<rect x="8" y="8" width="12" height="12" rx="2"/><path d="M16 8V6a2 2 0 0 0-2-2H6a2 2 0 0 0-2 2v8a2 2 0 0 0 2 2h2"/>'),+ paste: svg('<path d="M9 4h6v3H9zM15 5h2a2 2 0 0 1 2 2v13H5V7a2 2 0 0 1 2-2h2"/>'),+ download: svg('<path d="M12 4v11M7 11l5 5 5-5M5 20h14"/>'),+ clear: svg('<path d="M4 7h16M10 7V4h4v3M6 7l1 13h10l1-13"/>'),+ fit: svg('<path d="M4 9V4h5M20 9V4h-5M4 15v5h5M20 15v5h-5"/>'),+};+const PALETTE = ['#000000', '#7f7f7f', '#880015', '#ed1c24', '#ff7f27', '#fff200', '#22b14c', '#00a2e8', '#3f48cc', '#a349a4', '#ffffff', '#c3c3c3', '#b97a57', '#ffaec9', '#ffc90e', '#efe4b0', '#b5e61d', '#99d9ea', '#7092be', '#c8bfe7'];+const FONTS = { Sans: 'system-ui, "Segoe UI", sans-serif', Serif: 'Georgia, "Times New Roman", serif', Mono: 'ui-monospace, Consolas, monospace', Handwriting: '"Comic Sans MS", "Segoe Print", cursive' };++export function mount(host, ctx) {+ const { h, esc, fs, store } = ctx;+ host.classList.add('napp-paint');+ host.innerHTML = '';++ const st = {+ tool: 'pen', prevTool: 'pen', color: store.get('tws:paint:color') || '#000000', size: Number(store.get('tws:paint:size')) || 4,+ opacity: 100, tolerance: 24, filled: false, font: 'Sans', zoom: 1, path: null, name: 'Untitled', dirty: false,+ };+ const hist = new History();+ let W = 800;+ let H = 520;+ let disposed = false;+ let drawing = null;+ let floating = null;+ let textBox = null;+ let loadToken = 0;++ // ---- DOM ----+ const root = h('div', 'pt');+ root.tabIndex = 0;+ const actions = h('div', 'pt-row pt-actions');+ const toolsRow = h('div', 'pt-row pt-tools');+ const optsRow = h('div', 'pt-row pt-opts');+ const viewport = h('div', 'pt-view');+ const sheet = h('div', 'pt-sheet');+ const cv = h('canvas', 'pt-cv');+ const ov = h('canvas', 'pt-ov');+ cv.setAttribute('aria-label', 'Drawing canvas');+ cv.setAttribute('role', 'img');+ sheet.append(cv, ov);+ viewport.append(sheet);+ const status = h('div', 'pt-status');+ const stPos = h('span', 'pos', '');+ const stSize = h('span', 'dim', '');+ const stMsg = h('span', 'msg', '');+ const zoomWrap = h('div', 'pt-zoom');+ status.append(stPos, stSize, stMsg, h('span', 'grow'), zoomWrap);+ const dialog = h('div', 'pt-dialog');+ dialog.hidden = true;+ root.append(actions, toolsRow, optsRow, viewport, status, dialog);+ host.append(root);+ const g = cv.getContext('2d', { willReadFrequently: true });+ const o = ov.getContext('2d');++ // ---- canvas helpers ----+ function sizeCanvas(w, h2, keep) {+ const snap = keep ? g.getImageData(0, 0, cv.width, cv.height) : null;+ W = w;+ H = h2;+ cv.width = ov.width = w;+ cv.height = ov.height = h2;+ g.fillStyle = '#ffffff';+ g.fillRect(0, 0, w, h2);+ if (snap) g.putImageData(snap, 0, 0);+ applyZoom();+ }+ function applyZoom() {+ sheet.style.width = `${Math.round(W * st.zoom)}px`;+ sheet.style.height = `${Math.round(H * st.zoom)}px`;+ stSize.textContent = `${W} × ${H} px`;+ zoomLabel.textContent = `${Math.round(st.zoom * 100)}%`;+ zoomRange.value = String(Math.round(st.zoom * 100));+ }+ const snapshot = () => g.getImageData(0, 0, cv.width, cv.height);+ function restore(s) {+ if (s.width !== cv.width || s.height !== cv.height) {+ W = s.width;+ H = s.height;+ cv.width = ov.width = W;+ cv.height = ov.height = H;+ applyZoom();+ }+ g.putImageData(s, 0, 0);+ }+ function checkpoint() {+ hist.push(snapshot());+ setDirty(true);+ syncUi();+ }+ function setDirty(d) {+ st.dirty = d;+ ctx.setTitle(`${st.name}${d ? ' *' : ''} - Paint`);+ }+ function undo() {+ commitFloat();+ const s = hist.undo(snapshot());+ if (s) {+ restore(s);+ setDirty(true);+ }+ syncUi();+ }+ function redo() {+ commitFloat();+ const s = hist.redo(snapshot());+ if (s) {+ restore(s);+ setDirty(true);+ }+ syncUi();+ }+ const msg = (t) => {+ stMsg.textContent = t;+ };++ function pos(e) {+ const r = cv.getBoundingClientRect();+ return [((e.clientX - r.left) / r.width) * W, ((e.clientY - r.top) / r.height) * H];+ }+ const rgba = (alpha = 1) => {+ const [r, gg, b] = hexToRgb(st.color) || [0, 0, 0];+ return `rgba(${r},${gg},${b},${alpha})`;+ };++ // ---- tools ----+ const paintsOnOverlay = () => ['pen', 'brush'].includes(st.tool);+ function strokeSeg(c, x0, y0, x1, y1, width) {+ c.lineCap = 'round';+ c.lineJoin = 'round';+ c.lineWidth = width;+ c.beginPath();+ c.moveTo(x0, y0);+ c.lineTo(x1, y1);+ c.stroke();+ }+ function pencilSeg(c, x0, y0, x1, y1, sz) {+ // Bresenham with a square nib: crisp, aliased pixels.+ let ax = Math.floor(x0);+ let ay = Math.floor(y0);+ const bx = Math.floor(x1);+ const by = Math.floor(y1);+ const dx = Math.abs(bx - ax);+ const dy = -Math.abs(by - ay);+ const sx = ax < bx ? 1 : -1;+ const sy = ay < by ? 1 : -1;+ let err = dx + dy;+ const n = Math.max(1, Math.round(sz / 2));+ for (;;) {+ c.fillRect(ax - Math.floor(n / 2), ay - Math.floor(n / 2), n, n);+ if (ax === bx && ay === by) break;+ const e2 = 2 * err;+ if (e2 >= dy) {+ err += dy;+ ax += sx;+ }+ if (e2 <= dx) {+ err += dx;+ ay += sy;+ }+ }+ }+ function shapePath(c, kind, x0, y0, x1, y1) {+ c.beginPath();+ if (kind === 'line') {+ c.moveTo(x0, y0);+ c.lineTo(x1, y1);+ } else if (kind === 'rect') c.rect(Math.min(x0, x1), Math.min(y0, y1), Math.abs(x1 - x0), Math.abs(y1 - y0));+ else c.ellipse((x0 + x1) / 2, (y0 + y1) / 2, Math.abs(x1 - x0) / 2, Math.abs(y1 - y0) / 2, 0, 0, Math.PI * 2);+ }+ function drawShape(c, d, x1, y1) {+ let [x0, y0] = [d.x0, d.y0];+ if (d.shift) [x1, y1] = constrain(d.kind === 'line' ? 'line' : 'box', x0, y0, x1, y1);+ c.clearRect(0, 0, W, H);+ c.lineWidth = st.size;+ c.lineJoin = 'round';+ c.lineCap = 'round';+ c.strokeStyle = c.fillStyle = rgba(1);+ shapePath(c, d.kind, x0, y0, x1, y1);+ if (d.kind !== 'line' && st.filled) c.fill();+ else c.stroke();+ d.end = [x1, y1];+ }++ function onDown(e) {+ if (e.button > 0 && e.pointerType === 'mouse' && e.button !== 2) return;+ if (drawing) return;+ if (floating) {+ const [x, y] = pos(e);+ if (x >= floating.x && y >= floating.y && x <= floating.x + floating.w && y <= floating.y + floating.h) {+ floating.drag = [x - floating.x, y - floating.y];+ cv.setPointerCapture(e.pointerId);+ e.preventDefault();+ return;+ }+ commitFloat();+ }+ if (textBox) commitText();+ const [x, y] = pos(e);+ const right = e.button === 2;+ e.preventDefault();+ root.focus({ preventScroll: true });+ const t = st.tool;+ if (t === 'picker') return pickColor(x, y);+ if (t === 'text') return beginText(x, y);+ if (t === 'fill') {+ checkpoint();+ const im = g.getImageData(0, 0, W, H);+ const rgb = right ? [255, 255, 255] : hexToRgb(st.color);+ const n = floodFill(im, x, y, rgb, { tolerance: st.tolerance, opacity: st.opacity / 100 });+ if (n) g.putImageData(im, 0, 0);+ else {+ hist.undo(snapshot());+ syncUi();+ }+ return;+ }+ cv.setPointerCapture(e.pointerId);+ checkpoint();+ drawing = { id: e.pointerId, kind: t, x0: x, y0: y, lx: x, ly: y, shift: e.shiftKey, pen: e.pointerType, erase: t === 'eraser' || right };+ if (['line', 'rect', 'ellipse'].includes(t)) {+ ov.style.opacity = String(st.opacity / 100);+ drawShape(o, drawing, x, y);+ return;+ }+ if (paintsOnOverlay() && !right) {+ ov.style.opacity = String(st.opacity / 100);+ o.clearRect(0, 0, W, H);+ o.strokeStyle = o.fillStyle = rgba(1);+ applyBrush(o);+ dot(o, x, y, pressureWidth(st.size, e.pointerType, e.pressure));+ } else {+ stroke(g, x, y, x, y, e);+ }+ }+ function applyBrush(c) {+ if (st.tool === 'brush') {+ c.shadowColor = rgba(1);+ c.shadowBlur = Math.max(2, st.size * 0.6);+ } else {+ c.shadowBlur = 0;+ c.shadowColor = 'transparent';+ }+ }+ function dot(c, x, y, w) {+ c.beginPath();+ c.arc(x, y, w / 2, 0, Math.PI * 2);+ c.fill();+ }+ function stroke(c, x0, y0, x1, y1, e) {+ const w = pressureWidth(drawing.erase ? st.size * 2.5 : st.size, e.pointerType, e.pressure);+ if (drawing.erase) {+ c.save();+ c.strokeStyle = c.fillStyle = '#ffffff';+ c.shadowBlur = 0;+ strokeSeg(c, x0, y0, x1, y1, w);+ dot(c, x1, y1, w);+ c.restore();+ } else if (st.tool === 'pencil') {+ c.fillStyle = rgba(st.opacity / 100);+ pencilSeg(c, x0, y0, x1, y1, st.size);+ } else {+ strokeSeg(c, x0, y0, x1, y1, w);+ }+ }+ function onMove(e) {+ const [x, y] = pos(e);+ stPos.textContent = x >= 0 && y >= 0 && x < W && y < H ? `${Math.floor(x)}, ${Math.floor(y)} px` : '';+ if (floating?.drag) {+ floating.x = Math.round(x - floating.drag[0]);+ floating.y = Math.round(y - floating.drag[1]);+ drawFloat();+ return;+ }+ if (!drawing || e.pointerId !== drawing.id) return;+ const evs = e.getCoalescedEvents?.().length ? e.getCoalescedEvents() : [e];+ for (const ev of evs) {+ const [px, py] = pos(ev);+ if (['line', 'rect', 'ellipse'].includes(drawing.kind)) {+ drawing.shift = ev.shiftKey;+ drawShape(o, drawing, px, py);+ } else if (paintsOnOverlay() && !drawing.erase) {+ applyBrush(o);+ o.strokeStyle = o.fillStyle = rgba(1);+ strokeSeg(o, drawing.lx, drawing.ly, px, py, pressureWidth(st.size, ev.pointerType, ev.pressure));+ } else stroke(g, drawing.lx, drawing.ly, px, py, ev);+ drawing.lx = px;+ drawing.ly = py;+ }+ }+ function onUp(e) {+ if (floating?.drag) {+ floating.drag = null;+ return;+ }+ if (!drawing || e.pointerId !== drawing.id) return;+ const d = drawing;+ drawing = null;+ if (['line', 'rect', 'ellipse'].includes(d.kind) || (paintsOnOverlay() && !d.erase)) {+ g.save();+ g.globalAlpha = st.opacity / 100;+ g.drawImage(ov, 0, 0);+ g.restore();+ o.clearRect(0, 0, W, H);+ ov.style.opacity = '1';+ }+ }+ function onCancel(e) {+ if (!drawing || e.pointerId !== drawing.id) return;+ onUp(e);+ }+ cv.addEventListener('pointerdown', onDown);+ cv.addEventListener('pointermove', onMove);+ cv.addEventListener('pointerup', onUp);+ cv.addEventListener('pointercancel', onCancel);+ cv.addEventListener('contextmenu', (e) => e.preventDefault());+ cv.addEventListener('pointerleave', () => {+ if (!drawing) stPos.textContent = '';+ });++ function pickColor(x, y) {+ const px = g.getImageData(Math.max(0, Math.min(W - 1, Math.floor(x))), Math.max(0, Math.min(H - 1, Math.floor(y))), 1, 1).data;+ setColor(rgbToHex(px[0], px[1], px[2]));+ setTool(st.prevTool === 'picker' ? 'pen' : st.prevTool);+ msg(`Picked ${st.color}`);+ }++ // ---- text ----+ function beginText(x, y) {+ const px = Math.max(10, st.size * 3 + 8);+ const ta = h('textarea', 'pt-text');+ ta.rows = 1;+ ta.spellcheck = false;+ ta.setAttribute('aria-label', 'Text to place on the canvas');+ ta.placeholder = 'Type...';+ const sc = st.zoom;+ Object.assign(ta.style, { left: `${x * sc}px`, top: `${y * sc}px`, fontSize: `${px * sc}px`, color: st.color, fontFamily: FONTS[st.font], opacity: String(st.opacity / 100) });+ textBox = { ta, x, y, px };+ sheet.append(ta);+ ta.addEventListener('input', () => {+ ta.style.height = 'auto';+ ta.style.height = `${ta.scrollHeight}px`;+ ta.style.width = `${Math.max(80, ta.scrollWidth)}px`;+ });+ ta.addEventListener('keydown', (e) => {+ e.stopPropagation();+ if (e.key === 'Escape') cancelText();+ else if (e.key === 'Enter' && (e.ctrlKey || e.metaKey)) commitText();+ });+ ta.addEventListener('blur', () => setTimeout(() => textBox?.ta === ta && commitText(), 120));+ requestAnimationFrame(() => ta.focus());+ }+ function cancelText() {+ textBox?.ta.remove();+ textBox = null;+ }+ function commitText() {+ if (!textBox) return;+ const { ta, x, y, px } = textBox;+ textBox = null;+ const text = ta.value;+ ta.remove();+ if (!text.trim()) return;+ checkpoint();+ g.save();+ g.globalAlpha = st.opacity / 100;+ g.fillStyle = st.color;+ g.textBaseline = 'top';+ g.font = `${px}px ${FONTS[st.font]}`;+ text.split('\n').forEach((line, i) => g.fillText(line, x + 2, y + 2 + i * px * 1.2));+ g.restore();+ }++ // ---- floating paste ----+ function drawFloat() {+ o.clearRect(0, 0, W, H);+ if (!floating) return;+ o.drawImage(floating.bmp, floating.x, floating.y);+ o.save();+ o.setLineDash([5, 4]);+ o.strokeStyle = '#0078d4';+ o.lineWidth = 1 / st.zoom;+ o.strokeRect(floating.x + 0.5, floating.y + 0.5, floating.w, floating.h);+ o.restore();+ }+ function commitFloat() {+ if (!floating) return;+ const f = floating;+ floating = null;+ o.clearRect(0, 0, W, H);+ checkpoint();+ g.drawImage(f.bmp, f.x, f.y);+ cv.style.cursor = '';+ msg('Pasted');+ }+ function cancelFloat() {+ floating = null;+ o.clearRect(0, 0, W, H);+ }+ async function beginFloat(blob) {+ let bmp;+ try {+ bmp = await createImageBitmap(blob);+ } catch {+ return ctx.toast('That clipboard content is not an image Paint can read');+ }+ commitFloat();+ if (bmp.width > W || bmp.height > H) {+ checkpoint();+ sizeCanvas(Math.max(W, bmp.width), Math.max(H, bmp.height), true);+ }+ const r = viewport.getBoundingClientRect();+ const sx = Math.max(0, Math.floor(viewport.scrollLeft / st.zoom));+ const sy = Math.max(0, Math.floor(viewport.scrollTop / st.zoom));+ floating = { bmp, x: Math.min(sx, W - bmp.width), y: Math.min(sy, H - bmp.height), w: bmp.width, h: bmp.height, drag: null };+ void r;+ drawFloat();+ msg('Drag to position the pasted image, then press Enter or click outside it to place it');+ }++ // ---- file ops ----+ async function loadBlob(blob, { path = null, name = 'Untitled' } = {}) {+ const token = ++loadToken;+ let bmp;+ try {+ bmp = await createImageBitmap(blob);+ } catch {+ return ctx.toast('Paint could not read that image');+ }+ if (token !== loadToken || disposed) return;+ cancelFloat();+ cancelText();+ hist.clear();+ sizeCanvas(clampDim(bmp.width), clampDim(bmp.height), false);+ g.drawImage(bmp, 0, 0);+ st.path = path;+ st.name = name;+ setDirty(false);+ fitView();+ syncUi();+ }+ async function openPath(p) {+ try {+ const f = await fs.read(p);+ if (!f) return ctx.toast(`Cannot find ${p}`);+ await loadBlob(f.blob, { path: p, name: fs.nameOf(p) });+ } catch (err) {+ ctx.toast(`Could not open ${p}: ${err.message}`);+ }+ }+ function toBlob(mime) {+ const c = document.createElement('canvas');+ c.width = W;+ c.height = H;+ const x = c.getContext('2d');+ if (mime === 'image/jpeg') {+ x.fillStyle = '#fff';+ x.fillRect(0, 0, W, H);+ }+ x.drawImage(cv, 0, 0);+ return new Promise((res, rej) => c.toBlob((b) => (b ? res(b) : rej(new Error('Could not encode the image'))), mime, 0.92));+ }+ async function writeTo(path) {+ commitFloat();+ const fmt = formatForName(path);+ const blob = await toBlob(fmt.mime);+ await fs.write(path, blob, { mime: fmt.mime });+ st.path = path;+ st.name = fs.nameOf(path);+ setDirty(false);+ msg(`Saved ${path}`);+ ctx.toast(`Saved ${st.name}`);+ }+ async function save() {+ try {+ if (st.path && formatForName(st.path).ext && (await fs.exists(st.path))) return await writeTo(st.path);+ const name = await fs.uniqueName('/Pictures', 'Drawing.png');+ await writeTo(fs.join('/Pictures', name));+ } catch (err) {+ ctx.toast(`Could not save: ${err.message}`);+ }+ }+ function modal(title, build) {+ dialog.replaceChildren();+ const card = h('form', 'pt-card');+ card.append(h('h3', '', esc(title)));+ const close = () => {+ dialog.hidden = true;+ dialog.replaceChildren();+ root.focus({ preventScroll: true });+ };+ build(card, close);+ card.addEventListener('keydown', (e) => {+ if (e.key === 'Escape') {+ e.stopPropagation();+ close();+ }+ });+ dialog.append(card);+ dialog.hidden = false;+ card.querySelector('input,select')?.focus();+ return close;+ }+ function saveAs() {+ const base = st.path ? fs.nameOf(st.path) : 'Drawing.png';+ modal('Save as', (card, close) => {+ card.insertAdjacentHTML('beforeend', `<label>File name<input class="pt-in" name="n" value="${esc(base)}" maxlength="100"></label><label>Folder<input class="pt-in" name="d" value="${esc(st.path ? fs.parentOf(st.path) : '/Pictures')}"></label><p class="pt-hint">Use .png, .jpg or .webp.</p><p class="pt-warn" hidden></p>`);+ const row = h('div', 'pt-btns');+ const cancel = h('button', 'pt-btn', 'Cancel');+ cancel.type = 'button';+ cancel.addEventListener('click', close);+ const ok = h('button', 'pt-btn primary', 'Save');+ ok.type = 'submit';+ row.append(cancel, ok);+ card.append(row);+ const warn = card.querySelector('.pt-warn');+ let armed = '';+ card.addEventListener('submit', async (e) => {+ e.preventDefault();+ let n = card.n.value.trim();+ const dir = fs.normalize(card.d.value.trim() || '/Pictures');+ if (!n) return;+ if (!/\.(png|jpe?g|webp)$/i.test(n)) n += '.png';+ const path = fs.join(dir, n);+ try {+ const dnode = await fs.stat(dir);+ if (!dnode || dnode.type !== 'dir') {+ warn.hidden = false;+ warn.textContent = `The folder ${dir} does not exist.`;+ return;+ }+ if ((await fs.exists(path)) && armed !== path) {+ armed = path;+ warn.hidden = false;+ warn.textContent = `${n} already exists. Choose Save again to replace it.`;+ return;+ }+ await writeTo(path);+ close();+ } catch (err) {+ warn.hidden = false;+ warn.textContent = err.message;+ }+ });+ });+ }+ async function exportDownload() {+ commitFloat();+ const fmt = st.path ? formatForName(st.path) : { ext: 'png', mime: 'image/png' };+ try {+ const blob = await toBlob(fmt.mime);+ const a = document.createElement('a');+ const u = URL.createObjectURL(blob);+ a.href = u;+ a.download = `${st.name.replace(/\.[^.]+$/, '')}.${fmt.ext === 'jpeg' ? 'jpg' : fmt.ext}`;+ document.body.append(a);+ a.click();+ a.remove();+ setTimeout(() => URL.revokeObjectURL(u), 4000);+ } catch (err) {+ ctx.toast(err.message);+ }+ }+ async function copyImage() {+ commitFloat();+ try {+ const blob = await toBlob('image/png');+ await navigator.clipboard.write([new ClipboardItem({ 'image/png': blob })]);+ ctx.toast('Image copied to the clipboard');+ } catch {+ ctx.toast('The browser blocked clipboard access. Allow it for this site, or use Export.');+ }+ }+ async function pasteImage() {+ try {+ const items = await navigator.clipboard.read();+ for (const it of items) {+ const type = it.types.find((t) => t.startsWith('image/'));+ if (type) return beginFloat(await it.getType(type));+ }+ ctx.toast('There is no image on the clipboard');+ } catch {+ ctx.toast('The browser blocked clipboard access. Press Ctrl+V with the canvas focused instead.');+ }+ }+ root.addEventListener('paste', (e) => {+ const item = [...(e.clipboardData?.items || [])].find((i) => i.type.startsWith('image/'));+ if (!item || e.target.closest('textarea,input')) return;+ e.preventDefault();+ beginFloat(item.getAsFile());+ });+ function confirmDiscard(next) {+ if (!st.dirty) return next();+ modal('Discard changes?', (card, close) => {+ card.append(h('p', 'pt-hint', `${esc(st.name)} has unsaved changes.`));+ const row = h('div', 'pt-btns');+ const cancel = h('button', 'pt-btn', 'Cancel');+ cancel.type = 'button';+ cancel.addEventListener('click', close);+ const sv = h('button', 'pt-btn', 'Save first');+ sv.type = 'button';+ sv.addEventListener('click', async () => {+ await save();+ close();+ if (!st.dirty) next();+ });+ const ok = h('button', 'pt-btn primary', 'Discard');+ ok.type = 'button';+ ok.addEventListener('click', () => {+ close();+ next();+ });+ row.append(cancel, sv, ok);+ card.append(row);+ });+ }+ function newImage() {+ confirmDiscard(() =>+ modal('New image', (card, close) => {+ card.insertAdjacentHTML('beforeend', `<div class="pt-two"><label>Width<input class="pt-in" type="number" name="w" min="1" max="8192" value="${W}"></label><label>Height<input class="pt-in" type="number" name="h" min="1" max="8192" value="${H}"></label></div><div class="pt-presets"></div>`);+ const presets = card.querySelector('.pt-presets');+ for (const [l, w, hh] of [['800 × 520', 800, 520], ['1280 × 720', 1280, 720], ['1920 × 1080', 1920, 1080], ['512 × 512', 512, 512]]) {+ const b = h('button', 'pt-chip', l);+ b.type = 'button';+ b.addEventListener('click', () => ((card.w.value = w), (card.h.value = hh)));+ presets.append(b);+ }+ const row = h('div', 'pt-btns');+ const cancel = h('button', 'pt-btn', 'Cancel');+ cancel.type = 'button';+ cancel.addEventListener('click', close);+ const ok = h('button', 'pt-btn primary', 'Create');+ ok.type = 'submit';+ row.append(cancel, ok);+ card.append(row);+ card.addEventListener('submit', (e) => {+ e.preventDefault();+ cancelFloat();+ cancelText();+ hist.clear();+ sizeCanvas(clampDim(card.w.value), clampDim(card.h.value), false);+ st.path = null;+ st.name = 'Untitled';+ setDirty(false);+ fitView();+ syncUi();+ close();+ });+ }),+ );+ }+ function resizeCanvas() {+ modal('Canvas size', (card, close) => {+ card.insertAdjacentHTML('beforeend', `<div class="pt-two"><label>Width<input class="pt-in" type="number" name="w" min="1" max="8192" value="${W}"></label><label>Height<input class="pt-in" type="number" name="h" min="1" max="8192" value="${H}"></label></div><label class="pt-chk"><input type="checkbox" name="scale"> Stretch the picture to the new size</label><p class="pt-hint">Otherwise the picture keeps its size and the canvas grows or crops from the bottom right.</p>`);+ const row = h('div', 'pt-btns');+ const cancel = h('button', 'pt-btn', 'Cancel');+ cancel.type = 'button';+ cancel.addEventListener('click', close);+ const ok = h('button', 'pt-btn primary', 'Apply');+ ok.type = 'submit';+ row.append(cancel, ok);+ card.append(row);+ card.addEventListener('submit', (e) => {+ e.preventDefault();+ commitFloat();+ const nw = clampDim(card.w.value);+ const nh = clampDim(card.h.value);+ checkpoint();+ if (card.scale.checked) {+ const t = document.createElement('canvas');+ t.width = W;+ t.height = H;+ t.getContext('2d').drawImage(cv, 0, 0);+ sizeCanvas(nw, nh, false);+ g.imageSmoothingQuality = 'high';+ g.drawImage(t, 0, 0, nw, nh);+ } else sizeCanvas(nw, nh, true);+ close();+ });+ });+ }+ function clearAll() {+ commitFloat();+ cancelText();+ checkpoint();+ g.fillStyle = '#ffffff';+ g.fillRect(0, 0, W, H);+ }+ function openFromComputer() {+ const inp = document.createElement('input');+ inp.type = 'file';+ inp.accept = 'image/*';+ inp.addEventListener('change', () => {+ const f = inp.files?.[0];+ if (f) confirmDiscard(() => loadBlob(f, { name: f.name }));+ });+ inp.click();+ }++ // ---- toolbar ----+ const btn = (cls, html, title, onClick) => {+ const b = h('button', cls, html);+ b.type = 'button';+ b.title = title;+ b.setAttribute('aria-label', title.replace(/ \(.*\)$/, ''));+ b.addEventListener('click', onClick);+ return b;+ };+ const bNew = btn('pt-ab', `${ACTION_ICONS.new}<span>New</span>`, 'New image (Ctrl+N)', newImage);+ const bOpen = btn('pt-ab', `${ACTION_ICONS.open}<span>Open</span>`, 'Open from this computer (Ctrl+O)', openFromComputer);+ const bSave = btn('pt-ab', `${ACTION_ICONS.save}<span>Save</span>`, 'Save (Ctrl+S)', save);+ const bSaveAs = btn('pt-ab', '<span>Save as</span>', 'Save as (Ctrl+Shift+S)', saveAs);+ const bExport = btn('pt-ab', `${ACTION_ICONS.download}<span>Export</span>`, 'Download a copy', exportDownload);+ const bUndo = btn('pt-ab icon', ACTION_ICONS.undo, 'Undo (Ctrl+Z)', undo);+ const bRedo = btn('pt-ab icon', ACTION_ICONS.redo, 'Redo (Ctrl+Y)', redo);+ const bCopy = btn('pt-ab icon', ACTION_ICONS.copy, 'Copy image (Ctrl+C)', copyImage);+ const bPaste = btn('pt-ab icon', ACTION_ICONS.paste, 'Paste image (Ctrl+V)', pasteImage);+ const bResize = btn('pt-ab', '<span>Canvas size</span>', 'Canvas size', resizeCanvas);+ const bClear = btn('pt-ab icon', ACTION_ICONS.clear, 'Clear canvas', clearAll);+ const sep = () => h('span', 'pt-sep');+ actions.append(bNew, bOpen, bSave, bSaveAs, bExport, sep(), bUndo, bRedo, sep(), bCopy, bPaste, sep(), bResize, bClear);++ const toolBtns = {};+ for (const [id, label, key, icon] of TOOLS) {+ const b = btn('pt-tool', icon, `${label} (${key})`, () => setTool(id));+ b.setAttribute('aria-pressed', 'false');+ toolBtns[id] = b;+ toolsRow.append(b);+ }+ function setTool(id) {+ if (id !== st.tool) st.prevTool = st.tool;+ if (textBox) commitText();+ st.tool = id;+ for (const [k, b] of Object.entries(toolBtns)) {+ b.classList.toggle('on', k === id);+ b.setAttribute('aria-pressed', String(k === id));+ }+ cv.style.cursor = id === 'picker' ? 'copy' : id === 'text' ? 'text' : 'crosshair';+ fillWrap.hidden = !['rect', 'ellipse'].includes(id);+ tolWrap.hidden = id !== 'fill';+ fontWrap.hidden = id !== 'text';+ sizeWrap.hidden = ['fill', 'picker'].includes(id);+ }++ const field = (label, input, cls = '') => {+ const w = h('label', `pt-field ${cls}`);+ w.append(h('span', '', label), input);+ return w;+ };+ const sizeRange = h('input');+ Object.assign(sizeRange, { type: 'range', min: '1', max: '80', value: String(st.size) });+ const sizeOut = h('output', '', String(st.size));+ const sizeWrap = field(+ 'Size',+ (() => {+ const d = h('span', 'pt-rng');+ d.append(sizeRange, sizeOut);+ return d;+ })(),+ );+ sizeRange.addEventListener('input', () => {+ st.size = Number(sizeRange.value);+ sizeOut.textContent = sizeRange.value;+ store.set('tws:paint:size', sizeRange.value);+ });+ const opRange = h('input');+ Object.assign(opRange, { type: 'range', min: '5', max: '100', value: '100' });+ const opOut = h('output', '', '100%');+ const opWrap = field(+ 'Opacity',+ (() => {+ const d = h('span', 'pt-rng');+ d.append(opRange, opOut);+ return d;+ })(),+ );+ opRange.addEventListener('input', () => {+ st.opacity = Number(opRange.value);+ opOut.textContent = `${opRange.value}%`;+ });+ const tolRange = h('input');+ Object.assign(tolRange, { type: 'range', min: '0', max: '128', value: String(st.tolerance) });+ const tolOut = h('output', '', String(st.tolerance));+ const tolWrap = field(+ 'Tolerance',+ (() => {+ const d = h('span', 'pt-rng');+ d.append(tolRange, tolOut);+ return d;+ })(),+ );+ tolRange.addEventListener('input', () => {+ st.tolerance = Number(tolRange.value);+ tolOut.textContent = tolRange.value;+ });+ const fillSel = h('select', 'pt-sel', '<option value="0">Outline</option><option value="1">Filled</option>');+ fillSel.addEventListener('change', () => (st.filled = fillSel.value === '1'));+ const fillWrap = field('Shape', fillSel);+ const fontSel = h('select', 'pt-sel', Object.keys(FONTS).map((f) => `<option>${f}</option>`).join(''));+ fontSel.addEventListener('change', () => (st.font = fontSel.value));+ const fontWrap = field('Font', fontSel);++ const colorIn = h('input', 'pt-color');+ colorIn.type = 'color';+ colorIn.value = st.color;+ colorIn.title = 'Custom colour';+ colorIn.setAttribute('aria-label', 'Custom colour');+ colorIn.addEventListener('input', () => setColor(colorIn.value));+ const swatches = h('div', 'pt-swatches');+ swatches.setAttribute('role', 'group');+ swatches.setAttribute('aria-label', 'Colour palette');+ for (const c of PALETTE) {+ const b = h('button', 'pt-sw');+ b.type = 'button';+ b.style.background = c;+ b.title = c;+ b.setAttribute('aria-label', `Colour ${c}`);+ b.addEventListener('click', () => setColor(c));+ swatches.append(b);+ }+ const cur = h('span', 'pt-cur');+ function setColor(c) {+ st.color = c;+ colorIn.value = c;+ cur.style.background = c;+ cur.title = `Current colour ${c}`;+ store.set('tws:paint:color', c);+ for (const b of swatches.children) b.classList.toggle('on', b.title === c);+ }+ optsRow.append(sizeWrap, opWrap, tolWrap, fillWrap, fontWrap, h('span', 'pt-grow'), cur, swatches, colorIn);++ // ---- zoom ----+ const zoomLabel = h('span', 'z', '100%');+ const zoomRange = h('input');+ Object.assign(zoomRange, { type: 'range', min: '10', max: '800', step: '5', value: '100' });+ zoomRange.setAttribute('aria-label', 'Zoom');+ const zOut = btn('pt-zb', '−', 'Zoom out (Ctrl+-)', () => setZoom(stepZoom(st.zoom, -1)));+ const zIn = btn('pt-zb', '+', 'Zoom in (Ctrl++)', () => setZoom(stepZoom(st.zoom, 1)));+ const zFit = btn('pt-zb', ACTION_ICONS.fit, 'Fit to window', () => fitView());+ zoomRange.addEventListener('input', () => setZoom(Number(zoomRange.value) / 100));+ zoomWrap.append(zFit, zOut, zoomRange, zIn, zoomLabel);+ function setZoom(z, anchor) {+ const old = st.zoom;+ st.zoom = clampZoom(z);+ const vr = viewport.getBoundingClientRect();+ const ax = anchor ? anchor.x - vr.left : vr.width / 2;+ const ay = anchor ? anchor.y - vr.top : vr.height / 2;+ const cx = (viewport.scrollLeft + ax) / old;+ const cy = (viewport.scrollTop + ay) / old;+ applyZoom();+ viewport.scrollLeft = cx * st.zoom - ax;+ viewport.scrollTop = cy * st.zoom - ay;+ if (textBox) cancelText();+ if (floating) drawFloat();+ }+ function fitView() {+ const r = viewport.getBoundingClientRect();+ st.zoom = fitZoom(W, H, Math.max(100, r.width - 40), Math.max(100, r.height - 40));+ applyZoom();+ }+ viewport.addEventListener(+ 'wheel',+ (e) => {+ if (!e.ctrlKey && !e.metaKey) return;+ e.preventDefault();+ setZoom(stepZoom(st.zoom, e.deltaY < 0 ? 1 : -1), { x: e.clientX, y: e.clientY });+ },+ { passive: false },+ );++ // ---- drop + keyboard ----+ viewport.addEventListener('dragover', (e) => {+ if ([...(e.dataTransfer?.types || [])].includes('Files')) {+ e.preventDefault();+ viewport.classList.add('drop');+ }+ });+ viewport.addEventListener('dragleave', () => viewport.classList.remove('drop'));+ viewport.addEventListener('drop', (e) => {+ viewport.classList.remove('drop');+ const f = [...(e.dataTransfer?.files || [])].find((x) => x.type.startsWith('image/'));+ if (!f) return;+ e.preventDefault();+ confirmDiscard(() => loadBlob(f, { name: f.name }));+ });+ root.addEventListener('keydown', (e) => {+ if (e.target.closest('textarea,input[type=number],input[type=text],.pt-in')) return;+ const mod = e.ctrlKey || e.metaKey;+ const k = e.key.toLowerCase();+ if (floating && (e.key === 'Enter' || e.key === 'Escape')) {+ e.preventDefault();+ return e.key === 'Enter' ? commitFloat() : cancelFloat();+ }+ if (mod) {+ if (k === 'z') (e.shiftKey ? redo : undo)();+ else if (k === 'y') redo();+ else if (k === 's') (e.shiftKey ? saveAs : save)();+ else if (k === 'o') openFromComputer();+ else if (k === 'n') newImage();+ else if (k === 'c' && !window.getSelection()?.toString()) copyImage();+ else if (k === '=' || k === '+') setZoom(stepZoom(st.zoom, 1));+ else if (k === '-') setZoom(stepZoom(st.zoom, -1));+ else if (k === '0') setZoom(1);+ else return;+ e.preventDefault();+ return;+ }+ if (e.target.closest('button') && (e.key === 'Enter' || e.key === ' ')) return;+ const hit = TOOLS.find(([, , key]) => key.toLowerCase() === k);+ if (hit) setTool(hit[0]);+ else if (k === '[') bump(-2);+ else if (k === ']') bump(2);+ else return;+ e.preventDefault();+ });+ function bump(d) {+ st.size = Math.max(1, Math.min(80, st.size + d));+ sizeRange.value = String(st.size);+ sizeOut.textContent = String(st.size);+ }+ const beforeUnload = (e) => {+ if (st.dirty) {+ e.preventDefault();+ e.returnValue = '';+ }+ };+ window.addEventListener('beforeunload', beforeUnload);++ function syncUi() {+ bUndo.disabled = !hist.canUndo;+ bRedo.disabled = !hist.canRedo;+ bSave.classList.toggle('dirty', st.dirty);+ }++ ctx.onArg((p) => {+ if (typeof p === 'string' && p) confirmDiscard(() => openPath(p));+ });++ // ---- start ----+ sizeCanvas(W, H, false);+ setColor(st.color);+ setTool('pen');+ syncUi();+ ctx.setTitle('Untitled - Paint');+ if (typeof ctx.arg === 'string' && ctx.arg) openPath(ctx.arg);+ else requestAnimationFrame(() => !disposed && fitView());+ root.focus({ preventScroll: true });++ return () => {+ disposed = true;+ loadToken++;+ window.removeEventListener('beforeunload', beforeUnload);+ };+}diff --git a/src/desktop/os/apps/perf-logic.js b/src/desktop/os/apps/perf-logic.jsnew file mode 100644index 000000000..73baaccc1--- /dev/null+++ b/src/desktop/os/apps/perf-logic.js@@ -0,0 +1,155 @@+// Pure maths and formatting for the Task Manager's Performance and Details tabs.++/** Fixed-capacity ring buffer of numbers (null marks a sample the source could not provide). */+export class RingBuffer {+ constructor(capacity = 60) {+ this.capacity = capacity;+ this.buf = new Array(capacity).fill(null);+ this.head = 0;+ this.size = 0;+ }+ push(v) {+ this.buf[this.head] = v;+ this.head = (this.head + 1) % this.capacity;+ if (this.size < this.capacity) this.size++;+ }+ /** Oldest to newest. */+ toArray() {+ const out = [];+ for (let i = 0; i < this.size; i++) out.push(this.buf[(this.head - this.size + i + this.capacity * 2) % this.capacity]);+ return out;+ }+ last() {+ return this.size ? this.buf[(this.head - 1 + this.capacity) % this.capacity] : null;+ }+ /** Max of the real (non-null) samples, or 0. */+ max() {+ return this.toArray().reduce((m, v) => (v != null && v > m ? v : m), 0);+ }+}++export function formatBytes(n) {+ if (n == null || !Number.isFinite(n)) return 'n/a';+ if (n < 1024) return `${Math.round(n)} B`;+ const u = ['KB', 'MB', 'GB', 'TB'];+ let i = -1;+ do {+ n /= 1024;+ i++;+ } while (n >= 1024 && i < u.length - 1);+ return `${n.toFixed(n < 10 ? 2 : n < 100 ? 1 : 0)} ${u[i]}`;+}++export function formatMs(ms) {+ if (ms == null || !Number.isFinite(ms)) return 'n/a';+ return ms < 1000 ? `${ms < 10 ? ms.toFixed(1) : Math.round(ms)} ms` : `${(ms / 1000).toFixed(2)} s`;+}++export const formatPct = (f) => (f == null || !Number.isFinite(f) ? 'n/a' : `${Math.round(f * 100)}%`);++export function formatDuration(ms) {+ const s = Math.floor(ms / 1000);+ const hh = Math.floor(s / 3600);+ const mm = Math.floor((s % 3600) / 60);+ const ss = s % 60;+ return hh ? `${hh}:${String(mm).padStart(2, '0')}:${String(ss).padStart(2, '0')}` : `${mm}:${String(ss).padStart(2, '0')}`;+}++/** Frames per second from requestAnimationFrame timestamps (ms) that fall in the last `windowMs`. */+export function fpsFromFrames(times, now, windowMs = 1000) {+ const recent = times.filter((t) => t > now - windowMs && t <= now);+ if (recent.length < 2) return null;+ const span = recent[recent.length - 1] - recent[0];+ return span > 0 ? ((recent.length - 1) * 1000) / span : null;+}++/** Fraction (0..1) of [t0, t1] covered by long tasks ({ startTime, duration }). Overlap is clipped. */+export function longTaskLoad(tasks, t0, t1) {+ const span = t1 - t0;+ if (span <= 0) return 0;+ let busy = 0;+ for (const t of tasks) {+ const a = Math.max(t.startTime, t0);+ const b = Math.min(t.startTime + t.duration, t1);+ if (b > a) busy += b - a;+ }+ return Math.min(1, busy / span);+}++/** Fraction (0..1) of an interval a timer probe arrived late: a busy main thread delays timers. */+export function driftLoad(expectedMs, actualMs) {+ if (expectedMs <= 0) return 0;+ return Math.min(1, Math.max(0, (actualMs - expectedMs) / expectedMs));+}++/** Main-thread load estimate: the larger of what long tasks and timer drift each show. */+export function mainThreadLoad({ tasks = [], t0, t1, expectedMs, actualMs }) {+ return Math.max(longTaskLoad(tasks, t0, t1), driftLoad(expectedMs, actualMs));+}++/** Split a total across windows by weight. Returns shares that sum to the total (or zeros when weights are zero). */+export function shareTotal(total, weights) {+ const sum = weights.reduce((a, b) => a + b, 0);+ if (!sum || total == null) return weights.map(() => 0);+ return weights.map((w) => (total * w) / sum);+}++/** Approximate relative weight of a window for the estimated-memory split: its pixel area, floor of one 100x100 area. */+export const windowWeight = (rect) => Math.max(10000, (rect?.w || 0) * (rect?.h || 0));++/** Aggregate resource-timing entries into counts, bytes and slowest. */+export function summarizeResources(entries, top = 8) {+ const byType = {};+ let transfer = 0;+ for (const e of entries) {+ const t = e.initiatorType || 'other';+ const row = (byType[t] ||= { type: t, count: 0, bytes: 0 });+ row.count++;+ row.bytes += e.transferSize || 0;+ transfer += e.transferSize || 0;+ }+ const slowest = [...entries]+ .sort((a, b) => b.duration - a.duration)+ .slice(0, top)+ .map((e) => ({ name: e.name, type: e.initiatorType || 'other', duration: e.duration, bytes: e.transferSize || 0 }));+ return { total: entries.length, transfer, byType: Object.values(byType).sort((a, b) => b.count - a.count), slowest };+}++/** Short display name for a resource URL. */+export function shortUrl(url, max = 56) {+ let s = String(url);+ try {+ const u = new URL(s);+ s = (u.origin === (typeof location !== 'undefined' ? location.origin : '') ? '' : u.host) + u.pathname + u.search;+ } catch {+ /* keep raw */+ }+ return s.length > max ? `${s.slice(0, max / 2 - 1)}...${s.slice(-(max / 2 - 2))}` : s;+}++/** Sort rows by key. dir 1 ascending, -1 descending; nulls always last. */+export function sortRows(rows, key, dir = 1) {+ return [...rows].sort((a, b) => {+ const x = a[key];+ const y = b[key];+ if (x == null && y == null) return 0;+ if (x == null) return 1;+ if (y == null) return -1;+ return (typeof x === 'string' ? x.localeCompare(y, undefined, { sensitivity: 'base' }) : x - y) * dir;+ });+}++/** Navigation timing milestones in ms from the navigation start. */+export function pageTiming(nav) {+ if (!nav) return null;+ const rel = (v) => (v > 0 ? v : null);+ return {+ dns: nav.domainLookupEnd - nav.domainLookupStart,+ connect: nav.connectEnd - nav.connectStart,+ ttfb: rel(nav.responseStart),+ domInteractive: rel(nav.domInteractive),+ domContentLoaded: rel(nav.domContentLoadedEventEnd),+ load: rel(nav.loadEventEnd),+ transferSize: nav.transferSize || 0,+ };+}diff --git a/src/desktop/os/apps/photos.css b/src/desktop/os/apps/photos.cssnew file mode 100644index 000000000..f65f29660--- /dev/null+++ b/src/desktop/os/apps/photos.css@@ -0,0 +1,365 @@+.napp-photos {+ height: 100%;+ min-height: 0;+}+.napp-photos .ph {+ position: relative;+ display: flex;+ flex-direction: column;+ height: 100%;+ min-height: 0;+ background: var(--card);+ color: var(--text);+ font-size: 13px;+ overflow: hidden;+ container-type: inline-size;+}+.napp-photos .ph button {+ font: inherit;+ color: inherit;+}++/* gallery */+.napp-photos .ph-head {+ display: flex;+ align-items: baseline;+ gap: 12px;+ padding: 16px 18px 8px;+}+.napp-photos .ph-head h2 {+ margin: 0;+ font-size: 20px;+ font-weight: 600;+}+.napp-photos .ph-sub {+ color: var(--text2);+}+.napp-photos .ph-grid {+ flex: 1;+ min-height: 0;+ overflow-y: auto;+ display: grid;+ grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));+ grid-auto-rows: 150px;+ gap: 6px;+ padding: 8px 18px 18px;+}+.napp-photos .ph-cell {+ position: relative;+ padding: 0;+ border: 1px solid transparent;+ border-radius: 8px;+ background: var(--hover);+ overflow: hidden;+ content-visibility: auto;+ contain-intrinsic-size: 150px 150px;+}+.napp-photos .ph-cell:hover,+.napp-photos .ph-cell:focus-visible {+ border-color: var(--accent);+ outline: 0;+}+.napp-photos .ph-cell:active {+ transform: scale(0.985);+}+.napp-photos .ph-cellimg {+ position: absolute;+ inset: 0;+}+.napp-photos .ph-cellimg img,+.napp-photos .ph-thimg img {+ width: 100%;+ height: 100%;+ object-fit: cover;+ display: block;+}+.napp-photos .ph-cellname {+ position: absolute;+ left: 0;+ right: 0;+ bottom: 0;+ padding: 18px 8px 6px;+ text-align: left;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ font-size: 12px;+ color: #fff;+ background: linear-gradient(transparent, rgba(0, 0, 0, 0.65));+ opacity: 0;+ transition: opacity 0.12s;+}+.napp-photos .ph-cell:hover .ph-cellname,+.napp-photos .ph-cell:focus-visible .ph-cellname {+ opacity: 1;+}+.napp-photos .ph-sk {+ border-radius: 8px;+ background: linear-gradient(90deg, var(--hover) 25%, var(--hover-b, var(--hover)) 50%, var(--hover) 75%);+ background-size: 200% 100%;+ animation: ph-shim 1.2s linear infinite;+}+@keyframes ph-shim {+ to {+ background-position: -200% 0;+ }+}++/* states */+.napp-photos .ph-empty {+ flex: 1;+ display: flex;+ flex-direction: column;+ align-items: center;+ justify-content: center;+ gap: 6px;+ padding: 24px;+ text-align: center;+ color: var(--text2);+}+.napp-photos .ph-empty h3 {+ margin: 8px 0 0;+ font-size: 16px;+ font-weight: 600;+ color: var(--text);+}+.napp-photos .ph-empty p {+ margin: 0;+ max-width: 400px;+}+.napp-photos .ph-empty.err svg {+ color: #e5484d;+}+.napp-photos .ph-empty-act {+ display: flex;+ gap: 8px;+ margin-top: 14px;+}+.napp-photos .ph-pill {+ height: 32px;+ padding: 0 16px;+ border: 1px solid var(--bd);+ border-radius: var(--siz-radius3, 6px);+ background: var(--hover);+}+.napp-photos .ph-pill:hover {+ background: var(--hover-b, var(--hover));+}+.napp-photos .ph-pill.primary {+ background: var(--accent);+ border-color: transparent;+ color: #fff;+}++/* viewer */+.napp-photos .ph-bar {+ display: flex;+ align-items: center;+ gap: 2px;+ padding: 6px 8px;+ border-bottom: 1px solid var(--bd);+ overflow-x: auto;+ scrollbar-width: none;+}+.napp-photos .ph-title {+ display: flex;+ flex-direction: column;+ min-width: 0;+ max-width: 280px;+ margin-left: 6px;+ line-height: 1.25;+}+.napp-photos .ph-title b {+ font-weight: 600;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}+.napp-photos .ph-title span {+ font-size: 11px;+ color: var(--text2);+ white-space: pre;+}+.napp-photos .ph-grow {+ flex: 1;+ min-width: 8px;+}+.napp-photos .ph-b {+ display: grid;+ place-items: center;+ flex: none;+ width: 32px;+ height: 32px;+ border-radius: var(--siz-radius3, 6px);+}+.napp-photos .ph-b:hover {+ background: var(--hover);+}+.napp-photos .ph-b:active {+ background: var(--hover-b, var(--hover));+}+.napp-photos .ph-b[aria-pressed='true'] {+ background: color-mix(in srgb, var(--accent) 28%, transparent);+}+.napp-photos .ph-b.danger:hover {+ color: #e5484d;+}+.napp-photos .ph-zoom {+ flex: none;+ min-width: 52px;+ height: 28px;+ border-radius: 6px;+ font-variant-numeric: tabular-nums;+}+.napp-photos .ph-zoom:hover {+ background: var(--hover);+}+.napp-photos .ph-sep {+ width: 1px;+ height: 18px;+ margin: 0 5px;+ background: var(--bd);+}+.napp-photos .ph-stage {+ position: relative;+ flex: 1;+ min-height: 0;+ overflow: hidden;+ outline: 0;+ background:+ conic-gradient(var(--hover-half, #7f7f7f20) 25%, transparent 0 50%, var(--hover-half, #7f7f7f20) 0 75%, transparent 0) 0 0 / 24px 24px,+ var(--bg);+ cursor: default;+ touch-action: none;+}+.napp-photos .ph-stage.pannable {+ cursor: grab;+}+.napp-photos .ph-stage.dragging {+ cursor: grabbing;+}+.napp-photos .ph-img {+ position: absolute;+ left: 50%;+ top: 50%;+ max-width: none;+ user-select: none;+ -webkit-user-drag: none;+ transform-origin: center;+ image-rendering: auto;+ opacity: 0;+}+.napp-photos .ph-stage:not(.loading) .ph-img {+ opacity: 1;+}+.napp-photos .ph-img.turning {+ transition: transform 0.18s ease;+}+@media (prefers-reduced-motion: reduce) {+ .napp-photos .ph-img.turning {+ transition: none;+ }+}+.napp-photos .ph-spin {+ position: absolute;+ left: 50%;+ top: 50%;+ width: 28px;+ height: 28px;+ margin: -14px 0 0 -14px;+ border: 3px solid var(--bd);+ border-top-color: var(--accent);+ border-radius: 50%;+ animation: ph-rot 0.8s linear infinite;+}+.napp-photos .ph-stage:not(.loading) .ph-spin {+ display: none;+}+@keyframes ph-rot {+ to {+ transform: rotate(360deg);+ }+}+.napp-photos .ph-nav {+ position: absolute;+ top: 50%;+ display: grid;+ place-items: center;+ width: 40px;+ height: 64px;+ margin-top: -32px;+ border-radius: 8px;+ background: var(--bg70, rgba(0, 0, 0, 0.5));+ color: var(--text);+ opacity: 0;+ transition: opacity 0.15s;+}+.napp-photos .ph-nav[hidden] {+ display: none;+}+.napp-photos .ph-nav.prev {+ left: 10px;+}+.napp-photos .ph-nav.next {+ right: 10px;+}+.napp-photos .ph-stage:hover .ph-nav,+.napp-photos .ph-nav:focus-visible {+ opacity: 1;+}+.napp-photos .ph-nav:hover {+ background: var(--accent);+ color: #fff;+}+.napp-photos .ph-strip {+ flex: none;+ display: flex;+ gap: 6px;+ height: 74px;+ padding: 8px 10px;+ overflow-x: auto;+ border-top: 1px solid var(--bd);+ box-sizing: border-box;+}+.napp-photos .ph-strip[hidden] {+ display: none;+}+.napp-photos .ph-th {+ flex: none;+ width: 56px;+ height: 56px;+ padding: 0;+ border: 2px solid transparent;+ border-radius: 7px;+ overflow: hidden;+ background: var(--hover);+ opacity: 0.75;+}+.napp-photos .ph-th:hover {+ opacity: 1;+}+.napp-photos .ph-th.on {+ border-color: var(--accent);+ opacity: 1;+}+.napp-photos .ph-th:focus-visible {+ outline: 2px solid var(--accent);+ outline-offset: 1px;+}+.napp-photos .ph-thimg {+ display: block;+ width: 100%;+ height: 100%;+}+.napp-photos .broken {+ background: var(--hover-b, var(--hover));+}++/* slideshow / fullscreen: chrome fades away */+.napp-photos .ph.sliding .ph-bar,+.napp-photos .ph.sliding .ph-strip {+ display: none;+}+.napp-photos .ph.sliding .ph-stage {+ background: #000;+}diff --git a/src/desktop/os/apps/photos.js b/src/desktop/os/apps/photos.jsnew file mode 100644index 000000000..2f229623d--- /dev/null+++ b/src/desktop/os/apps/photos.js@@ -0,0 +1,512 @@+// Photos: picture viewer and gallery over the virtual file system (../fs.js).+import './photos.css';+import * as fs from '../fs.js';++/* ---------- pure helpers (unit tested) ---------- */++export const isImageName = (name) => fs.kindOf(String(name)) === 'image';++/** Image files only, newest first (ties broken by name). */+export function newestFirst(nodes) {+ return nodes+ .filter((n) => n.type === 'file' && isImageName(n.name))+ .sort((a, b) => (b.mtime || 0) - (a.mtime || 0) || a.name.localeCompare(b.name, undefined, { numeric: true }));+}++/** Image files in natural name order, for the filmstrip. */+export function byName(nodes) {+ return nodes+ .filter((n) => n.type === 'file' && isImageName(n.name))+ .sort((a, b) => a.name.localeCompare(b.name, undefined, { numeric: true, sensitivity: 'base' }));+}++/** Step through `count` items, wrapping around. */+export const stepIndex = (i, dir, count) => (count ? (((i + dir) % count) + count) % count : -1);++export const MIN_ZOOM = 0.05;+export const MAX_ZOOM = 16;+export const clampZoom = (z) => Math.max(MIN_ZOOM, Math.min(MAX_ZOOM, z));++/** Dimensions after a rotation in degrees (multiples of 90 swap width and height). */+export function rotatedSize(w, h, deg) {+ return Math.round(Math.abs(deg) / 90) % 2 ? { w: h, h: w } : { w, h };+}++/** Scale that fits the whole picture in the box. Never enlarges past 100%. */+export function fitScale(imgW, imgH, boxW, boxH, deg = 0) {+ const r = rotatedSize(imgW, imgH, deg);+ if (!r.w || !r.h || boxW <= 0 || boxH <= 0) return 1;+ return Math.min(1, boxW / r.w, boxH / r.h);+}++/** Keep at least part of the picture on screen while panning. */+export function clampPan(t, shownSize, boxSize, keep = 48) {+ const max = Math.max(0, (shownSize + boxSize) / 2 - keep);+ return Math.max(-max, Math.min(max, t));+}++/**+ * Zoom about a point. `cx`/`cy` are the cursor offsets from the box centre,+ * `v` is { s, x, y }. Returns the new { s, x, y } keeping the point fixed.+ */+export function zoomAt(v, factor, cx, cy) {+ const s = clampZoom(v.s * factor);+ const k = s / v.s;+ return { s, x: cx - (cx - v.x) * k, y: cy - (cy - v.y) * k };+}++/** "3 of 12" label; empty when nothing is open. */+export const positionLabel = (i, n) => (i >= 0 && n > 0 ? `${i + 1} of ${n}` : '');++/* ---------- the app ---------- */++const GLYPHS = {+ 'ph-left': '<path d="M15 5l-7 7 7 7"/>',+ 'ph-right': '<path d="M9 5l7 7-7 7"/>',+ 'ph-zin': '<circle cx="11" cy="11" r="7"/><path d="m16 16 5 5M11 8v6M8 11h6"/>',+ 'ph-zout': '<circle cx="11" cy="11" r="7"/><path d="m16 16 5 5M8 11h6"/>',+ 'ph-rotl': '<path d="M4 9a8 8 0 1 1-1 4"/><path d="M4 3v6h6"/>',+ 'ph-rotr': '<path d="M20 9a8 8 0 1 0 1 4"/><path d="M20 3v6h-6"/>',+ 'ph-fit': '<path d="M4 9V4h5M20 9V4h-5M4 15v5h5M20 15v5h-5"/>',+ 'ph-one': '<rect x="3" y="5" width="18" height="14" rx="2"/><path d="M10 10l2-1.5V15"/>',+ 'ph-back': '<rect x="3" y="3" width="7.5" height="7.5" rx="1.5"/><rect x="13.5" y="3" width="7.5" height="7.5" rx="1.5"/><rect x="3" y="13.5" width="7.5" height="7.5" rx="1.5"/><rect x="13.5" y="13.5" width="7.5" height="7.5" rx="1.5"/>',+};++export function mount(host, ctx) {+ for (const [k, v] of Object.entries(GLYPHS)) ctx.registerGlyph(k, v);+ const { h, esc, icon } = ctx;+ const SLIDE_MS = 3500;++ const root = h('div', 'ph');+ host.append(root);+ let dead = false;+ const urls = new Map(); // path -> { mtime, url } for thumbnails+ let io = null;++ // viewer state+ const v = { path: null, siblings: [], url: null, nw: 0, nh: 0, s: 1, x: 0, y: 0, rot: 0, fit: true, failed: false };+ let slide = null;+ let stage = null;+ let imgEl = null;+ let ro = null;+ const err = (e) => ctx.toast(e?.message || 'Something went wrong');++ /* --- thumbnails --- */+ async function thumbUrl(node) {+ let t = urls.get(node.path);+ if (!t || t.mtime !== node.mtime) {+ if (t) URL.revokeObjectURL(t.url);+ const url = await fs.urlFor(node.path).catch(() => null);+ if (!url) return null;+ t = { mtime: node.mtime, url };+ urls.set(node.path, t);+ }+ return t.url;+ }+ function lazyThumbs(container, nodes) {+ io?.disconnect();+ const byPath = new Map(nodes.map((n) => [n.path, n]));+ io = new IntersectionObserver(+ (entries) => {+ for (const e of entries) {+ if (!e.isIntersecting) continue;+ io.unobserve(e.target);+ const node = byPath.get(e.target.dataset.path);+ if (!node) continue;+ thumbUrl(node).then((u) => {+ if (!u || dead || !e.target.isConnected) return;+ const img = new Image();+ img.alt = '';+ img.decoding = 'async';+ img.onload = () => e.target.replaceChildren(img);+ img.onerror = () => e.target.classList.add('broken');+ img.src = u;+ });+ }+ },+ { rootMargin: '300px' },+ );+ for (const el of container.querySelectorAll('[data-path]')) io.observe(el);+ }++ /* --- gallery --- */+ async function showGallery() {+ stopSlide();+ leaveViewer();+ ctx.setTitle('Photos');+ root.className = 'ph ph-gallery';+ root.innerHTML = `<div class="ph-head"><h2>Photos</h2><span class="ph-sub" aria-live="polite"></span></div><div class="ph-grid" aria-busy="true">${'<i class="ph-sk"></i>'.repeat(12)}</div>`;+ let nodes = [];+ try {+ const [a, b] = await Promise.all([fs.walk('/Pictures'), fs.walk('/Downloads')]);+ nodes = newestFirst([...a, ...b]);+ } catch (e) {+ if (dead) return;+ root.querySelector('.ph-grid').outerHTML = `<div class="ph-empty err">${icon('close', 44)}<h3>Your pictures could not be loaded</h3><p>${esc(e?.message || 'Storage is unavailable.')}</p><div class="ph-empty-act"><button class="ph-pill primary" data-act="retry">Try again</button></div></div>`;+ return;+ }+ if (dead || v.path) return;+ const sub = root.querySelector('.ph-sub');+ if (!nodes.length) {+ root.querySelector('.ph-grid').outerHTML = `<div class="ph-empty">${icon('image', 44)}<h3>No pictures yet</h3><p>Take a photo with Camera, or upload pictures in File Explorer. Anything saved in Pictures or Downloads shows up here.</p><div class="ph-empty-act"><button class="ph-pill primary" data-act="camera">Open Camera</button><button class="ph-pill" data-act="explorer">Open File Explorer</button></div></div>`;+ sub.textContent = '';+ return;+ }+ sub.textContent = `${nodes.length} ${nodes.length === 1 ? 'picture' : 'pictures'}`;+ const grid = root.querySelector('.ph-grid');+ grid.removeAttribute('aria-busy');+ grid.innerHTML = nodes.map((n) => `<button class="ph-cell" data-path="${esc(n.path)}" title="${esc(n.name)}" aria-label="${esc(n.name)}"><span class="ph-cellimg" data-path="${esc(n.path)}"></span><span class="ph-cellname">${esc(n.name)}</span></button>`).join('');+ lazyThumbs(grid, nodes);+ grid.querySelector('.ph-cell')?.focus({ preventScroll: true });+ }++ /* --- viewer --- */+ function leaveViewer() {+ if (v.url) URL.revokeObjectURL(v.url);+ v.url = null;+ v.path = null;+ ro?.disconnect();+ ro = null;+ stage = imgEl = null;+ }++ async function openImage(path) {+ const node = await fs.stat(path).catch(() => null);+ if (!node || node.type !== 'file' || !isImageName(node.name)) {+ ctx.toast(node ? `${node.name} is not a picture` : 'That picture no longer exists');+ return v.path ? null : showGallery();+ }+ const dir = fs.parentOf(path);+ v.siblings = byName(await fs.list(dir));+ leaveViewer();+ v.path = path;+ v.rot = 0;+ v.fit = true;+ v.failed = false;+ v.nw = v.nh = 0;+ ctx.setTitle(node.name);+ buildViewer(node);+ const url = await fs.urlFor(path);+ if (dead || v.path !== path) {+ if (url) URL.revokeObjectURL(url);+ return;+ }+ if (!url) return failView('This picture could not be read from storage.');+ v.url = url;+ imgEl.onload = () => {+ v.nw = imgEl.naturalWidth;+ v.nh = imgEl.naturalHeight;+ stage.classList.remove('loading');+ fitView();+ renderInfo();+ };+ imgEl.onerror = () => failView("This picture can't be displayed. The file may be damaged or in a format the browser does not support.");+ imgEl.src = url;+ }++ function failView(msg) {+ v.failed = true;+ if (!stage) return;+ stage.classList.remove('loading');+ stage.innerHTML = `<div class="ph-empty err">${icon('image', 44)}<h3>Can’t show this picture</h3><p>${esc(msg)}</p></div>`;+ imgEl = null;+ }++ function buildViewer(node) {+ root.className = `ph ph-viewer${slide != null ? ' sliding' : ''}`;+ root.innerHTML = `+ <div class="ph-bar" role="toolbar" aria-label="Photo tools">+ <button class="ph-b" data-act="gallery" title="Back to gallery (Esc)" aria-label="Back to gallery">${icon('ph-back', 17)}</button>+ <div class="ph-title"><b></b><span></span></div>+ <span class="ph-grow"></span>+ <button class="ph-b" data-act="zout" title="Zoom out (-)" aria-label="Zoom out">${icon('ph-zout', 17)}</button>+ <button class="ph-zoom" data-act="fit" title="Fit to window (0)" aria-live="polite">100%</button>+ <button class="ph-b" data-act="zin" title="Zoom in (+)" aria-label="Zoom in">${icon('ph-zin', 17)}</button>+ <button class="ph-b" data-act="actual" title="Actual size (1)" aria-label="Actual size">${icon('ph-one', 17)}</button>+ <button class="ph-b" data-act="rotl" title="Rotate left (Shift+R)" aria-label="Rotate left">${icon('ph-rotl', 17)}</button>+ <button class="ph-b" data-act="rotr" title="Rotate right (R)" aria-label="Rotate right">${icon('ph-rotr', 17)}</button>+ <i class="ph-sep"></i>+ <button class="ph-b" data-act="slide" title="Slideshow (F5)" aria-label="Start slideshow" aria-pressed="false">${icon('play', 17)}</button>+ <button class="ph-b" data-act="paint" title="Edit in Paint" aria-label="Edit in Paint">${icon('paint', 17)}</button>+ <button class="ph-b" data-act="download" title="Download" aria-label="Download">${icon('download', 17)}</button>+ <button class="ph-b danger" data-act="delete" title="Delete (Del)" aria-label="Delete">${icon('trash', 17)}</button>+ </div>+ <div class="ph-stage loading" tabindex="0" aria-label="Picture"><img class="ph-img" alt="${esc(node.name)}" draggable="false" /><div class="ph-spin" aria-label="Loading picture"></div>+ <button class="ph-nav prev" data-act="prev" aria-label="Previous picture">${icon('ph-left', 24)}</button>+ <button class="ph-nav next" data-act="next" aria-label="Next picture">${icon('ph-right', 24)}</button>+ </div>+ <div class="ph-strip" role="listbox" aria-label="Pictures in this folder"></div>`;+ stage = root.querySelector('.ph-stage');+ imgEl = root.querySelector('.ph-img');+ ro = new ResizeObserver(() => v.fit && fitView());+ ro.observe(stage);+ attachPanZoom();+ renderStrip();+ renderInfo();+ stage.focus({ preventScroll: true });+ }++ function renderStrip() {+ const strip = root.querySelector('.ph-strip');+ if (!strip) return;+ strip.hidden = v.siblings.length < 2;+ strip.innerHTML = v.siblings.map((n) => `<button class="ph-th${n.path === v.path ? ' on' : ''}" role="option" aria-selected="${n.path === v.path}" data-open="${esc(n.path)}" title="${esc(n.name)}"><span class="ph-thimg" data-path="${esc(n.path)}"></span></button>`).join('');+ lazyThumbs(strip, v.siblings);+ strip.querySelector('.on')?.scrollIntoView({ inline: 'center', block: 'nearest' });+ }++ function renderInfo() {+ if (!v.path) return;+ const i = v.siblings.findIndex((n) => n.path === v.path);+ const dims = v.nw ? `${v.nw} × ${v.nh}` : '';+ root.querySelector('.ph-title b').textContent = fs.nameOf(v.path);+ root.querySelector('.ph-title span').textContent = [positionLabel(i, v.siblings.length), dims].filter(Boolean).join(' ');+ const multi = v.siblings.length > 1;+ root.querySelectorAll('.ph-nav').forEach((b) => (b.hidden = !multi));+ const z = root.querySelector('.ph-zoom');+ if (z) z.textContent = `${Math.round(v.s * 100)}%`;+ }++ function applyTransform() {+ if (!imgEl) return;+ const r = rotatedSize(v.nw, v.nh, v.rot);+ const box = stage.getBoundingClientRect();+ v.x = clampPan(v.x, r.w * v.s, box.width);+ v.y = clampPan(v.y, r.h * v.s, box.height);+ imgEl.style.transform = `translate(calc(-50% + ${v.x}px), calc(-50% + ${v.y}px)) rotate(${v.rot}deg) scale(${v.s})`;+ stage.classList.toggle('pannable', r.w * v.s > box.width || r.h * v.s > box.height);+ const z = root.querySelector('.ph-zoom');+ if (z) z.textContent = `${Math.round(v.s * 100)}%`;+ }+ function fitView() {+ if (!imgEl || !v.nw) return;+ const box = stage.getBoundingClientRect();+ v.s = fitScale(v.nw, v.nh, box.width, box.height, v.rot);+ v.x = v.y = 0;+ v.fit = true;+ applyTransform();+ }+ function zoomBy(factor, clientX, clientY) {+ if (!imgEl || !v.nw) return;+ const box = stage.getBoundingClientRect();+ const cx = clientX == null ? 0 : clientX - (box.left + box.width / 2);+ const cy = clientY == null ? 0 : clientY - (box.top + box.height / 2);+ Object.assign(v, zoomAt(v, factor, cx, cy));+ v.fit = false;+ applyTransform();+ }+ function actualSize() {+ if (!imgEl || !v.nw) return;+ v.s = 1;+ v.x = v.y = 0;+ v.fit = false;+ applyTransform();+ }+ function rotate(deg) {+ if (!imgEl || !v.nw) return;+ v.rot = (v.rot + deg + 360) % 360;+ imgEl.classList.add('turning');+ fitView();+ }++ function attachPanZoom() {+ let drag = null;+ stage.addEventListener('wheel', (e) => {+ if (!imgEl) return;+ e.preventDefault();+ zoomBy(Math.exp(-e.deltaY * (e.ctrlKey ? 0.01 : 0.0015)), e.clientX, e.clientY);+ }, { passive: false });+ stage.addEventListener('pointerdown', (e) => {+ if (e.button !== 0 || e.target.closest('.ph-nav') || !imgEl) return;+ drag = { id: e.pointerId, px: e.clientX, py: e.clientY, x: v.x, y: v.y };+ stage.setPointerCapture(e.pointerId);+ stage.classList.add('dragging');+ imgEl.classList.remove('turning');+ });+ stage.addEventListener('pointermove', (e) => {+ if (!drag || drag.id !== e.pointerId) return;+ v.x = drag.x + e.clientX - drag.px;+ v.y = drag.y + e.clientY - drag.py;+ v.fit = false;+ applyTransform();+ });+ const end = (e) => {+ if (drag && drag.id === e.pointerId) {+ drag = null;+ stage.classList.remove('dragging');+ }+ };+ stage.addEventListener('pointerup', end);+ stage.addEventListener('pointercancel', end);+ stage.addEventListener('dblclick', (e) => {+ if (e.target.closest('.ph-nav') || !imgEl) return;+ const r = Math.abs(v.s - 1) < 0.01;+ if (r) fitView();+ else {+ const f = 1 / v.s;+ zoomBy(f, e.clientX, e.clientY);+ }+ });+ }++ /* --- navigation, slideshow, actions --- */+ function go(dir) {+ const i = v.siblings.findIndex((n) => n.path === v.path);+ const j = stepIndex(i, dir, v.siblings.length);+ if (j >= 0 && j !== i) openImage(v.siblings[j].path);+ }+ function startSlide() {+ if (v.siblings.length < 2) return ctx.toast('Add more pictures to this folder to run a slideshow');+ slide = setInterval(() => go(1), SLIDE_MS);+ root.classList.add('sliding');+ root.querySelector('[data-act="slide"]')?.setAttribute('aria-pressed', 'true');+ root.requestFullscreen?.().catch(() => {});+ }+ function stopSlide() {+ if (slide == null) return;+ clearInterval(slide);+ slide = null;+ root.classList.remove('sliding');+ root.querySelector('[data-act="slide"]')?.setAttribute('aria-pressed', 'false');+ if (document.fullscreenElement === root) document.exitFullscreen?.().catch(() => {});+ }++ async function removeCurrent() {+ const path = v.path;+ if (!path) return;+ const i = v.siblings.findIndex((n) => n.path === path);+ try {+ await fs.remove(path);+ } catch (e) {+ return err(e);+ }+ ctx.toast(`Moved ${fs.nameOf(path)} to the Recycle Bin`);+ const rest = v.siblings.filter((n) => n.path !== path);+ if (!rest.length) return showGallery();+ openImage(rest[Math.min(i, rest.length - 1)].path);+ }+ async function download() {+ if (!v.path) return;+ try {+ const f = await fs.read(v.path);+ if (!f) throw new Error('That picture no longer exists');+ const url = URL.createObjectURL(f.blob);+ const a = h('a');+ a.href = url;+ a.download = fs.nameOf(v.path);+ root.append(a);+ a.click();+ a.remove();+ setTimeout(() => URL.revokeObjectURL(url), 4000);+ } catch (e) {+ err(e);+ }+ }++ const actions = {+ gallery: showGallery,+ retry: showGallery,+ camera: () => ctx.launchId('camera'),+ explorer: () => ctx.launchId('files', { arg: '/Pictures' }),+ prev: () => go(-1),+ next: () => go(1),+ zin: () => zoomBy(1.25),+ zout: () => zoomBy(0.8),+ fit: fitView,+ actual: actualSize,+ rotl: () => rotate(-90),+ rotr: () => rotate(90),+ slide: () => (slide == null ? startSlide() : stopSlide()),+ paint: () => v.path && ctx.launchId('paint', { arg: v.path }),+ download,+ delete: removeCurrent,+ };++ root.addEventListener('click', (e) => {+ const a = e.target.closest('[data-act]');+ if (a) {+ if (a.dataset.act === 'next' || a.dataset.act === 'prev') stopSlide();+ return actions[a.dataset.act]?.();+ }+ if (slide != null && e.target.closest('.ph-stage')) return stopSlide();+ const o = e.target.closest('[data-open]');+ if (o) {+ stopSlide();+ return openImage(o.dataset.open);+ }+ const cell = e.target.closest('.ph-cell');+ if (cell) openImage(cell.dataset.path);+ });+ root.addEventListener('keydown', (e) => {+ if (!v.path) return;+ if (e.ctrlKey || e.metaKey || e.altKey) return;+ const k = e.key;+ const hit = (fn) => (e.preventDefault(), fn());+ if (k === 'ArrowLeft') return hit(() => (stopSlide(), go(-1)));+ if (k === 'ArrowRight') return hit(() => (stopSlide(), go(1)));+ if (k === '+' || k === '=') return hit(() => zoomBy(1.25));+ if (k === '-' || k === '_') return hit(() => zoomBy(0.8));+ if (k === '0') return hit(fitView);+ if (k === '1') return hit(actualSize);+ if (k === 'r') return hit(() => rotate(90));+ if (k === 'R') return hit(() => rotate(-90));+ if (k === 'F5') return hit(actions.slide);+ if (k === 'Delete') return hit(removeCurrent);+ if (k === 'Home') return hit(() => v.siblings[0] && openImage(v.siblings[0].path));+ if (k === 'End') return hit(() => v.siblings.length && openImage(v.siblings[v.siblings.length - 1].path));+ if (k === 'Escape') return hit(() => (slide != null ? stopSlide() : showGallery()));+ const pan = { ArrowUp: [0, 60], ArrowDown: [0, -60] }[k];+ if (pan && !v.fit) hit(() => ((v.y += pan[1]), applyTransform()));+ });+ const onFs = () => {+ if (!document.fullscreenElement && slide != null) stopSlide();+ };+ document.addEventListener('fullscreenchange', onFs);++ /* --- live refresh --- */+ let refreshTimer = 0;+ const unsub = fs.subscribe(() => {+ clearTimeout(refreshTimer);+ refreshTimer = setTimeout(async () => {+ if (dead) return;+ if (!v.path) {+ if (root.classList.contains('ph-gallery')) showGallery();+ return;+ }+ const still = await fs.stat(v.path).catch(() => null);+ if (!still) {+ const rest = v.siblings.filter((n) => n.path !== v.path);+ return rest.length ? openImage(rest[0].path) : showGallery();+ }+ v.siblings = byName(await fs.list(fs.parentOf(v.path)));+ renderStrip();+ renderInfo();+ }, 120);+ });++ /* --- launch --- */+ async function applyArg(arg) {+ if (typeof arg === 'string' && arg) {+ const p = fs.normalize(arg);+ const node = await fs.stat(p).catch(() => null);+ if (node?.type === 'file') return openImage(p);+ if (!node) ctx.toast(`${arg} does not exist`);+ }+ return showGallery();+ }+ ctx.onArg(applyArg);+ applyArg(ctx.arg);++ return () => {+ dead = true;+ stopSlide();+ clearTimeout(refreshTimer);+ unsub();+ io?.disconnect();+ ro?.disconnect();+ document.removeEventListener('fullscreenchange', onFs);+ if (v.url) URL.revokeObjectURL(v.url);+ for (const t of urls.values()) URL.revokeObjectURL(t.url);+ urls.clear();+ };+}diff --git a/src/desktop/os/apps/playlist-logic.js b/src/desktop/os/apps/playlist-logic.jsnew file mode 100644index 000000000..eb741c69a--- /dev/null+++ b/src/desktop/os/apps/playlist-logic.js@@ -0,0 +1,92 @@+// Pure helpers for the Media Player: queue order, shuffle, repeat, time+// formatting and the per-file resume position rules.++const AUDIO = ['mp3', 'wav', 'ogg', 'm4a', 'flac', 'weba', 'aac', 'opus'];+const VIDEO = ['mp4', 'webm', 'mov', 'mkv', 'm4v', 'ogv'];++const ext = (name) => {+ const i = String(name).lastIndexOf('.');+ return i > 0 ? name.slice(i + 1).toLowerCase() : '';+};++/** 'audio' | 'video' | null, from a file name and an optional mime type. */+export function mediaKind(name, mime = '') {+ if (mime.startsWith('audio/')) return 'audio';+ if (mime.startsWith('video/')) return 'video';+ const e = ext(name);+ if (AUDIO.includes(e)) return 'audio';+ if (VIDEO.includes(e)) return 'video';+ return null;+}++export const titleFromName = (name) => String(name).replace(/\.[^.]+$/, '').replace(/[_]+/g, ' ').trim() || String(name);++/** "3:07", "1:02:09"; "0:00" for anything not finite. */+export function formatTime(sec) {+ if (!Number.isFinite(sec) || sec < 0) return '0:00';+ const s = Math.floor(sec);+ const h = Math.floor(s / 3600);+ const m = Math.floor((s % 3600) / 60);+ const r = String(s % 60).padStart(2, '0');+ return h ? `${h}:${String(m).padStart(2, '0')}:${r}` : `${m}:${r}`;+}++export const SPEEDS = [0.5, 0.75, 1, 1.25, 1.5, 2];+export const clamp = (v, lo, hi) => Math.min(hi, Math.max(lo, v));++/** A play order over `n` items. Shuffle keeps `current` first so the playing track does not jump. */+export function buildOrder(n, { shuffle = false, current = 0, rng = Math.random } = {}) {+ const idx = Array.from({ length: n }, (_, i) => i);+ if (!shuffle || n < 2) return idx;+ const rest = idx.filter((i) => i !== current);+ for (let i = rest.length - 1; i > 0; i--) {+ const j = Math.floor(rng() * (i + 1));+ [rest[i], rest[j]] = [rest[j], rest[i]];+ }+ return current >= 0 && current < n ? [current, ...rest] : rest;+}++/**+ * The item index to play after `current`, or null at the end of the queue.+ * repeat: 'off' | 'all' | 'one'. `auto` is true when the track ended by itself+ * (repeat 'one' only replays on auto-advance; the Next button still moves on).+ */+export function nextIndex(order, current, { repeat = 'off', auto = false } = {}) {+ if (!order.length) return null;+ if (auto && repeat === 'one') return current;+ const pos = order.indexOf(current);+ if (pos < 0) return order[0];+ if (pos + 1 < order.length) return order[pos + 1];+ return repeat === 'all' || repeat === 'one' ? order[0] : null;+}++export function prevIndex(order, current, { repeat = 'off' } = {}) {+ if (!order.length) return null;+ const pos = order.indexOf(current);+ if (pos < 0) return order[0];+ if (pos > 0) return order[pos - 1];+ return repeat === 'all' ? order[order.length - 1] : order[0];+}++/** Library entries (audio and video only) from file-system nodes, grouped Music then Videos, natural order. */+export function buildLibrary(nodes) {+ return nodes+ .filter((n) => n.type === 'file' && mediaKind(n.name, n.mime))+ .map((n) => ({ id: n.path, path: n.path, name: n.name, kind: mediaKind(n.name, n.mime), size: n.size }))+ .sort((a, b) => (a.kind === b.kind ? a.name.localeCompare(b.name, undefined, { numeric: true, sensitivity: 'base' }) : a.kind === 'audio' ? -1 : 1));+}++/** Should the position be remembered? Not for the first seconds or the last few, and not for unknown length. */+export function shouldRemember(pos, duration) {+ return Number.isFinite(duration) && duration > 20 && pos > 5 && pos < duration - 5;+}++/** Update a { path: seconds } map, bounded to `max` entries (oldest dropped). */+export function updateResume(map, key, pos, duration, max = 200) {+ const next = { ...map };+ delete next[key];+ if (shouldRemember(pos, duration)) next[key] = Math.floor(pos);+ const keys = Object.keys(next);+ for (const k of keys.slice(0, Math.max(0, keys.length - max))) delete next[k];+ return next;+}diff --git a/src/desktop/os/apps/taskmgr.css b/src/desktop/os/apps/taskmgr.cssnew file mode 100644index 000000000..7c76c272d--- /dev/null+++ b/src/desktop/os/apps/taskmgr.css@@ -0,0 +1,58 @@+.napp-taskmgr { height: 100%; background: var(--card); color: var(--text); font-size: 13px; }+.napp-taskmgr .tmg { position: relative; height: 100%; display: flex; flex-direction: column; min-height: 0; }+.napp-taskmgr .tmg-tabs { display: flex; gap: 2px; padding: 8px 10px 0; border-bottom: 1px solid var(--bd); }+.napp-taskmgr .tmg-tabs button { padding: 8px 14px; border-radius: 6px 6px 0 0; color: var(--text2); border-bottom: 2px solid transparent; }+.napp-taskmgr .tmg-tabs button:hover { background: var(--hover); color: var(--text); }+.napp-taskmgr .tmg-tabs button[aria-selected=true] { color: var(--text); border-bottom-color: var(--accent); }+.napp-taskmgr .tmg-pane { flex: 1; min-height: 0; overflow: auto; padding: 12px; }+.napp-taskmgr .tmg-pane[hidden] { display: none; }+.napp-taskmgr .dim { color: var(--text2); }+.napp-taskmgr .r { text-align: right; justify-content: flex-end; }+.napp-taskmgr .tmg-bar { display: flex; align-items: center; justify-content: space-between; margin-bottom: 10px; }+.napp-taskmgr .tmg-btn { padding: 6px 14px; border-radius: 6px; background: var(--hover); border: 1px solid var(--bd); }+.napp-taskmgr .tmg-btn:hover:not(:disabled) { background: var(--accent); color: #fff; border-color: var(--accent); }+.napp-taskmgr .tmg-btn:active:not(:disabled) { filter: brightness(0.9); }+.napp-taskmgr .tmg-btn:disabled { opacity: 0.45; cursor: default; }+.napp-taskmgr .tmg-table { border: 1px solid var(--bd); border-radius: 8px; overflow: hidden; }+.napp-taskmgr .tmg-tr { display: grid; grid-template-columns: minmax(0, 2.4fr) 1fr 1fr 1.2fr; align-items: center; padding: 0 10px; min-height: 36px; gap: 8px; }+.napp-taskmgr .tmg-th { background: var(--hover); min-height: 32px; color: var(--text2); }+.napp-taskmgr .tmg-th button { text-align: left; padding: 6px 0; display: block; width: 100%; }+.napp-taskmgr .tmg-th button.r { text-align: right; }+.napp-taskmgr .tmg-th button:hover { color: var(--text); }+.napp-taskmgr .tmg-row { border-top: 1px solid var(--bd); cursor: default; }+.napp-taskmgr .tmg-row:hover { background: var(--hover); }+.napp-taskmgr .tmg-row.sel { background: color-mix(in srgb, var(--accent) 22%, transparent); }+.napp-taskmgr .tmg-name { display: flex; align-items: center; gap: 8px; min-width: 0; }+.napp-taskmgr .tmg-name > span:last-child { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }+.napp-taskmgr .tmg-empty { padding: 28px; text-align: center; color: var(--text2); border-top: 1px solid var(--bd); }+.napp-taskmgr .tmg-note { color: var(--text2); font-size: 12px; margin: 10px 2px 0; }+.napp-taskmgr .tmg-menu { position: absolute; z-index: 5; min-width: 140px; padding: 4px; background: var(--card); border: 1px solid var(--bd); border-radius: 8px; box-shadow: 0 8px 24px var(--sd, rgba(0,0,0,.4)); }+.napp-taskmgr .tmg-menu[hidden] { display: none; }+.napp-taskmgr .tmg-menu button { display: block; width: 100%; text-align: left; padding: 7px 10px; border-radius: 5px; }+.napp-taskmgr .tmg-menu button:hover, .napp-taskmgr .tmg-menu button:focus-visible { background: var(--hover); }+.napp-taskmgr .tmg-pane[data-pane=perf]:not([hidden]) { display: grid; grid-template-columns: 220px minmax(0, 1fr); gap: 14px; }+.napp-taskmgr .tmg-side { display: flex; flex-direction: column; gap: 6px; }+.napp-taskmgr .tmg-m { display: flex; gap: 10px; align-items: center; padding: 8px; border-radius: 8px; border: 1px solid transparent; text-align: left; }+.napp-taskmgr .tmg-m:hover { background: var(--hover); }+.napp-taskmgr .tmg-m.sel { background: var(--hover); border-color: var(--accent); }+.napp-taskmgr .tmg-m canvas { width: 96px; height: 40px; flex: none; border: 1px solid var(--bd); border-radius: 4px; }+.napp-taskmgr .tmg-m span { display: flex; flex-direction: column; min-width: 0; }+.napp-taskmgr .tmg-m small { color: var(--text2); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }+.napp-taskmgr .tmg-main { min-width: 0; }+.napp-taskmgr .tmg-head h3 { margin: 0; font-size: 15px; font-weight: 600; }+.napp-taskmgr .tmg-head .big { font-size: 26px; font-weight: 600; margin: 2px 0; }+.napp-taskmgr .tmg-head small { color: var(--text2); }+.napp-taskmgr .tmg-graph { display: block; width: 100%; height: 190px; margin: 12px 0; border: 1px solid var(--bd); border-radius: 8px; background: var(--hover-half, transparent); }+.napp-taskmgr .tmg-facts, .napp-taskmgr .tmg-card { display: grid; gap: 4px; }+.napp-taskmgr .tmg-facts > div, .napp-taskmgr .tmg-card > div:not(.tmg-res) { display: flex; justify-content: space-between; gap: 12px; padding: 5px 0; border-bottom: 1px solid var(--bd); }+.napp-taskmgr .tmg-facts span, .napp-taskmgr .tmg-card > div > span { color: var(--text2); }+.napp-taskmgr .tmg-facts b, .napp-taskmgr .tmg-card > div > b { font-weight: 500; text-align: right; }+.napp-taskmgr .tmg-cols { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; margin-bottom: 12px; }+.napp-taskmgr .tmg-card { align-content: start; border: 1px solid var(--bd); border-radius: 8px; padding: 12px; }+.napp-taskmgr .tmg-card h4 { margin: 0 0 6px; font-size: 13px; }+.napp-taskmgr .tmg-res { display: grid; grid-template-columns: minmax(0, 3fr) 70px 70px minmax(0, 1.2fr); gap: 8px; padding: 5px 0; border-bottom: 1px solid var(--bd); }+.napp-taskmgr .tmg-res > span:first-child { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }+@media (max-width: 620px) {+ .napp-taskmgr .tmg-pane[data-pane=perf]:not([hidden]) { grid-template-columns: 1fr; }+ .napp-taskmgr .tmg-cols { grid-template-columns: 1fr; }+}diff --git a/src/desktop/os/apps/taskmgr.js b/src/desktop/os/apps/taskmgr.jsnew file mode 100644index 000000000..c54ede457--- /dev/null+++ b/src/desktop/os/apps/taskmgr.js@@ -0,0 +1,461 @@+// Task Manager: running desktop windows, live performance from real browser+// sources, and page/resource details. Anything the browser cannot measure is+// labelled as such; no number is invented.+import './taskmgr.css';+import {+ RingBuffer, formatBytes, formatMs, formatPct, fpsFromFrames, mainThreadLoad, shareTotal, windowWeight,+ summarizeResources, shortUrl, sortRows, pageTiming,+} from './perf-logic.js';++const NA = 'Not supported by this browser';+const N = 60;++function gpuName() {+ try {+ const gl = document.createElement('canvas').getContext('webgl');+ const ext = gl?.getExtension('WEBGL_debug_renderer_info');+ return ext ? gl.getParameter(ext.UNMASKED_RENDERER_WEBGL) : null;+ } catch {+ return null;+ }+}++export function mount(host, ctx) {+ const { h, esc } = ctx;+ const root = h('div', 'tmg');+ root.innerHTML = `+ <div class="tmg-tabs" role="tablist">+ <button role="tab" data-tab="proc" aria-selected="true">Processes</button>+ <button role="tab" data-tab="perf" aria-selected="false">Performance</button>+ <button role="tab" data-tab="det" aria-selected="false">Details</button>+ </div>+ <section class="tmg-pane" data-pane="proc"></section>+ <section class="tmg-pane" data-pane="perf" hidden></section>+ <section class="tmg-pane" data-pane="det" hidden></section>+ <div class="tmg-menu" hidden role="menu"></div>`;+ host.append(root);+ const pane = (n) => root.querySelector(`[data-pane="${n}"]`);+ const menu = root.querySelector('.tmg-menu');+ const procPane = pane('proc');++ let tab = 'proc';+ let sort = { key: 'name', dir: 1 };+ let selected = null;+ let heapTotal = null;+ let heapExact = false;+ const disposers = [];+ let disposed = false;++ /* ---------------- sampling ---------------- */+ const buf = { cpu: new RingBuffer(N), fps: new RingBuffer(N), mem: new RingBuffer(N), rtt: new RingBuffer(N) };+ const frames = [];+ let rafId = 0;+ let tasks = [];+ let lastTick = performance.now();+ let lateSum = 0;+ let probeAt = performance.now();+ let probeTimer = 0;+ let tickTimer = 0;+ let po = null;+ const live = { battery: null, storage: null, rttNow: null, gpu: gpuName(), cpuNow: null, fpsNow: null };+ let battery = null;++ if (typeof PerformanceObserver !== 'undefined' && PerformanceObserver.supportedEntryTypes?.includes('longtask')) {+ try {+ po = new PerformanceObserver((list) => {+ tasks.push(...list.getEntries().map((e) => ({ startTime: e.startTime, duration: e.duration })));+ });+ po.observe({ type: 'longtask', buffered: false });+ } catch {+ po = null;+ }+ }+ navigator.getBattery?.().then((b) => {+ battery = b;+ }).catch(() => {});++ const active = () => document.visibilityState === 'visible' && host.offsetParent !== null && !disposed;++ function rafLoop(t) {+ frames.push(t);+ if (frames.length > 400) frames.splice(0, frames.length - 400);+ rafId = requestAnimationFrame(rafLoop);+ }+ function startRaf() {+ if (!rafId) rafId = requestAnimationFrame(rafLoop);+ }+ function stopRaf() {+ cancelAnimationFrame(rafId);+ rafId = 0;+ frames.length = 0;+ }++ // Timer drift probe: a 100ms timer that arrives late shows main-thread contention.+ function probe() {+ const now = performance.now();+ if (active()) lateSum += Math.max(0, now - probeAt - 100);+ probeAt = now;+ probeTimer = setTimeout(probe, 100);+ }++ async function rttProbe() {+ const t0 = performance.now();+ try {+ await fetch(location.pathname, { method: 'HEAD', cache: 'no-store' });+ live.rttNow = performance.now() - t0;+ } catch {+ live.rttNow = null;+ }+ }++ async function readMemory() {+ if (performance.measureUserAgentSpecificMemory && self.crossOriginIsolated) {+ try {+ const m = await performance.measureUserAgentSpecificMemory();+ heapTotal = m.bytes;+ heapExact = true;+ return;+ } catch {+ /* fall through to the heap counter */+ }+ }+ heapExact = false;+ heapTotal = performance.memory?.usedJSHeapSize ?? null;+ }++ let ticks = 0;+ async function tick() {+ const now = performance.now();+ if (!active()) {+ stopRaf();+ tasks = [];+ lateSum = 0;+ lastTick = now;+ return;+ }+ startRaf();+ const elapsed = now - lastTick;+ const cut = tasks;+ tasks = [];+ const cpu = frames.length > 2 || ticks > 0 ? mainThreadLoad({ tasks: cut, t0: lastTick, t1: now, expectedMs: elapsed, actualMs: elapsed + lateSum }) : null;+ lateSum = 0;+ lastTick = now;+ ticks++;+ live.cpuNow = cpu;+ buf.cpu.push(cpu);+ live.fpsNow = fpsFromFrames(frames, now);+ buf.fps.push(live.fpsNow);+ await readMemory();+ buf.mem.push(heapTotal);+ if (ticks % 5 === 1) rttProbe().then(() => buf.rtt.push(live.rttNow));+ if (ticks % 10 === 1 && navigator.storage?.estimate) navigator.storage.estimate().then((e) => (live.storage = e)).catch(() => {});+ render();+ }++ /* ---------------- Processes ---------------- */+ function procRows() {+ const wins = ctx.windows();+ const shares = shareTotal(heapTotal, wins.map((w) => windowWeight(w.rect)));+ return wins.map((w, i) => ({+ id: w.id, app: w.app, name: w.title, status: w.minimized ? 'Minimized' : 'Running',+ mem: heapTotal == null ? null : shares[i],+ size: w.rect ? w.rect.w * w.rect.h : null, rect: w.rect,+ }));+ }+ let procSig = '';+ const memText = () => (heapTotal == null ? 'Memory is not reported by this browser.' : `Page ${heapExact ? 'memory measured at' : 'JS heap is'} ${formatBytes(heapTotal)}; per-window values are shares by window area (estimated).`);+ function renderProc() {+ const focusId = procPane.contains(document.activeElement) ? document.activeElement.closest('[data-id]')?.dataset.id : null;+ const rows = sortRows(procRows(), sort.key, sort.dir);+ if (selected && !rows.some((r) => r.id === selected)) selected = null;+ const p = pane('proc');+ const sig = JSON.stringify([rows.map((r) => [r.id, r.name, r.status, r.rect && [Math.round(r.rect.w), Math.round(r.rect.h)]]), sort, selected, heapTotal == null, heapExact]);+ if (sig === procSig) {+ rows.forEach((r) => {+ const c = p.querySelector(`[data-id="${CSS.escape(r.id)}"] [data-mem]`);+ if (c) c.textContent = r.mem == null ? 'n/a' : formatBytes(r.mem);+ });+ const note = p.querySelector('.tmg-note');+ if (note) note.textContent = memText();+ return;+ }+ procSig = sig;+ const arrow = (k) => (sort.key === k ? (sort.dir > 0 ? ' ▲' : ' ▼') : '');+ p.innerHTML = `+ <div class="tmg-bar"><span><b>${rows.length}</b> app${rows.length === 1 ? '' : 's'} running</span>+ <button class="tmg-btn" data-act="end" ${selected ? '' : 'disabled'}>End task</button></div>+ <div class="tmg-table" role="table">+ <div class="tmg-tr tmg-th" role="row">+ <button data-sort="name" role="columnheader">Name${arrow('name')}</button>+ <button data-sort="status" role="columnheader">Status${arrow('status')}</button>+ <button data-sort="size" role="columnheader" class="r">Window${arrow('size')}</button>+ <button data-sort="mem" role="columnheader" class="r">Memory (est.)${arrow('mem')}</button>+ </div>+ ${rows.length ? rows.map((r) => `+ <div class="tmg-tr tmg-row${r.id === selected ? ' sel' : ''}" role="row" tabindex="0" data-id="${esc(r.id)}">+ <span class="tmg-name">${ctx.tile(r.app, 'sm', 16)}<span>${esc(r.name)}</span></span>+ <span class="${r.status === 'Minimized' ? 'dim' : ''}">${r.status}</span>+ <span class="r dim">${r.rect ? `${Math.round(r.rect.w)} x ${Math.round(r.rect.h)}` : 'n/a'}</span>+ <span class="r" data-mem>${r.mem == null ? 'n/a' : formatBytes(r.mem)}</span>+ </div>`).join('') : '<div class="tmg-empty">No apps are open.</div>'}+ </div>+ <p class="tmg-note">${esc(memText())}</p>`;+ if (focusId) p.querySelector(`[data-id="${CSS.escape(focusId)}"]`)?.focus();+ }++ /* ---------------- Performance ---------------- */+ let perfSel = 'cpu';+ const conn = () => navigator.connection;+ function metrics() {+ const c = conn();+ const heapLabel = heapExact ? 'Page memory' : 'JS heap';+ return [+ { id: 'cpu', name: 'Main thread', buf: buf.cpu, max: 1, value: formatPct(live.cpuNow), sub: 'Estimated from long tasks and timer drift', fmt: formatPct, ok: true },+ { id: 'fps', name: 'Frame rate', buf: buf.fps, max: 120, value: live.fpsNow == null ? 'n/a' : `${Math.round(live.fpsNow)} fps`, sub: 'requestAnimationFrame cadence', fmt: (v) => `${Math.round(v)} fps`, ok: true },+ { id: 'mem', name: heapLabel, buf: buf.mem, max: null, value: heapTotal == null ? NA : formatBytes(heapTotal), sub: heapExact ? 'measureUserAgentSpecificMemory' : 'performance.memory (Chromium)', fmt: formatBytes, ok: heapTotal != null },+ { id: 'net', name: 'Network', buf: buf.rtt, max: null, value: live.rttNow == null ? 'n/a' : formatMs(live.rttNow), sub: c ? `${c.effectiveType || '?'} ${c.downlink ?? '?'} Mbps rtt ${c.rtt ?? '?'} ms (browser estimate)` : 'Round trip to this site (measured)', fmt: formatMs, ok: true },+ ];+ }+ function facts() {+ const st = live.storage;+ const c = conn();+ return [+ ['Logical cores', navigator.hardwareConcurrency ? String(navigator.hardwareConcurrency) : NA],+ ['Device memory', navigator.deviceMemory ? `${navigator.deviceMemory} GB (rounded, capped by the browser)` : NA],+ ['GPU', live.gpu || 'Unavailable'],+ ['Connection', c ? `${c.effectiveType || 'unknown'}, ${c.downlink ?? '?'} Mbps down, ${c.rtt ?? '?'} ms rtt${c.saveData ? ', data saver on' : ''}` : NA],+ ['Battery', battery ? `${Math.round(battery.level * 100)}%${battery.charging ? ', charging' : ''}` : navigator.getBattery ? 'Reading...' : NA],+ ['Storage', st ? `${formatBytes(st.usage)} used of ${formatBytes(st.quota)} quota` : navigator.storage?.estimate ? 'Reading...' : NA],+ ['Cross-origin isolated', self.crossOriginIsolated ? 'Yes (exact page memory available)' : 'No (page memory is the JS heap)'],+ ];+ }+ function renderPerf() {+ const p = pane('perf');+ const ms = metrics();+ if (!p.firstElementChild) {+ p.innerHTML = '<div class="tmg-side"></div><div class="tmg-main"><div class="tmg-head"></div><canvas class="tmg-graph"></canvas><div class="tmg-facts"></div></div>';+ p.querySelector('.tmg-side').addEventListener('click', (e) => {+ const b = e.target.closest('[data-m]');+ if (b) {+ perfSel = b.dataset.m;+ renderPerf();+ }+ });+ }+ p.querySelector('.tmg-side').innerHTML = ms.map((m) => `+ <button class="tmg-m${m.id === perfSel ? ' sel' : ''}" data-m="${m.id}">+ <canvas width="96" height="40" data-spark="${m.id}"></canvas>+ <span><b>${esc(m.name)}</b><small>${esc(m.value)}</small></span>+ </button>`).join('');+ const cur = ms.find((m) => m.id === perfSel) || ms[0];+ p.querySelector('.tmg-head').innerHTML = `<h3>${esc(cur.name)}</h3><div class="big">${esc(cur.value)}</div><small>${esc(cur.sub)}</small>`;+ p.querySelector('.tmg-facts').innerHTML = facts().map(([k, v]) => `<div><span>${esc(k)}</span><b>${esc(v)}</b></div>`).join('');+ const accent = getComputedStyle(root).getPropertyValue('--accent').trim() || '#4cc2ff';+ for (const m of ms) {+ const cv = p.querySelector(`[data-spark="${m.id}"]`);+ if (cv) drawGraph(cv, m, accent, false);+ }+ const big = p.querySelector('.tmg-graph');+ if (!cur.ok) {+ const ctx2 = big.getContext('2d');+ big.width = big.clientWidth;+ big.height = big.clientHeight;+ ctx2.clearRect(0, 0, big.width, big.height);+ ctx2.fillStyle = '#8a8f99';+ ctx2.font = '13px system-ui';+ ctx2.fillText(NA, 12, 24);+ } else drawGraph(big, cur, accent, true);+ }+ function drawGraph(cv, m, color, big) {+ const dpr = window.devicePixelRatio || 1;+ const w = big ? cv.clientWidth : 96;+ const hgt = big ? cv.clientHeight : 40;+ if (!w || !hgt) return;+ if (cv.width !== Math.round(w * dpr) || cv.height !== Math.round(hgt * dpr)) {+ cv.width = Math.round(w * dpr);+ cv.height = Math.round(hgt * dpr);+ }+ const g = cv.getContext('2d');+ g.setTransform(dpr, 0, 0, dpr, 0, 0);+ g.clearRect(0, 0, w, hgt);+ const data = m.buf.toArray();+ const max = m.max ?? Math.max(m.buf.max() * 1.15, 1);+ if (big) {+ g.strokeStyle = 'rgba(128,128,140,0.25)';+ g.lineWidth = 1;+ for (let i = 1; i < 4; i++) {+ g.beginPath();+ g.moveTo(0, (hgt * i) / 4);+ g.lineTo(w, (hgt * i) / 4);+ g.stroke();+ }+ g.fillStyle = '#8a8f99';+ g.font = '11px system-ui';+ g.fillText(m.fmt(max), 6, 12);+ }+ const step = w / (N - 1);+ const x = (i) => w - (data.length - 1 - i) * step;+ const y = (v) => hgt - 2 - Math.min(1, v / max) * (hgt - 4);+ g.beginPath();+ let started = false;+ let firstX = 0;+ let lastX = 0;+ data.forEach((v, i) => {+ if (v == null) return;+ if (!started) {+ g.moveTo(x(i), y(v));+ firstX = x(i);+ started = true;+ } else g.lineTo(x(i), y(v));+ lastX = x(i);+ });+ if (!started) return;+ g.strokeStyle = color;+ g.lineWidth = big ? 2 : 1.5;+ g.stroke();+ g.lineTo(lastX, hgt);+ g.lineTo(firstX, hgt);+ g.closePath();+ g.globalAlpha = 0.18;+ g.fillStyle = color;+ g.fill();+ g.globalAlpha = 1;+ }++ /* ---------------- Details ---------------- */+ function renderDet() {+ const p = pane('det');+ const nav = performance.getEntriesByType('navigation')[0];+ const t = pageTiming(nav);+ const sum = summarizeResources(performance.getEntriesByType('resource'));+ const row = (k, v) => `<div><span>${esc(k)}</span><b>${esc(v)}</b></div>`;+ p.innerHTML = `+ <div class="tmg-cols">+ <div class="tmg-card"><h4>Page timing</h4>+ ${t ? [['DNS lookup', formatMs(t.dns)], ['Connect', formatMs(t.connect)], ['First byte', formatMs(t.ttfb)], ['DOM interactive', formatMs(t.domInteractive)], ['DOM content loaded', formatMs(t.domContentLoaded)], ['Load event', formatMs(t.load)], ['Document transfer', formatBytes(t.transferSize)]].map((r) => row(...r)).join('') : `<p class="dim">${NA}</p>`}+ </div>+ <div class="tmg-card"><h4>Resources</h4>+ ${row('Requests', String(sum.total))}${row('Transferred', formatBytes(sum.transfer))}+ ${sum.byType.map((b) => row(b.type, `${b.count} ${formatBytes(b.bytes)}`)).join('')}+ </div>+ </div>+ <div class="tmg-card wide"><h4>Slowest resources</h4>+ ${sum.slowest.length ? sum.slowest.map((s) => `<div class="tmg-res"><span title="${esc(s.name)}">${esc(shortUrl(s.name))}</span><span class="dim">${esc(s.type)}</span><b>${formatMs(s.duration)}</b><span class="dim r">${s.bytes ? formatBytes(s.bytes) : 'cached or cross-origin'}</span></div>`).join('') : '<p class="dim">No resource timings recorded yet.</p>'}+ </div>`;+ }++ function render() {+ if (tab === 'proc') renderProc();+ else if (tab === 'perf') renderPerf();+ else if (tab === 'det' && ticks % 3 === 1) renderDet();+ }++ /* ---------------- events ---------------- */+ function setTab(t) {+ tab = t;+ root.querySelectorAll('.tmg-tabs [role=tab]').forEach((b) => b.setAttribute('aria-selected', String(b.dataset.tab === t)));+ root.querySelectorAll('.tmg-pane').forEach((s) => (s.hidden = s.dataset.pane !== t));+ hideMenu();+ if (t === 'det') renderDet();+ else if (t === 'perf') renderPerf();+ else renderProc();+ }+ root.querySelector('.tmg-tabs').addEventListener('click', (e) => {+ const b = e.target.closest('[data-tab]');+ if (b) setTab(b.dataset.tab);+ });++ function endTask(id) {+ if (!id) return;+ if (id === 'taskmgr') ctx.toast('Closing Task Manager');+ ctx.closeWindow(id);+ if (selected === id) selected = null;+ setTimeout(() => !disposed && render(), 0);+ }+ function hideMenu() {+ menu.hidden = true;+ }+ function showMenu(e, id) {+ selected = id;+ menu.innerHTML = `<button role="menuitem" data-a="switch">Switch to</button><button role="menuitem" data-a="end">End task</button>`;+ menu.dataset.id = id;+ const r = root.getBoundingClientRect();+ menu.style.left = `${Math.min(e.clientX - r.left, r.width - 150)}px`;+ menu.style.top = `${Math.min(e.clientY - r.top, r.height - 80)}px`;+ menu.hidden = false;+ menu.querySelector('button').focus();+ renderProc();+ }+ procPane.addEventListener('click', (e) => {+ const s = e.target.closest('[data-sort]');+ if (s) {+ sort = { key: s.dataset.sort, dir: sort.key === s.dataset.sort ? -sort.dir : 1 };+ return renderProc();+ }+ if (e.target.closest('[data-act=end]')) return endTask(selected);+ const r = e.target.closest('[data-id]');+ if (r) {+ selected = r.dataset.id;+ renderProc();+ }+ });+ procPane.addEventListener('dblclick', (e) => {+ const r = e.target.closest('[data-id]');+ if (r) ctx.focusWindow(r.dataset.id);+ });+ procPane.addEventListener('contextmenu', (e) => {+ const r = e.target.closest('[data-id]');+ if (!r) return;+ e.preventDefault();+ showMenu(e, r.dataset.id);+ });+ procPane.addEventListener('keydown', (e) => {+ const r = e.target.closest('[data-id]');+ if (!r) return;+ if (e.key === 'Delete') endTask(r.dataset.id);+ else if (e.key === 'Enter') ctx.focusWindow(r.dataset.id);+ else if (e.key === ' ') {+ e.preventDefault();+ selected = r.dataset.id;+ renderProc();+ }+ });+ menu.addEventListener('click', (e) => {+ const a = e.target.closest('[data-a]')?.dataset.a;+ const id = menu.dataset.id;+ hideMenu();+ if (a === 'switch') ctx.focusWindow(id);+ else if (a === 'end') endTask(id);+ });+ const away = (e) => {+ if (!menu.hidden && !menu.contains(e.target)) hideMenu();+ };+ document.addEventListener('pointerdown', away, true);+ disposers.push(() => document.removeEventListener('pointerdown', away, true));+ root.addEventListener('keydown', (e) => e.key === 'Escape' && hideMenu());++ const ro = new ResizeObserver(() => tab === 'perf' && renderPerf());+ ro.observe(root);+ disposers.push(() => ro.disconnect());++ const onVis = () => {+ if (document.visibilityState === 'visible') tick();+ };+ document.addEventListener('visibilitychange', onVis);+ disposers.push(() => document.removeEventListener('visibilitychange', onVis));++ renderProc();+ probe();+ tickTimer = setInterval(tick, 1000);+ startRaf();+ readMemory().then(() => !disposed && render());++ return () => {+ disposed = true;+ clearInterval(tickTimer);+ clearTimeout(probeTimer);+ stopRaf();+ po?.disconnect();+ disposers.forEach((d) => d());+ };+}diff --git a/src/desktop/os/apps/term-commands.js b/src/desktop/os/apps/term-commands.jsnew file mode 100644index 000000000..baa909f9b--- /dev/null+++ b/src/desktop/os/apps/term-commands.js@@ -0,0 +1,832 @@+// Terminal command language: tokenizer, pipeline executor and the command table.+// Pure of the DOM. Everything the commands touch arrives through an injected+// environment, so the same code runs against the real virtual file system in+// the browser and against an in-memory one in tests.+//+// env = {+// fs, // ../fs.js API (stat, list, read, readText, write, mkdir, move, copy, remove, walk, normalize, join, nameOf, parentOf, kindOf)+// fetch, // fetch-compatible+// now: () => Date, // clock+// cwd: '/', // mutated by cd+// vars: {}, // environment variables+// history: [], // command history (for `history`)+// host: { // optional bridges into the desktop+// openPath, launchId, apps: [{id,title}], windows: () => [], closeWindow,+// setTheme(mode), clear(), userName(), sysinfo(): object, uptimeMs(): number,+// },+// }++export const COMMAND_NAMES = [];++/** Split a command line into pipeline stages of { argv, redirect }. Throws on a syntax error. */+export function parseLine(line) {+ const stages = [];+ let argv = [];+ let redirect = null;+ let cur = '';+ let has = false;+ let quote = null;+ let pendingRedirect = null;+ let trailingPipe = false;+ const pushWord = () => {+ if (!has) return;+ if (pendingRedirect) {+ redirect = { mode: pendingRedirect, target: cur };+ pendingRedirect = null;+ } else argv.push(cur);+ cur = '';+ has = false;+ };+ const endStage = () => {+ pushWord();+ if (pendingRedirect) throw new Error('syntax error: expected a file name after the redirect');+ if (!argv.length) throw new Error('syntax error: empty command in pipeline');+ trailingPipe = false;+ stages.push({ argv, redirect });+ argv = [];+ redirect = null;+ };+ for (let i = 0; i < line.length; i++) {+ const c = line[i];+ if (quote) {+ if (c === quote) quote = null;+ else if (c === '\\' && quote === '"' && i + 1 < line.length && '"\\$'.includes(line[i + 1])) cur += line[++i];+ else cur += c;+ continue;+ }+ if (c === '"' || c === "'") {+ quote = c;+ has = true;+ } else if (c === '\\' && i + 1 < line.length) {+ cur += line[++i];+ has = true;+ } else if (/\s/.test(c)) pushWord();+ else if (c === '|') {+ endStage();+ trailingPipe = true;+ continue;+ }+ else if (c === '>') {+ pushWord();+ if (line[i + 1] === '>') {+ pendingRedirect = 'append';+ i++;+ } else pendingRedirect = 'write';+ } else {+ cur += c;+ has = true;+ }+ }+ if (quote) throw new Error('syntax error: unterminated quote');+ if (has || argv.length || pendingRedirect) endStage();+ if (trailingPipe) throw new Error('syntax error: empty command in pipeline');+ return stages;+}++/** Levenshtein distance. */+export function editDistance(a, b) {+ const dp = Array.from({ length: a.length + 1 }, (_, i) => [i, ...Array(b.length).fill(0)]);+ for (let j = 1; j <= b.length; j++) dp[0][j] = j;+ for (let i = 1; i <= a.length; i++)+ for (let j = 1; j <= b.length; j++)+ dp[i][j] = Math.min(dp[i - 1][j] + 1, dp[i][j - 1] + 1, dp[i - 1][j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1));+ return dp[a.length][b.length];+}++/** Closest command name within a small distance, or null. */+export function suggest(name, names = COMMAND_NAMES) {+ let best = null;+ let bestD = Infinity;+ for (const n of names) {+ const d = editDistance(name.toLowerCase(), n);+ if (d < bestD) {+ bestD = d;+ best = n;+ }+ }+ return best && bestD <= Math.max(2, Math.floor(name.length / 3)) ? best : null;+}++export function formatBytes(n) {+ if (!Number.isFinite(n)) return '-';+ if (n < 1024) return `${n} B`;+ const u = ['KB', 'MB', 'GB', 'TB'];+ let i = -1;+ do {+ n /= 1024;+ i++;+ } while (n >= 1024 && i < u.length - 1);+ return `${n.toFixed(n < 10 ? 1 : 0)} ${u[i]}`;+}++export function formatUptime(ms) {+ const s = Math.floor(ms / 1000);+ const parts = [];+ if (s >= 3600) parts.push(`${Math.floor(s / 3600)}h`);+ if (s >= 60) parts.push(`${Math.floor((s % 3600) / 60)}m`);+ parts.push(`${s % 60}s`);+ return parts.join(' ');+}++/** Output buffer of styled segments. cls: 'dir' | 'err' | 'ok' | 'warn' | 'dim' | 'acc' | ''. */+export class Out {+ constructor() {+ this.segs = [];+ }+ write(text, cls = '') {+ if (text !== '') this.segs.push({ t: String(text), c: cls });+ }+ line(text = '', cls = '') {+ this.write(`${text}\n`, cls);+ }+ text() {+ return this.segs.map((s) => s.t).join('');+ }+}++const usageErr = (io, msg) => {+ io.out.line(msg, 'err');+ return 1;+};++const resolvePath = (env, p) => {+ const { normalize } = env.fs;+ if (p === '~' || p === '') return '/';+ if (p.startsWith('~/')) return normalize(p.slice(1));+ return p.startsWith('/') ? normalize(p) : normalize(`${env.cwd}/${p}`);+};++/** Split `-l -r` style flags from operands. */+function flags(args) {+ const f = new Set();+ const rest = [];+ let done = false;+ for (const a of args) {+ if (!done && a === '--') done = true;+ else if (!done && /^-[a-zA-Z]+$/.test(a)) for (const ch of a.slice(1)) f.add(ch);+ else rest.push(a);+ }+ return { f, rest };+}++async function readInput(env, io, files) {+ if (!files.length) return io.stdin ?? '';+ const parts = [];+ for (const file of files) {+ const p = resolvePath(env, file);+ const st = await env.fs.stat(p);+ if (!st) throw new Error(`${file}: no such file`);+ if (st.type === 'dir') throw new Error(`${file}: is a directory`);+ parts.push(await env.fs.readText(p));+ }+ return parts.join('');+}++const lines = (s) => {+ const l = s.split('\n');+ if (l.length && l[l.length - 1] === '') l.pop();+ return l;+};++const fmtDate = (ms) => {+ const d = new Date(ms);+ const p = (n) => String(n).padStart(2, '0');+ return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}`;+};++async function jsonFetch(env, url, init) {+ const r = await env.fetch(url, init);+ if (!r.ok) throw new Error(`HTTP ${r.status} from ${url}`);+ return r.json();+}++const money = (n) => {+ if (n == null || !Number.isFinite(Number(n))) return 'n/a';+ n = Number(n);+ return `$${n >= 1 ? n.toLocaleString('en-US', { maximumFractionDigits: 2 }) : n.toPrecision(4)}`;+};++const WMO = {+ 0: 'Clear sky', 1: 'Mainly clear', 2: 'Partly cloudy', 3: 'Overcast', 45: 'Fog', 48: 'Rime fog',+ 51: 'Light drizzle', 53: 'Drizzle', 55: 'Heavy drizzle', 61: 'Light rain', 63: 'Rain', 65: 'Heavy rain',+ 71: 'Light snow', 73: 'Snow', 75: 'Heavy snow', 77: 'Snow grains', 80: 'Rain showers', 81: 'Rain showers', 82: 'Violent showers',+ 85: 'Snow showers', 86: 'Heavy snow showers', 95: 'Thunderstorm', 96: 'Thunderstorm, hail', 99: 'Thunderstorm, heavy hail',+};+export const weatherLabel = (code) => WMO[code] || `Code ${code}`;++const HELP = [+ ['help', 'Show this list'],+ ['ls [-l] [path]', 'List a folder'],+ ['cd, pwd', 'Change or print the working folder'],+ ['cat, head, tail, wc, grep', 'Read and filter text (work in pipes)'],+ ['echo [text] [> file]', 'Print text, or write it to a file (>> appends)'],+ ['mkdir, touch, rm [-r], mv, cp', 'Manage files (rm moves to the Trash)'],+ ['open <path|app>', 'Open a file or launch an app'],+ ['edit <file>', 'Edit a file in Notepad'],+ ['find <name>', 'Search file names'],+ ['apps, kill <id>', 'List apps, close a window'],+ ['theme dark|light|auto', 'Switch the desktop theme'],+ ['date, whoami, uname, env, history, neofetch', 'System information'],+ ['curl <url>', 'Fetch a URL (same origin or CORS enabled)'],+ ['ping [host]', 'Measure a real round trip'],+ ['weather <city>', 'Live forecast from Open-Meteo'],+ ['three price|agents [n]|launches', 'Live three.ws data'],+ ['clear', 'Clear the screen (Ctrl+L)'],+];++export const COMMANDS = {+ help(args, env, io) {+ io.out.line('three.ws terminal. Pipes (|) and redirects (> >>) work with the text commands.', 'dim');+ io.out.line('');+ const w = Math.max(...HELP.map((h) => h[0].length)) + 2;+ for (const [c, d] of HELP) {+ io.out.write(c.padEnd(w), 'acc');+ io.out.line(d);+ }+ io.out.line('');+ io.out.line('Tab completes commands and paths. Up and Down walk your history. Ctrl+C cancels, Ctrl+L clears.', 'dim');+ return 0;+ },++ clear(args, env, io) {+ env.host?.clear?.();+ io.cleared = true;+ return 0;+ },++ pwd(args, env, io) {+ io.out.line(env.cwd);+ return 0;+ },++ async cd(args, env, io) {+ const target = resolvePath(env, args[0] ?? '~');+ const st = await env.fs.stat(target);+ if (!st) return usageErr(io, `cd: ${args[0]}: no such folder`);+ if (st.type !== 'dir') return usageErr(io, `cd: ${args[0]}: not a folder`);+ env.cwd = target;+ return 0;+ },++ async ls(args, env, io) {+ const { f, rest } = flags(args);+ const targets = rest.length ? rest : ['.'];+ let code = 0;+ for (const t of targets) {+ const p = resolvePath(env, t);+ const st = await env.fs.stat(p);+ if (!st) {+ io.out.line(`ls: ${t}: no such file or folder`, 'err');+ code = 1;+ continue;+ }+ if (targets.length > 1) io.out.line(`${t}:`, 'dim');+ const items = st.type === 'dir' ? await env.fs.list(p) : [st];+ if (!items.length) io.out.line('(empty)', 'dim');+ else if (f.has('l')) {+ for (const n of items) {+ io.out.write(`${n.type === 'dir' ? 'd' : '-'} ${(n.type === 'dir' ? '-' : formatBytes(n.size)).padStart(8)} ${fmtDate(n.mtime)} `, 'dim');+ io.out.line(n.type === 'dir' ? `${n.name}/` : n.name, n.type === 'dir' ? 'dir' : '');+ }+ } else {+ items.forEach((n, i) => {+ io.out.write(n.type === 'dir' ? `${n.name}/` : n.name, n.type === 'dir' ? 'dir' : '');+ io.out.write(i === items.length - 1 ? '\n' : ' ');+ });+ }+ }+ return code;+ },++ async cat(args, env, io) {+ try {+ io.out.write(await readInput(env, io, args));+ return 0;+ } catch (e) {+ return usageErr(io, `cat: ${e.message}`);+ }+ },++ echo(args, env, io) {+ io.out.line(args.join(' '));+ return 0;+ },++ async mkdir(args, env, io) {+ const { f, rest } = flags(args);+ if (!rest.length) return usageErr(io, 'usage: mkdir [-p] <folder>...');+ let code = 0;+ for (const a of rest) {+ try {+ const p = resolvePath(env, a);+ if (f.has('p')) {+ let acc = '';+ for (const seg of p.split('/').filter(Boolean)) {+ acc += `/${seg}`;+ if (!(await env.fs.stat(acc))) await env.fs.mkdir(acc);+ }+ } else await env.fs.mkdir(p);+ } catch (e) {+ io.out.line(`mkdir: ${a}: ${e.message}`, 'err');+ code = 1;+ }+ }+ return code;+ },++ async touch(args, env, io) {+ if (!args.length) return usageErr(io, 'usage: touch <file>...');+ let code = 0;+ for (const a of args) {+ try {+ const p = resolvePath(env, a);+ const st = await env.fs.stat(p);+ if (!st) await env.fs.write(p, '');+ else if (st.type === 'file') await env.fs.write(p, (await env.fs.read(p)).blob);+ } catch (e) {+ io.out.line(`touch: ${a}: ${e.message}`, 'err');+ code = 1;+ }+ }+ return code;+ },++ async rm(args, env, io) {+ const { f, rest } = flags(args);+ if (!rest.length) return usageErr(io, 'usage: rm [-r] <path>...');+ let code = 0;+ for (const a of rest) {+ try {+ const p = resolvePath(env, a);+ const st = await env.fs.stat(p);+ if (!st) throw new Error('no such file or folder');+ if (st.type === 'dir' && !f.has('r') && !f.has('R')) throw new Error('is a folder (use rm -r)');+ await env.fs.remove(p);+ io.out.line(`${a} moved to the Trash`, 'dim');+ } catch (e) {+ io.out.line(`rm: ${a}: ${e.message}`, 'err');+ code = 1;+ }+ }+ return code;+ },++ async mv(args, env, io) {+ if (args.length !== 2) return usageErr(io, 'usage: mv <from> <to>');+ try {+ const from = resolvePath(env, args[0]);+ let to = resolvePath(env, args[1]);+ const dst = await env.fs.stat(to);+ if (dst?.type === 'dir') to = env.fs.join(to, env.fs.nameOf(from));+ await env.fs.move(from, to);+ return 0;+ } catch (e) {+ return usageErr(io, `mv: ${e.message}`);+ }+ },++ async cp(args, env, io) {+ if (args.length !== 2) return usageErr(io, 'usage: cp <from> <to>');+ try {+ const from = resolvePath(env, args[0]);+ let to = resolvePath(env, args[1]);+ const dst = await env.fs.stat(to);+ if (dst?.type === 'dir') to = env.fs.join(to, env.fs.nameOf(from));+ await env.fs.copy(from, to);+ return 0;+ } catch (e) {+ return usageErr(io, `cp: ${e.message}`);+ }+ },++ async open(args, env, io) {+ if (!args.length) return usageErr(io, 'usage: open <path|app>');+ const host = env.host;+ if (!host?.openPath) return usageErr(io, 'open: not available here');+ const p = resolvePath(env, args[0]);+ const st = await env.fs.stat(p);+ if (st) {+ await host.openPath(p);+ return 0;+ }+ const app = (host.apps || []).find((a) => a.id === args[0].toLowerCase() || a.title.toLowerCase() === args.join(' ').toLowerCase());+ if (app) {+ host.launchId(app.id);+ return 0;+ }+ return usageErr(io, `open: ${args[0]}: no such file, folder or app`);+ },++ async edit(args, env, io) {+ if (!args.length) return usageErr(io, 'usage: edit <file>');+ const p = resolvePath(env, args[0]);+ let st = await env.fs.stat(p);+ if (!st) {+ try {+ await env.fs.write(p, '');+ } catch (e) {+ return usageErr(io, `edit: ${e.message}`);+ }+ st = await env.fs.stat(p);+ }+ if (st.type === 'dir') return usageErr(io, 'edit: is a folder');+ env.host?.launchId?.('notepad', { arg: p });+ return 0;+ },++ async find(args, env, io) {+ if (!args.length) return usageErr(io, 'usage: find <name> [folder]');+ const needle = args[0].toLowerCase();+ const root = resolvePath(env, args[1] ?? '.');+ const hits = (await env.fs.walk(root)).filter((n) => n.name.toLowerCase().includes(needle) && !n.path.startsWith('/Trash/'));+ if (!hits.length) io.out.line('No matches.', 'dim');+ for (const n of hits) io.out.line(n.path, n.type === 'dir' ? 'dir' : '');+ return hits.length ? 0 : 1;+ },++ async grep(args, env, io) {+ const { f, rest } = flags(args);+ if (!rest.length) return usageErr(io, 'usage: grep [-i] [-n] [-v] <pattern> [file]');+ const [pattern, ...files] = rest;+ let re;+ try {+ re = new RegExp(pattern, f.has('i') ? 'i' : '');+ } catch {+ re = new RegExp(pattern.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), f.has('i') ? 'i' : '');+ }+ let text;+ try {+ text = await readInput(env, io, files);+ } catch (e) {+ return usageErr(io, `grep: ${e.message}`);+ }+ let n = 0;+ lines(text).forEach((l, i) => {+ if (re.test(l) === !!f.has('v')) return;+ n++;+ if (f.has('n')) io.out.write(`${i + 1}:`, 'dim');+ io.out.line(l);+ });+ return n ? 0 : 1;+ },++ async wc(args, env, io) {+ const { f, rest } = flags(args);+ let text;+ try {+ text = await readInput(env, io, rest);+ } catch (e) {+ return usageErr(io, `wc: ${e.message}`);+ }+ const l = (text.match(/\n/g) || []).length;+ const w = (text.trim() ? text.trim().split(/\s+/) : []).length;+ const c = new TextEncoder().encode(text).length;+ const parts = [];+ if (f.has('l')) parts.push(l);+ if (f.has('w')) parts.push(w);+ if (f.has('c')) parts.push(c);+ io.out.line((parts.length ? parts : [l, w, c]).join(' '));+ return 0;+ },++ async head(args, env, io) {+ return headTail(args, env, io, true);+ },+ async tail(args, env, io) {+ return headTail(args, env, io, false);+ },++ date(args, env, io) {+ io.out.line(env.now().toString());+ return 0;+ },++ whoami(args, env, io) {+ io.out.line(env.host?.userName?.() || 'guest');+ return 0;+ },++ uname(args, env, io) {+ const si = env.host?.sysinfo?.() || {};+ io.out.line(args.includes('-a') ? `three.ws-desktop web ${si.platform || ''} ${si.userAgent || ''}`.trim() : 'three.ws-desktop');+ return 0;+ },++ env(args, env, io) {+ for (const [k, v] of Object.entries(env.vars)) io.out.line(`${k}=${v}`);+ return 0;+ },++ history(args, env, io) {+ env.history.forEach((h, i) => io.out.line(`${String(i + 1).padStart(4)} ${h}`));+ return 0;+ },++ theme(args, env, io) {+ const m = (args[0] || '').toLowerCase();+ if (!['dark', 'light', 'auto'].includes(m)) return usageErr(io, 'usage: theme dark|light|auto');+ env.host?.setTheme?.(m);+ io.out.line(`Theme set to ${m}.`, 'ok');+ return 0;+ },++ apps(args, env, io) {+ const list = env.host?.apps || [];+ if (!list.length) io.out.line('No apps registered.', 'dim');+ for (const a of list) {+ io.out.write(a.id.padEnd(14), 'acc');+ io.out.line(a.title);+ }+ return 0;+ },++ kill(args, env, io) {+ const wins = env.host?.windows?.() || [];+ if (!args.length) {+ if (!wins.length) io.out.line('No open windows.', 'dim');+ for (const w of wins) {+ io.out.write(String(w.id).padEnd(14), 'acc');+ io.out.line(w.title);+ }+ return 0;+ }+ const w = wins.find((x) => x.id === args[0]);+ if (!w) return usageErr(io, `kill: ${args[0]}: no such window (run kill with no arguments to list them)`);+ env.host.closeWindow(w.id);+ io.out.line(`Closed ${w.title}.`, 'ok');+ return 0;+ },++ async curl(args, env, io) {+ const { f, rest } = flags(args);+ if (!rest.length) return usageErr(io, 'usage: curl [-I] <url>');+ let url;+ try {+ url = new URL(rest[0], env.baseUrl || 'https://three.ws/').href;+ } catch {+ return usageErr(io, `curl: invalid URL: ${rest[0]}`);+ }+ const t0 = env.perfNow();+ try {+ const r = await env.fetch(url, { method: f.has('I') ? 'HEAD' : 'GET' });+ io.out.write(`HTTP ${r.status} ${r.statusText || ''}`.trim(), r.ok ? 'ok' : 'err');+ io.out.line(` ${Math.round(env.perfNow() - t0)} ms`, 'dim');+ const ct = r.headers?.get?.('content-type');+ if (ct) io.out.line(`content-type: ${ct}`, 'dim');+ if (!f.has('I')) {+ const body = await r.text();+ const cap = 20000;+ io.out.write(body.slice(0, cap));+ if (!body.endsWith('\n')) io.out.write('\n');+ if (body.length > cap) io.out.line(`... truncated ${formatBytes(body.length - cap)}`, 'dim');+ }+ return r.ok ? 0 : 22;+ } catch (e) {+ io.out.line(`curl: request failed: ${e.message}. Cross-origin URLs need CORS enabled by the server.`, 'err');+ return 7;+ }+ },++ async ping(args, env, io) {+ const base = env.baseUrl || 'https://three.ws/';+ let url;+ try {+ url = args[0] ? new URL(/^https?:\/\//.test(args[0]) ? args[0] : `https://${args[0]}/`).href : new URL('/api/health', base).href;+ } catch {+ return usageErr(io, `ping: invalid host: ${args[0]}`);+ }+ const times = [];+ for (let i = 0; i < 4; i++) {+ if (io.signal?.aborted) break;+ const t0 = env.perfNow();+ try {+ const r = await env.fetch(url, { method: 'GET', cache: 'no-store', mode: args[0] ? 'no-cors' : 'cors', signal: io.signal });+ const ms = env.perfNow() - t0;+ times.push(ms);+ io.out.line(`reply from ${url}: ${r.status || 'opaque'} time=${ms.toFixed(1)} ms`);+ } catch (e) {+ if (io.signal?.aborted) break;+ io.out.line(`request to ${url} failed: ${e.message}`, 'err');+ }+ }+ if (times.length) {+ const avg = times.reduce((a, b) => a + b, 0) / times.length;+ io.out.line(`${times.length} replies, min ${Math.min(...times).toFixed(1)} ms, avg ${avg.toFixed(1)} ms, max ${Math.max(...times).toFixed(1)} ms`, 'ok');+ return 0;+ }+ return 1;+ },++ async weather(args, env, io) {+ const city = args.join(' ').trim();+ if (!city) return usageErr(io, 'usage: weather <city>');+ try {+ const g = await jsonFetch(env, `https://geocoding-api.open-meteo.com/v1/search?name=${encodeURIComponent(city)}&count=1&language=en&format=json`);+ const place = g.results?.[0];+ if (!place) return usageErr(io, `weather: no place found for "${city}"`);+ const w = await jsonFetch(+ env,+ `https://api.open-meteo.com/v1/forecast?latitude=${place.latitude}&longitude=${place.longitude}¤t=temperature_2m,apparent_temperature,relative_humidity_2m,wind_speed_10m,weather_code&daily=temperature_2m_max,temperature_2m_min,weather_code&forecast_days=3&timezone=auto`,+ );+ const c = w.current;+ io.out.line(`${place.name}${place.admin1 ? `, ${place.admin1}` : ''}, ${place.country || ''}`, 'acc');+ io.out.line(`${weatherLabel(c.weather_code)} ${c.temperature_2m}${w.current_units.temperature_2m} (feels ${c.apparent_temperature}${w.current_units.temperature_2m})`);+ io.out.line(`Humidity ${c.relative_humidity_2m}% Wind ${c.wind_speed_10m} ${w.current_units.wind_speed_10m}`, 'dim');+ w.daily.time.forEach((d, i) => io.out.line(`${d} ${String(w.daily.temperature_2m_min[i]).padStart(5)} / ${String(w.daily.temperature_2m_max[i]).padEnd(5)} ${weatherLabel(w.daily.weather_code[i])}`));+ return 0;+ } catch (e) {+ return usageErr(io, `weather: ${e.message}`);+ }+ },++ async three(args, env, io) {+ const sub = (args[0] || '').toLowerCase();+ try {+ if (sub === 'price') {+ const s = await jsonFetch(env, new URL('/api/three-token/stats', env.baseUrl || 'https://three.ws/').href);+ const t = s.token || {};+ io.out.write('$THREE ', 'acc');+ io.out.write(money(t.price_usd));+ const ch = t.price_change_24h;+ if (ch != null) io.out.write(` ${ch >= 0 ? '+' : ''}${Number(ch).toFixed(2)}% 24h`, ch >= 0 ? 'ok' : 'err');+ io.out.write('\n');+ io.out.line(`market cap ${money(t.market_cap)} volume 24h ${money(t.volume_24h)} holders ${t.holders ?? 'n/a'}`, 'dim');+ return 0;+ }+ if (sub === 'agents') {+ const n = Math.min(Math.max(parseInt(args[1], 10) || 10, 1), 48);+ const d = await jsonFetch(env, new URL(`/api/agents/public?limit=${n}`, env.baseUrl || 'https://three.ws/').href);+ const list = d.agents || [];+ if (!list.length) io.out.line('No public agents yet.', 'dim');+ for (const a of list) {+ io.out.write(String(a.name || 'Unnamed').padEnd(26), 'acc');+ io.out.line(String(a.description || '').replace(/\s+/g, ' ').slice(0, 60), 'dim');+ }+ return 0;+ }+ if (sub === 'launches') {+ const d = await jsonFetch(env, new URL('/api/pump/launches?limit=10', env.baseUrl || 'https://three.ws/').href);+ const list = d.data?.launches || [];+ if (!list.length) io.out.line('No launches yet.', 'dim');+ for (const l of list) {+ io.out.write(String(l.symbol || '?').padEnd(10), 'acc');+ io.out.write(String(l.name || '').slice(0, 28).padEnd(30));+ io.out.line(l.mint ? `${l.mint.slice(0, 6)}...${l.mint.slice(-4)}` : '', 'dim');+ }+ return 0;+ }+ } catch (e) {+ return usageErr(io, `three ${sub}: ${e.message}`);+ }+ return usageErr(io, 'usage: three price | three agents [n] | three launches');+ },++ async neofetch(args, env, io) {+ const si = env.host?.sysinfo?.() || {};+ const wins = env.host?.windows?.() || [];+ const rows = [+ ['OS', 'three.ws Desktop'],+ ['Host', si.platform || 'unknown'],+ ['Browser', si.browser || si.userAgent || 'unknown'],+ ['Uptime', formatUptime(env.host?.uptimeMs?.() ?? 0)],+ ['CPU', si.cores ? `${si.cores} logical cores` : 'unknown'],+ ['Memory', si.deviceMemory ? `${si.deviceMemory} GB (reported, capped by the browser)` : 'not reported by this browser'],+ ['GPU', si.gpu || 'unavailable'],+ ['Screen', si.screen || 'unknown'],+ ['Language', si.language || 'unknown'],+ ['Windows', String(wins.length)],+ ['Theme', si.theme || 'unknown'],+ ];+ const art = [' _ _ ', ' | |_| |_ _ _ ___ ___ ', ' | _| \' \\ \'_/ -_) -_) ', ' \\__|_||_|_| \\___\\___| ', ' ', ' three.ws desktop '];+ rows.forEach((r, i) => {+ io.out.write((art[i] ?? ' '.repeat(26)).padEnd(28), 'acc');+ io.out.write(`${r[0].padEnd(10)}`, 'ok');+ io.out.line(r[1]);+ });+ return 0;+ },+};++async function headTail(args, env, io, head) {+ const name = head ? 'head' : 'tail';+ let n = 10;+ const files = [];+ for (let i = 0; i < args.length; i++) {+ if (args[i] === '-n' && args[i + 1]) n = parseInt(args[++i], 10);+ else if (/^-\d+$/.test(args[i])) n = parseInt(args[i].slice(1), 10);+ else files.push(args[i]);+ }+ if (!Number.isFinite(n) || n < 0) return usageErr(io, `${name}: invalid line count`);+ try {+ const l = lines(await readInput(env, io, files));+ for (const x of head ? l.slice(0, n) : l.slice(Math.max(0, l.length - n))) io.out.line(x);+ return 0;+ } catch (e) {+ return usageErr(io, `${name}: ${e.message}`);+ }+}++COMMAND_NAMES.push(...Object.keys(COMMANDS));++/** Build the default environment from injected parts. */+export function createEnv({ fs, fetch, now = () => new Date(), perfNow = () => performance.now(), host = {}, baseUrl = 'https://three.ws/', vars = {}, history = [] }) {+ return {+ fs, fetch, now, perfNow, host, baseUrl, history,+ cwd: '/',+ vars: { USER: host.userName?.() || 'guest', HOME: '/', SHELL: 'tws-sh', TERM: 'xterm-256color', ...vars },+ };+}++/**+ * Run one command line. Returns { out: Out, code, cleared }.+ * `signal` aborts long commands (Ctrl+C).+ */+export async function runLine(line, env, { signal } = {}) {+ const out = new Out();+ const result = { out, code: 0, cleared: false };+ const trimmed = line.trim();+ if (!trimmed) return result;+ let stages;+ try {+ stages = parseLine(trimmed);+ } catch (e) {+ out.line(e.message, 'err');+ result.code = 2;+ return result;+ }+ let stdin = null;+ for (let i = 0; i < stages.length; i++) {+ const { argv, redirect } = stages[i];+ const [name, ...args] = argv;+ const fn = COMMANDS[name];+ const last = i === stages.length - 1;+ const stageOut = new Out();+ const io = { out: stageOut, stdin, signal, cleared: false };+ if (!fn) {+ const s = suggest(name);+ out.line(`${name}: command not found${s ? `. Did you mean "${s}"?` : '. Type help for the list of commands.'}`, 'err');+ result.code = 127;+ return result;+ }+ try {+ result.code = (await fn(args, env, io)) ?? 0;+ } catch (e) {+ stageOut.line(`${name}: ${e?.message || e}`, 'err');+ result.code = 1;+ }+ if (io.cleared) result.cleared = true;+ if (redirect) {+ const p = resolvePath(env, redirect.target);+ try {+ let text = stageOut.text();+ if (redirect.mode === 'append') {+ const prev = (await env.fs.stat(p)) ? await env.fs.readText(p) : '';+ text = prev + text;+ }+ await env.fs.write(p, text);+ stdin = '';+ } catch (e) {+ out.line(`${redirect.target}: ${e.message}`, 'err');+ result.code = 1;+ return result;+ }+ if (last) break;+ } else if (last) out.segs.push(...stageOut.segs);+ else stdin = stageOut.text();+ if (result.code === 127) break;+ }+ return result;+}++/**+ * Tab completion. Returns { start, matches } where `start` is the index in+ * `line` where the completed word begins and `matches` are full replacement+ * words (folders end with "/").+ */+export async function complete(line, env) {+ const m = line.match(/(?:^|[\s|>])([^\s|>]*)$/);+ const word = m ? m[1] : '';+ const start = line.length - word.length;+ const before = line.slice(0, start);+ const isCommand = !/\S/.test(before.replace(/^.*\|/, '')) && !before.trimEnd().endsWith('>');+ if (isCommand) return { start, matches: COMMAND_NAMES.filter((c) => c.startsWith(word)).sort() };+ const slash = word.lastIndexOf('/');+ const dirPart = slash >= 0 ? word.slice(0, slash + 1) : '';+ const base = slash >= 0 ? word.slice(slash + 1) : word;+ let items = [];+ try {+ const dir = resolvePath(env, dirPart || '.');+ items = await env.fs.list(dir);+ } catch {+ items = [];+ }+ const matches = items.filter((n) => n.name.toLowerCase().startsWith(base.toLowerCase())).map((n) => dirPart + n.name + (n.type === 'dir' ? '/' : ''));+ return { start, matches };+}++export function commonPrefix(list) {+ if (!list.length) return '';+ let p = list[0];+ for (const s of list) while (!s.startsWith(p)) p = p.slice(0, -1);+ return p;+}diff --git a/src/desktop/os/apps/terminal.css b/src/desktop/os/apps/terminal.cssnew file mode 100644index 000000000..facf37d71--- /dev/null+++ b/src/desktop/os/apps/terminal.css@@ -0,0 +1,16 @@+.napp-terminal { height: 100%; display: flex; flex-direction: column; background: #0c0e12; color: #d7dae0; font: 13px/1.5 ui-monospace, 'JetBrains Mono', 'Cascadia Code', Menlo, Consolas, monospace; }+.napp-terminal .napp-terminal-root { flex: 1; min-height: 0; display: flex; flex-direction: column; outline: 0; }+.napp-terminal .tm-screen { flex: 1; min-height: 0; overflow-y: auto; padding: 10px 14px 14px; user-select: text; -webkit-user-select: text; cursor: text; scrollbar-width: thin; scrollbar-color: #3a3f4a transparent; }+.napp-terminal .tm-row { white-space: pre-wrap; overflow-wrap: anywhere; min-height: 1.5em; }+.napp-terminal .tm-prompt-row { display: flex; gap: 8px; align-items: baseline; }+.napp-terminal .tm-prompt-row[hidden] { display: none; }+.napp-terminal .tm-prompt { color: #5be4a0; white-space: nowrap; flex: none; max-width: 60%; overflow: hidden; text-overflow: ellipsis; }+.napp-terminal .tm-input { flex: 1; min-width: 0; background: transparent; border: 0; outline: 0; color: #fff; font: inherit; padding: 0; caret-color: var(--accent, #4cc2ff); user-select: text; -webkit-user-select: text; }+.napp-terminal .tm-input:focus-visible { outline: 0; }+.napp-terminal .tm-ok { color: #5be4a0; }+.napp-terminal .tm-err { color: #ff7b7b; }+.napp-terminal .tm-warn { color: #f4c05a; }+.napp-terminal .tm-dim { color: #7d8594; }+.napp-terminal .tm-acc { color: #6cc7ff; }+.napp-terminal .tm-dir { color: #8ab4ff; font-weight: 600; }+.napp-terminal .tm-screen::selection, .napp-terminal .tm-screen *::selection { background: rgba(108, 199, 255, 0.35); }diff --git a/src/desktop/os/apps/terminal.js b/src/desktop/os/apps/terminal.jsnew file mode 100644index 000000000..c88d58234--- /dev/null+++ b/src/desktop/os/apps/terminal.js@@ -0,0 +1,246 @@+// Terminal: a real command line over the virtual file system and the live+// three.ws APIs. Parsing and commands live in term-commands.js.+import './terminal.css';+import { createEnv, runLine, complete, commonPrefix } from './term-commands.js';++const HIST_KEY = 'tws:term:history';+const MAX_LINES = 3000;+const T0 = performance.now();++function gpuName() {+ try {+ const gl = document.createElement('canvas').getContext('webgl');+ const ext = gl?.getExtension('WEBGL_debug_renderer_info');+ return ext ? gl.getParameter(ext.UNMASKED_RENDERER_WEBGL) : null;+ } catch {+ return null;+ }+}++function browserName(ua) {+ const m = ua.match(/(Edg|OPR|Firefox|Chrome|Safari)\/([\d.]+)/);+ if (!m) return ua;+ const n = { Edg: 'Edge', OPR: 'Opera' }[m[1]] || m[1];+ return `${n} ${m[2].split('.')[0]}`;+}++export async function mount(host, ctx) {+ const { h } = ctx;+ let appList = [];+ try {+ appList = (await import('../registry.js')).OS_APPS.map((a) => ({ id: a.id, title: a.title }));+ } catch {+ appList = [];+ }+ let history = [];+ try {+ history = JSON.parse(ctx.store.get(HIST_KEY) || '[]').filter((x) => typeof x === 'string').slice(-200);+ } catch {+ history = [];+ }++ const root = h('div', 'napp-terminal-root');+ const screen = h('div', 'tm-screen');+ screen.tabIndex = -1;+ const promptRow = h('div', 'tm-row tm-prompt-row');+ const promptEl = h('span', 'tm-prompt');+ const input = h('input', 'tm-input');+ input.type = 'text';+ input.spellcheck = false;+ input.autocomplete = 'off';+ input.autocapitalize = 'off';+ input.setAttribute('aria-label', 'Terminal command line');+ promptRow.append(promptEl, input);+ screen.append(promptRow);+ root.append(screen);+ host.append(root);++ const host_ = {+ openPath: (p) => ctx.openPath(p),+ launchId: (id, o) => ctx.launchId(id, o),+ apps: appList,+ windows: () => ctx.windows().map((w) => ({ id: w.id, title: w.title })),+ closeWindow: (id) => ctx.closeWindow(id),+ userName: () => String(ctx.prefs?.name || 'guest').replace(/\s+/g, '_'),+ uptimeMs: () => performance.now() - T0,+ clear: () => clearScreen(),+ setTheme(mode) {+ ctx.setPrefs({ mode });+ },+ sysinfo() {+ const nav = navigator;+ return {+ platform: nav.userAgentData?.platform || nav.platform,+ userAgent: nav.userAgent,+ browser: browserName(nav.userAgent),+ cores: nav.hardwareConcurrency,+ deviceMemory: nav.deviceMemory,+ gpu: gpuName(),+ screen: `${screen_.width}x${screen_.height} @${devicePixelRatio}x`,+ language: nav.language,+ theme: document.documentElement.getAttribute('data-theme'),+ };+ },+ };+ const screen_ = window.screen;+ const env = createEnv({+ fs: ctx.fs,+ fetch: (...a) => window.fetch(...a),+ host: host_,+ baseUrl: location.origin + '/',+ history,+ });++ const promptText = () => `${host_.userName()}@three.ws:${env.cwd === '/' ? '~' : env.cwd}$`;+ const refreshPrompt = () => {+ promptEl.textContent = promptText();+ };++ function addLine(segs, extraCls = '') {+ const row = h('div', `tm-row ${extraCls}`);+ for (const s of segs) {+ const span = document.createElement('span');+ if (s.c) span.className = `tm-${s.c}`;+ span.textContent = s.t;+ row.append(span);+ }+ screen.insertBefore(row, promptRow);+ while (screen.children.length > MAX_LINES) screen.firstElementChild.remove();+ return row;+ }+ function print(segs) {+ // split segments on newlines so each visual line is its own row+ let cur = [];+ const flush = () => {+ addLine(cur.length ? cur : [{ t: ' ', c: '' }]);+ cur = [];+ };+ for (const s of segs) {+ const parts = s.t.split('\n');+ parts.forEach((p, i) => {+ if (i > 0) flush();+ if (p) cur.push({ t: p, c: s.c });+ });+ }+ if (cur.length) flush();+ }+ function clearScreen() {+ [...screen.children].forEach((c) => c !== promptRow && c.remove());+ }+ const scrollEnd = () => {+ screen.scrollTop = screen.scrollHeight;+ };++ print([{ t: 'three.ws terminal', c: 'acc' }]);+ print([{ t: 'Type help for commands. Tab completes, Up and Down browse history, Ctrl+C cancels.', c: 'dim' }]);+ refreshPrompt();++ let running = null;+ let hi = history.length;+ let draft = '';+ let lastTab = '';++ async function exec(line) {+ addLine([{ t: promptText(), c: 'ok' }, { t: ` ${line}`, c: '' }]);+ if (line.trim()) {+ if (history[history.length - 1] !== line) history.push(line);+ history.length > 200 && history.splice(0, history.length - 200);+ ctx.store.set(HIST_KEY, JSON.stringify(history));+ }+ hi = history.length;+ draft = '';+ const ac = new AbortController();+ running = ac;+ promptRow.hidden = true;+ const r = await runLine(line, env, { signal: ac.signal });+ running = null;+ if (!ac.signal.aborted && !r.cleared) print(r.out.segs);+ else if (r.cleared) clearScreen();+ promptRow.hidden = false;+ refreshPrompt();+ input.focus();+ scrollEnd();+ }++ input.addEventListener('keydown', async (e) => {+ if (e.key === 'Enter') {+ e.preventDefault();+ const v = input.value;+ input.value = '';+ lastTab = '';+ exec(v);+ } else if (e.key === 'ArrowUp') {+ e.preventDefault();+ if (hi === history.length) draft = input.value;+ if (hi > 0) input.value = history[--hi];+ } else if (e.key === 'ArrowDown') {+ e.preventDefault();+ if (hi < history.length) {+ hi++;+ input.value = hi === history.length ? draft : history[hi];+ }+ } else if (e.key === 'Tab') {+ e.preventDefault();+ const before = input.value.slice(0, input.selectionStart);+ const after = input.value.slice(input.selectionStart);+ const { start, matches } = await complete(before, env);+ if (!matches.length) return;+ const pre = commonPrefix(matches);+ if (matches.length === 1) {+ const full = matches[0] + (matches[0].endsWith('/') ? '' : ' ');+ input.value = before.slice(0, start) + full + after;+ const pos = start + full.length;+ input.setSelectionRange(pos, pos);+ } else {+ if (pre.length > before.length - start) {+ input.value = before.slice(0, start) + pre + after;+ const pos = start + pre.length;+ input.setSelectionRange(pos, pos);+ } else if (lastTab === before) {+ addLine([{ t: promptText(), c: 'ok' }, { t: ` ${input.value}`, c: '' }]);+ print([{ t: matches.map((m) => m.split('/').filter(Boolean).pop() + (m.endsWith('/') ? '/' : '')).join(' '), c: 'dim' }]);+ scrollEnd();+ }+ lastTab = before;+ return;+ }+ lastTab = '';+ } else if (e.ctrlKey && e.key.toLowerCase() === 'l') {+ e.preventDefault();+ clearScreen();+ } else if (e.ctrlKey && e.key.toLowerCase() === 'c' && input.selectionStart === input.selectionEnd) {+ e.preventDefault();+ addLine([{ t: promptText(), c: 'ok' }, { t: ` ${input.value}^C`, c: '' }]);+ input.value = '';+ } else if (e.ctrlKey && e.key.toLowerCase() === 'u') {+ e.preventDefault();+ input.value = input.value.slice(input.selectionStart);+ }+ if (e.key !== 'Tab') lastTab = '';+ });++ // Ctrl+C while a command runs: the input is hidden, so listen on the root.+ root.addEventListener('keydown', (e) => {+ if (running && e.ctrlKey && e.key.toLowerCase() === 'c' && !String(getSelection())) {+ e.preventDefault();+ running.abort();+ addLine([{ t: '^C', c: 'err' }]);+ }+ });+ root.tabIndex = -1;++ // Clicking the output focuses the prompt unless the user is selecting text.+ screen.addEventListener('mouseup', () => {+ if (!String(getSelection())) input.focus();+ });++ const first = ctx.arg;+ const run = (a) => typeof a === 'string' && a.trim() && exec(a);+ ctx.onArg?.((a) => run(a));+ if (typeof first === 'string') run(first);+ requestAnimationFrame(() => input.focus());++ return () => {+ running?.abort();+ };+}diff --git a/src/desktop/os/apps/unit-convert.js b/src/desktop/os/apps/unit-convert.jsnew file mode 100644index 000000000..9cbfed733--- /dev/null+++ b/src/desktop/os/apps/unit-convert.js@@ -0,0 +1,54 @@+// Pure unit table for the Calculator's Converter mode. Linear categories carry a factor to the+// category's base unit; temperature uses explicit to/from functions.++export const CATEGORIES = {+ length: { label: 'Length', base: 'm', units: {+ mm: ['Millimeters', 0.001], cm: ['Centimeters', 0.01], m: ['Meters', 1], km: ['Kilometers', 1000],+ in: ['Inches', 0.0254], ft: ['Feet', 0.3048], yd: ['Yards', 0.9144], mi: ['Miles', 1609.344], nmi: ['Nautical miles', 1852],+ } },+ mass: { label: 'Mass', base: 'kg', units: {+ mg: ['Milligrams', 1e-6], g: ['Grams', 0.001], kg: ['Kilograms', 1], t: ['Metric tons', 1000],+ oz: ['Ounces', 0.028349523125], lb: ['Pounds', 0.45359237], st: ['Stone', 6.35029318],+ } },+ temperature: { label: 'Temperature', base: 'C', units: {+ C: ['Celsius', null], F: ['Fahrenheit', null], K: ['Kelvin', null],+ } },+ area: { label: 'Area', base: 'm2', units: {+ mm2: ['Square millimeters', 1e-6], cm2: ['Square centimeters', 1e-4], m2: ['Square meters', 1], ha: ['Hectares', 10000],+ km2: ['Square kilometers', 1e6], in2: ['Square inches', 0.00064516], ft2: ['Square feet', 0.09290304], ac: ['Acres', 4046.8564224], mi2: ['Square miles', 2589988.110336],+ } },+ volume: { label: 'Volume', base: 'l', units: {+ ml: ['Milliliters', 0.001], l: ['Liters', 1], m3: ['Cubic meters', 1000], tsp: ['Teaspoons (US)', 0.00492892159375],+ tbsp: ['Tablespoons (US)', 0.01478676478125], floz: ['Fluid ounces (US)', 0.0295735295625], cup: ['Cups (US)', 0.2365882365],+ pt: ['Pints (US)', 0.473176473], qt: ['Quarts (US)', 0.946352946], gal: ['Gallons (US)', 3.785411784], ft3: ['Cubic feet', 28.316846592],+ } },+ speed: { label: 'Speed', base: 'ms', units: {+ ms: ['Meters per second', 1], kmh: ['Kilometers per hour', 1 / 3.6], mph: ['Miles per hour', 0.44704], kn: ['Knots', 1852 / 3600], fts: ['Feet per second', 0.3048], mach: ['Mach (sea level)', 340.29],+ } },+ time: { label: 'Time', base: 's', units: {+ ms: ['Milliseconds', 0.001], s: ['Seconds', 1], min: ['Minutes', 60], h: ['Hours', 3600], d: ['Days', 86400], wk: ['Weeks', 604800], mo: ['Months (30.44 d)', 2629746], yr: ['Years (365.25 d)', 31557600],+ } },+ data: { label: 'Data', base: 'B', units: {+ bit: ['Bits', 0.125], B: ['Bytes', 1], KB: ['Kilobytes', 1e3], MB: ['Megabytes', 1e6], GB: ['Gigabytes', 1e9], TB: ['Terabytes', 1e12],+ KiB: ['Kibibytes', 1024], MiB: ['Mebibytes', 1048576], GiB: ['Gibibytes', 1073741824], TiB: ['Tebibytes', 1099511627776],+ } },+};++const toCelsius = { C: (v) => v, F: (v) => ((v - 32) * 5) / 9, K: (v) => v - 273.15 };+const fromCelsius = { C: (v) => v, F: (v) => (v * 9) / 5 + 32, K: (v) => v + 273.15 };++/** Convert `value` between two units of one category. Throws on unknown units. */+export function convert(category, from, to, value) {+ const cat = CATEGORIES[category];+ if (!cat) throw new Error(`Unknown category ${category}`);+ if (!(from in cat.units) || !(to in cat.units)) throw new Error('Unknown unit');+ if (!Number.isFinite(value)) throw new Error('Enter a number');+ if (category === 'temperature') {+ const c = toCelsius[from](value);+ if (c < -273.15 - 1e-9) throw new Error('Below absolute zero');+ return fromCelsius[to](c);+ }+ return (value * cat.units[from][1]) / cat.units[to][1];+}++export const unitKeys = (category) => Object.keys(CATEGORIES[category].units);diff --git a/src/desktop/os/apps/weather-codes.js b/src/desktop/os/apps/weather-codes.jsnew file mode 100644index 000000000..7d74f34ea--- /dev/null+++ b/src/desktop/os/apps/weather-codes.js@@ -0,0 +1,57 @@+// WMO weather interpretation codes (Open-Meteo) mapped to labels and icon kinds. Pure data.++const T = {+ 0: ['Clear sky', 'clear'],+ 1: ['Mainly clear', 'clear'],+ 2: ['Partly cloudy', 'partly'],+ 3: ['Overcast', 'cloud'],+ 45: ['Fog', 'fog'],+ 48: ['Freezing fog', 'fog'],+ 51: ['Light drizzle', 'drizzle'],+ 53: ['Drizzle', 'drizzle'],+ 55: ['Heavy drizzle', 'drizzle'],+ 56: ['Light freezing drizzle', 'drizzle'],+ 57: ['Freezing drizzle', 'drizzle'],+ 61: ['Light rain', 'rain'],+ 63: ['Rain', 'rain'],+ 65: ['Heavy rain', 'rain'],+ 66: ['Light freezing rain', 'rain'],+ 67: ['Freezing rain', 'rain'],+ 71: ['Light snow', 'snow'],+ 73: ['Snow', 'snow'],+ 75: ['Heavy snow', 'snow'],+ 77: ['Snow grains', 'snow'],+ 80: ['Light showers', 'rain'],+ 81: ['Showers', 'rain'],+ 82: ['Violent showers', 'rain'],+ 85: ['Light snow showers', 'snow'],+ 86: ['Snow showers', 'snow'],+ 95: ['Thunderstorm', 'storm'],+ 96: ['Thunderstorm with hail', 'storm'],+ 99: ['Severe thunderstorm with hail', 'storm'],+};++/** { label, kind, night } for a WMO code. `isDay` false picks the night variant of clear and partly. */+export function describe(code, isDay = true) {+ const [label, kind] = T[code] || ['Unknown', 'cloud'];+ const night = !isDay;+ let l = label;+ if (night && code === 0) l = 'Clear night';+ if (night && code === 1) l = 'Mainly clear night';+ return { label: l, kind, night };+}++/** Compass point for a wind direction in degrees. */+export function compass(deg) {+ const pts = ['N', 'NNE', 'NE', 'ENE', 'E', 'ESE', 'SE', 'SSE', 'S', 'SSW', 'SW', 'WSW', 'W', 'WNW', 'NW', 'NNW'];+ return pts[Math.round((((deg % 360) + 360) % 360) / 22.5) % 16];+}++/** UV index category label. */+export function uvLabel(uv) {+ if (uv < 3) return 'Low';+ if (uv < 6) return 'Moderate';+ if (uv < 8) return 'High';+ if (uv < 11) return 'Very high';+ return 'Extreme';+}diff --git a/src/desktop/os/apps/weather-data.js b/src/desktop/os/apps/weather-data.jsnew file mode 100644index 000000000..faeba9e34--- /dev/null+++ b/src/desktop/os/apps/weather-data.js@@ -0,0 +1,168 @@+// Open-Meteo data layer (no API key). Shared by the Weather app and the shell's Widgets board.+// fetchWeather(lat, lon, unit) -> normalised forecast, falling back to the last cached response offline+// searchCity(query) -> geocoding results+// describeWeather(code, isDay) -> { label, kind, night }+// loadPlaces and savePlaces -> saved cities in localStorage+// currentPlace() -> the selected saved city, or null++import { describe } from './weather-codes.js';++export { describe as describeWeather };++const PLACES_KEY = 'tws:weather:places';+const SELECTED_KEY = 'tws:weather:selected';+const CACHE_PREFIX = 'tws:weather:cache:';++const ls = {+ get(k) {+ try {+ return localStorage.getItem(k);+ } catch {+ return null;+ }+ },+ set(k, v) {+ try {+ localStorage.setItem(k, v);+ } catch {+ /* storage unavailable or full: the cache is a convenience */+ }+ },+};++export function loadPlaces() {+ try {+ const v = JSON.parse(ls.get(PLACES_KEY) || '[]');+ return Array.isArray(v) ? v.filter((p) => p && Number.isFinite(p.lat) && Number.isFinite(p.lon)) : [];+ } catch {+ return [];+ }+}++export function savePlaces(places) {+ ls.set(PLACES_KEY, JSON.stringify(places));+}++export const placeId = (p) => `${p.lat.toFixed(2)},${p.lon.toFixed(2)}`;++export function selectPlace(p) {+ ls.set(SELECTED_KEY, p ? placeId(p) : '');+}++export function currentPlace() {+ const places = loadPlaces();+ if (!places.length) return null;+ const id = ls.get(SELECTED_KEY);+ return places.find((p) => placeId(p) === id) || places[0];+}++export function loadUnit() {+ return ls.get('tws:weather:unit') === 'F' ? 'F' : 'C';+}+export function saveUnit(u) {+ ls.set('tws:weather:unit', u === 'F' ? 'F' : 'C');+}++/** Geocoding search. Returns [{ name, admin1, country, lat, lon, tz }]. Throws on network failure. */+export async function searchCity(query, { signal } = {}) {+ const q = String(query).trim();+ if (q.length < 2) return [];+ const url = `https://geocoding-api.open-meteo.com/v1/search?name=${encodeURIComponent(q)}&count=8&language=en&format=json`;+ const r = await fetch(url, { signal });+ if (!r.ok) throw new Error(`Search failed (HTTP ${r.status})`);+ const j = await r.json();+ return (j.results || []).map((x) => ({ name: x.name, admin1: x.admin1 || '', country: x.country || '', lat: x.latitude, lon: x.longitude, tz: x.timezone || '' }));+}++const cacheKey = (lat, lon, unit) => `${CACHE_PREFIX}${lat.toFixed(2)},${lon.toFixed(2)},${unit}`;++export function cachedWeather(lat, lon, unit) {+ try {+ const raw = ls.get(cacheKey(lat, lon, unit));+ return raw ? JSON.parse(raw) : null;+ } catch {+ return null;+ }+}++/**+ * Forecast for a point. `unit` is 'C' (km/h) or 'F' (mph). On network failure resolves with the last+ * cached response marked `{ stale: true }` when one exists, otherwise throws.+ */+export async function fetchWeather(lat, lon, unit = 'C', { signal } = {}) {+ const f = unit === 'F';+ const q = new URLSearchParams({+ latitude: String(lat),+ longitude: String(lon),+ current: 'temperature_2m,relative_humidity_2m,apparent_temperature,is_day,precipitation,weather_code,wind_speed_10m,wind_direction_10m,surface_pressure',+ hourly: 'temperature_2m,precipitation_probability,weather_code,is_day',+ daily: 'weather_code,temperature_2m_max,temperature_2m_min,sunrise,sunset,uv_index_max,precipitation_probability_max,wind_speed_10m_max',+ timezone: 'auto',+ forecast_days: '7',+ temperature_unit: f ? 'fahrenheit' : 'celsius',+ wind_speed_unit: f ? 'mph' : 'kmh',+ });+ try {+ const r = await fetch(`https://api.open-meteo.com/v1/forecast?${q}`, { signal });+ if (!r.ok) throw new Error(`Forecast failed (HTTP ${r.status})`);+ const data = normalise(await r.json(), unit);+ ls.set(cacheKey(lat, lon, unit), JSON.stringify(data));+ return data;+ } catch (err) {+ if (err?.name === 'AbortError') throw err;+ const hit = cachedWeather(lat, lon, unit);+ if (hit) return { ...hit, stale: true };+ throw err;+ }+}++/** Shape the raw API response into rows the UI can render directly. */+export function normalise(j, unit) {+ const c = j.current || {};+ const d = j.daily || {};+ const hh = j.hourly || {};+ const daily = (d.time || []).map((date, i) => ({+ date,+ code: d.weather_code[i],+ max: d.temperature_2m_max[i],+ min: d.temperature_2m_min[i],+ sunrise: d.sunrise[i],+ sunset: d.sunset[i],+ uv: d.uv_index_max[i],+ rain: d.precipitation_probability_max[i],+ wind: d.wind_speed_10m_max[i],+ }));+ // Hourly rows from the current hour onward, 24 of them.+ const curHour = (c.time || '').slice(0, 13);+ let start = (hh.time || []).findIndex((t) => t.slice(0, 13) >= curHour);+ if (start < 0) start = 0;+ const hourly = (hh.time || []).slice(start, start + 24).map((time, k) => ({+ time,+ temp: hh.temperature_2m[start + k],+ rain: hh.precipitation_probability[start + k],+ code: hh.weather_code[start + k],+ isDay: !!hh.is_day[start + k],+ }));+ return {+ unit,+ fetchedAt: Date.now(),+ tz: j.timezone,+ current: {+ time: c.time,+ temp: c.temperature_2m,+ feels: c.apparent_temperature,+ humidity: c.relative_humidity_2m,+ code: c.weather_code,+ isDay: !!c.is_day,+ precip: c.precipitation,+ wind: c.wind_speed_10m,+ windDir: c.wind_direction_10m,+ pressure: c.surface_pressure,+ },+ hourly,+ daily,+ units: { wind: unit === 'F' ? 'mph' : 'km/h', precip: 'mm' },+ };+}++export const placeLabel = (p) => [p.name, p.admin1 && p.admin1 !== p.name ? p.admin1 : '', p.country].filter(Boolean).slice(0, 2).join(', ');diff --git a/src/desktop/os/apps/weather.css b/src/desktop/os/apps/weather.cssnew file mode 100644index 000000000..c8bddf03d--- /dev/null+++ b/src/desktop/os/apps/weather.css@@ -0,0 +1,80 @@+.napp-weather { display: flex; flex-direction: column; min-height: 0; background: var(--card); color: var(--text); }+.napp-weather .wx { flex: 1; display: flex; flex-direction: column; min-height: 0; }+.napp-weather .wx-bar { display: flex; align-items: center; gap: 8px; padding: 8px 12px; border-bottom: 1px solid var(--bd); flex-wrap: wrap; }+.napp-weather .wx-grow { flex: 1; }+.napp-weather [hidden] { display: none !important; }+.napp-weather .wx-sel, .napp-weather .wx-in { background: var(--hover); color: var(--text); border: 1px solid var(--bd); border-radius: 6px; padding: 6px 10px; font: inherit; font-size: 0.88rem; max-width: 240px; }+.napp-weather .wx-btn, .napp-weather .wx-secondary { border: 1px solid var(--bd); background: transparent; color: var(--text); border-radius: 6px; padding: 6px 12px; font: inherit; font-size: 0.85rem; cursor: pointer; }+.napp-weather .wx-btn:hover, .napp-weather .wx-secondary:hover { background: var(--hover); }+.napp-weather .wx-primary { border: 0; background: var(--accent); color: #fff; border-radius: 6px; padding: 8px 18px; font: inherit; font-weight: 600; cursor: pointer; }+.napp-weather .wx-primary:hover { filter: brightness(1.12); }+.napp-weather .wx-primary:active, .napp-weather .wx-btn:active, .napp-weather .wx-secondary:active { transform: scale(0.97); }+.napp-weather button:focus-visible, .napp-weather select:focus-visible, .napp-weather input:focus-visible, .napp-weather .wx-hours:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }+.napp-weather .wx-seg { display: inline-flex; background: var(--hover); border-radius: 999px; padding: 2px; }+.napp-weather .wx-seg button { border: 0; background: transparent; color: var(--text2); border-radius: 999px; padding: 4px 12px; font: inherit; font-size: 0.85rem; cursor: pointer; }+.napp-weather .wx-seg button.on { background: var(--accent); color: #fff; }+.napp-weather .wx-body { flex: 1; min-height: 0; overflow-y: auto; padding: 14px 16px 20px; }+.napp-weather .wx-body section { margin-top: 18px; }+.napp-weather h2 { margin: 0; font-size: 1.15rem; }+.napp-weather h3 { margin: 0 0 8px; font-size: 0.78rem; text-transform: uppercase; letter-spacing: 0.06em; color: var(--text2); }+.napp-weather .wx-hero { display: flex; align-items: center; justify-content: space-between; gap: 16px; border-radius: 14px; padding: 20px 24px; color: #fff; background: linear-gradient(135deg, #3b8be0, #6fb6f5); }+.napp-weather .wx-hero.night, .napp-weather .wx-hero.clear.night { background: linear-gradient(135deg, #16213e, #34497a); }+.napp-weather .wx-hero.cloud, .napp-weather .wx-hero.fog { background: linear-gradient(135deg, #6b7b92, #98a8bd); }+.napp-weather .wx-hero.rain, .napp-weather .wx-hero.drizzle { background: linear-gradient(135deg, #43587a, #6b86ad); }+.napp-weather .wx-hero.storm { background: linear-gradient(135deg, #2c3550, #4d5a7e); }+.napp-weather .wx-hero.snow { background: linear-gradient(135deg, #7d9cc3, #b4cbe6); }+.napp-weather .wx-place { font-size: 1.05rem; font-weight: 600; }+.napp-weather .wx-temp { font-size: 4.2rem; font-weight: 300; line-height: 1; margin: 6px 0; }+.napp-weather .wx-temp small { font-size: 1.3rem; vertical-align: top; margin-left: 4px; opacity: 0.8; }+.napp-weather .wx-cond { font-size: 1.1rem; }+.napp-weather .wx-hl { font-size: 0.85rem; opacity: 0.9; margin-top: 4px; }+.napp-weather .wx-updated, .napp-weather .wx-credit { font-size: 0.75rem; color: var(--text2); margin: 8px 2px 0; }+.napp-weather .wx-stale { margin-top: 10px; padding: 9px 12px; border-radius: 8px; background: #f5a62326; border: 1px solid #f5a62366; font-size: 0.85rem; }+.napp-weather .wx-hours { display: flex; gap: 6px; overflow-x: auto; padding-bottom: 6px; }+.napp-weather .wx-hour { flex: none; width: 62px; display: flex; flex-direction: column; align-items: center; gap: 4px; padding: 8px 4px; border-radius: 10px; background: var(--hover); font-size: 0.8rem; }+.napp-weather .wx-hour em { font-style: normal; font-size: 0.7rem; color: #4aa3ff; min-height: 1em; }+.napp-weather .wx-days { list-style: none; margin: 0; padding: 0; }+.napp-weather .wx-days li { display: grid; grid-template-columns: 56px 30px 38px 36px 1fr 36px; align-items: center; gap: 6px; padding: 6px 0; border-bottom: 1px solid var(--bd); font-size: 0.88rem; }+.napp-weather .wx-days .rain { color: #4aa3ff; font-size: 0.75rem; }+.napp-weather .wx-days .lo { text-align: right; color: var(--text2); }+.napp-weather .wx-days .bar { position: relative; height: 5px; border-radius: 3px; background: var(--hover); }+.napp-weather .wx-days .bar i { position: absolute; top: 0; bottom: 0; border-radius: 3px; background: linear-gradient(90deg, #4aa3ff, #ffb23f); }+.napp-weather .wx-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(140px, 1fr)); gap: 8px; }+.napp-weather .wx-tile { background: var(--hover); border-radius: 10px; padding: 10px 12px; display: flex; flex-direction: column; gap: 2px; }+.napp-weather .wx-tile span { font-size: 0.72rem; text-transform: uppercase; letter-spacing: 0.05em; color: var(--text2); }+.napp-weather .wx-tile b { font-size: 1.2rem; font-weight: 600; }+.napp-weather .wx-tile em { font-style: normal; font-size: 0.78rem; color: var(--text2); }+.napp-weather .wx-state, .napp-weather .wx-search { max-width: 420px; margin: 40px auto; display: flex; flex-direction: column; align-items: center; text-align: center; gap: 10px; }+.napp-weather .wx-search { align-items: stretch; text-align: left; margin-top: 20px; }+.napp-weather .wx-state p, .napp-weather .wx-note { margin: 0; color: var(--text2); font-size: 0.9rem; line-height: 1.5; }+.napp-weather .wx-detail { font-size: 0.78rem !important; opacity: 0.8; }+.napp-weather .wx-actions { display: flex; gap: 8px; flex-wrap: wrap; justify-content: center; margin-top: 6px; }+.napp-weather .wx-form { display: flex; gap: 8px; }+.napp-weather .wx-form .wx-in { flex: 1; max-width: none; }+.napp-weather .wx-results { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 4px; }+.napp-weather .wx-result { width: 100%; display: flex; justify-content: space-between; gap: 12px; text-align: left; border: 1px solid var(--bd); background: transparent; color: var(--text); border-radius: 8px; padding: 9px 12px; font: inherit; cursor: pointer; }+.napp-weather .wx-result span { color: var(--text2); font-size: 0.82rem; }+.napp-weather .wx-result:hover { background: var(--hover); border-color: var(--accent); }+.napp-weather .wx-hint { color: var(--text2); font-size: 0.85rem; padding: 6px 2px; }+.napp-weather .wx-hint.err { color: #e5484d; }+.napp-weather .wx-spin-ring { width: 34px; height: 34px; border-radius: 50%; border: 3px solid var(--bd); border-top-color: var(--accent); animation: wx-rot 0.8s linear infinite; }+.napp-weather .wx-skel .sk { border-radius: 12px; background: linear-gradient(90deg, var(--hover) 25%, var(--bd) 50%, var(--hover) 75%); background-size: 200% 100%; animation: wx-shimmer 1.4s infinite; margin-bottom: 14px; }+.napp-weather .wx-skel .a { height: 170px; } .napp-weather .wx-skel .b { height: 100px; } .napp-weather .wx-skel .c { height: 200px; } .napp-weather .wx-skel .d { height: 90px; }+@keyframes wx-shimmer { to { background-position: -200% 0; } }+@keyframes wx-rot { to { transform: rotate(360deg); } }+.napp-weather .wx-ico { flex: none; overflow: visible; }+.napp-weather .wx-spin { transform-origin: 32px 32px; animation: wx-rot 24s linear infinite; }+.napp-weather .wx-drift { animation: wx-drift 6s ease-in-out infinite alternate; }+.napp-weather .wx-bob { animation: wx-drift 5s ease-in-out infinite alternate; }+.napp-weather .wx-twinkle { animation: wx-twinkle 2.4s ease-in-out infinite; }+.napp-weather .wx-drop { animation: wx-fall 0.9s linear infinite; }+.napp-weather .wx-flake { animation: wx-fall 2.2s linear infinite; }+.napp-weather .wx-bolt { animation: wx-flash 3s steps(1) infinite; }+@keyframes wx-drift { from { transform: translateX(-2px); } to { transform: translateX(3px); } }+@keyframes wx-twinkle { 50% { opacity: 0.25; } }+@keyframes wx-fall { 0% { transform: translateY(-4px); opacity: 0; } 30% { opacity: 1; } 100% { transform: translateY(8px); opacity: 0; } }+@keyframes wx-flash { 0%, 88%, 94% { opacity: 1; } 91%, 97% { opacity: 0.2; } }+@media (prefers-reduced-motion: reduce) {+ .napp-weather .wx-ico *, .napp-weather .wx-skel .sk, .napp-weather .wx-spin-ring { animation: none !important; }+}+@media (max-width: 520px) { .napp-weather .wx-hero { flex-direction: column-reverse; text-align: center; } }diff --git a/src/desktop/os/apps/weather.js b/src/desktop/os/apps/weather.jsnew file mode 100644index 000000000..cdd992e13--- /dev/null+++ b/src/desktop/os/apps/weather.js@@ -0,0 +1,298 @@+// Weather: live Open-Meteo forecast with saved cities, geolocation, a C/F toggle and animated SVG icons.+import './weather.css';+import { fetchWeather, searchCity, describeWeather, loadPlaces, savePlaces, placeId, selectPlace, currentPlace, loadUnit, saveUnit, placeLabel } from './weather-data.js';+import { compass, uvLabel } from './weather-codes.js';++const SUN = '<g class="wx-spin"><circle cx="32" cy="32" r="11" fill="#ffc533"/><g stroke="#ffc533" stroke-width="3" stroke-linecap="round"><path d="M32 8v7M32 49v7M8 32h7M49 32h7M15 15l5 5M44 44l5 5M49 15l-5 5M20 44l-5 5"/></g></g>';+const MOON = '<path class="wx-bob" d="M42 40a16 16 0 0 1-18-24 16 16 0 1 0 18 24z" fill="#d9e1f2"/><g fill="#fff" class="wx-twinkle"><circle cx="46" cy="16" r="1.6"/><circle cx="52" cy="26" r="1.2"/></g>';+const CLOUD = (fill = '#cfd8e6', y = 0) => `<g class="wx-drift"><path d="M20 ${46 + y}a9 9 0 0 1 1-18 12 12 0 0 1 23 3 8 8 0 0 1 0 15z" fill="${fill}"/></g>`;+const DROPS = (n, color = '#4aa3ff') => Array.from({ length: n }, (_, i) => `<path class="wx-drop" style="animation-delay:${i * 0.25}s" d="M${24 + i * 9} 50l-2 6" stroke="${color}" stroke-width="3" stroke-linecap="round"/>`).join('');+const FLAKES = [0, 1, 2].map((i) => `<circle class="wx-flake" style="animation-delay:${i * 0.5}s" cx="${25 + i * 10}" cy="52" r="2.4" fill="#fff"/>`).join('');+const ICONS = {+ clear: (night) => (night ? MOON : SUN),+ partly: (night) => `<g transform="translate(-8 -8) scale(.8)">${night ? MOON : SUN}</g>${CLOUD('#e4eaf4', 2)}`,+ cloud: () => `<g transform="translate(4 -6) scale(.8)">${CLOUD('#9fb0c7')}</g>${CLOUD('#d3dbe8', 4)}`,+ fog: () => `${CLOUD('#c1cad8', -4)}<g class="wx-drift" stroke="#c1cad8" stroke-width="3" stroke-linecap="round"><path d="M16 50h32M22 57h24"/></g>`,+ drizzle: () => `${CLOUD('#aab8cc', -4)}${DROPS(3, '#8cc4ff')}`,+ rain: () => `${CLOUD('#8294ad', -4)}${DROPS(4)}`,+ snow: () => `${CLOUD('#b9c5d6', -4)}${FLAKES}`,+ storm: () => `${CLOUD('#5f6f86', -4)}<path class="wx-bolt" d="M34 42l-8 12h7l-3 9 11-14h-7l4-7z" fill="#ffd23f"/>`,+};+export const iconSvg = (kind, night, size = 48) => `<svg class="wx-ico" viewBox="0 0 64 64" width="${size}" height="${size}" role="img" aria-hidden="true">${(ICONS[kind] || ICONS.cloud)(night)}</svg>`;++const WEEKDAY = new Intl.DateTimeFormat(undefined, { weekday: 'short' });+const hourFmt = (iso) => new Date(iso).toLocaleTimeString([], { hour: 'numeric' });+const timeFmt = (iso) => new Date(iso).toLocaleTimeString([], { hour: 'numeric', minute: '2-digit' });++export function mount(host, ctx) {+ const { h, esc } = ctx;+ host.classList.add('napp-weather');+ host.innerHTML = '';+ let unit = loadUnit();+ let places = loadPlaces();+ let place = currentPlace();+ let ac = null;+ let disposed = false;+ let searchAc = null;++ const root = h('div', 'wx');+ const bar = h('div', 'wx-bar');+ const body = h('div', 'wx-body');+ root.append(bar, body);+ host.append(root);++ // ---- top bar ----+ const placeSel = h('select', 'wx-sel');+ placeSel.setAttribute('aria-label', 'Saved city');+ placeSel.addEventListener('change', () => {+ if (placeSel.value === '__add') {+ placeSel.value = place ? placeId(place) : '';+ return showSearch();+ }+ const p = places.find((x) => placeId(x) === placeSel.value);+ if (p) choose(p);+ });+ const addBtn = h('button', 'wx-btn', '+ Add city');+ addBtn.type = 'button';+ addBtn.addEventListener('click', () => showSearch());+ const rmBtn = h('button', 'wx-btn', 'Remove');+ rmBtn.type = 'button';+ rmBtn.title = 'Remove this city from your saved list';+ rmBtn.addEventListener('click', () => {+ if (!place) return;+ places = places.filter((p) => placeId(p) !== placeId(place));+ savePlaces(places);+ place = places[0] || null;+ selectPlace(place);+ syncBar();+ place ? load() : showWelcome();+ });+ const reload = h('button', 'wx-btn', 'Refresh');+ reload.type = 'button';+ reload.addEventListener('click', () => place && load());+ const seg = h('div', 'wx-seg');+ seg.setAttribute('role', 'group');+ seg.setAttribute('aria-label', 'Temperature unit');+ const segBtns = ['C', 'F'].map((u) => {+ const b = h('button', '', `°${u}`);+ b.type = 'button';+ b.setAttribute('aria-label', u === 'C' ? 'Celsius' : 'Fahrenheit');+ b.addEventListener('click', () => {+ if (unit === u) return;+ unit = u;+ saveUnit(u);+ syncBar();+ if (place) load();+ });+ return b;+ });+ seg.append(...segBtns);+ bar.append(placeSel, addBtn, rmBtn, h('span', 'wx-grow'), reload, seg);+ function syncBar() {+ placeSel.replaceChildren();+ for (const p of places) {+ const o = h('option', '', esc(placeLabel(p)));+ o.value = placeId(p);+ placeSel.append(o);+ }+ const add = h('option', '', 'Add a city...');+ add.value = '__add';+ placeSel.append(add);+ if (place) placeSel.value = placeId(place);+ const has = !!place && places.some((p) => placeId(p) === placeId(place));+ placeSel.hidden = !places.length;+ rmBtn.hidden = !has;+ reload.hidden = !place;+ segBtns.forEach((b, i) => {+ const on = ['C', 'F'][i] === unit;+ b.classList.toggle('on', on);+ b.setAttribute('aria-pressed', String(on));+ });+ }++ function choose(p) {+ place = p;+ if (!places.some((x) => placeId(x) === placeId(p))) {+ places = [...places, p];+ savePlaces(places);+ }+ selectPlace(p);+ syncBar();+ load();+ }++ // ---- states ----+ function showSkeleton() {+ body.innerHTML = `<div class="wx-skel" aria-busy="true" aria-label="Loading forecast"><div class="sk a"></div><div class="sk b"></div><div class="sk c"></div><div class="sk d"></div></div>`;+ }+ function showError(err) {+ const offline = typeof navigator !== 'undefined' && navigator.onLine === false;+ body.innerHTML = `<div class="wx-state" role="alert">${iconSvg('cloud', false, 72)}<h2>${offline ? 'You are offline' : 'Weather is unavailable right now'}</h2><p>${offline ? 'Check your connection and try again. Cities you have already viewed are shown from your last update once they have loaded at least once.' : 'The forecast service did not respond. Your saved cities are safe.'}</p><p class="wx-detail">${esc(err?.message || '')}</p></div>`;+ const retry = h('button', 'wx-primary', 'Try again');+ retry.type = 'button';+ retry.addEventListener('click', () => (place ? load() : showWelcome()));+ body.querySelector('.wx-state').append(retry);+ retry.focus();+ }+ function showWelcome() {+ body.innerHTML = `<div class="wx-state">${iconSvg('partly', false, 88)}<h2>See the weather where you are</h2><p>Allow location access for a local forecast, or search for any city. Your location stays in this browser and is only sent to the forecast service as coordinates.</p><div class="wx-actions"></div></div>`;+ const acts = body.querySelector('.wx-actions');+ if (navigator.geolocation) {+ const loc = h('button', 'wx-primary', 'Use my location');+ loc.type = 'button';+ loc.addEventListener('click', locate);+ acts.append(loc);+ }+ const find = h('button', 'wx-secondary', 'Search for a city');+ find.type = 'button';+ find.addEventListener('click', () => showSearch());+ acts.append(find);+ acts.firstElementChild.focus();+ }+ function locate() {+ body.innerHTML = `<div class="wx-state"><div class="wx-spin-ring"></div><h2>Finding you...</h2><p>Choose Allow in your browser prompt.</p></div>`;+ navigator.geolocation.getCurrentPosition(+ (pos) => {+ if (disposed) return;+ const lat = Math.round(pos.coords.latitude * 100) / 100;+ const lon = Math.round(pos.coords.longitude * 100) / 100;+ choose({ name: 'My location', admin1: '', country: '', lat, lon, tz: '' });+ },+ (err) => {+ if (disposed) return;+ showSearch(err.code === 1 ? 'Location access was declined, so search for a city instead.' : 'Your location could not be determined. Search for a city instead.');+ },+ { timeout: 12000, maximumAge: 600000 },+ );+ }+ function showSearch(note = '') {+ body.innerHTML = `<div class="wx-search"><h2>Add a city</h2>${note ? `<p class="wx-note">${esc(note)}</p>` : ''}<form class="wx-form" role="search"><input class="wx-in" type="search" placeholder="Search a city, e.g. Lisbon" aria-label="City name" autocomplete="off" maxlength="80"><button class="wx-primary" type="submit">Search</button></form><ul class="wx-results" aria-live="polite"></ul></div>`;+ const form = body.querySelector('form');+ const input = body.querySelector('input');+ const list = body.querySelector('.wx-results');+ input.focus();+ let timer = 0;+ const run = async () => {+ const q = input.value.trim();+ searchAc?.abort();+ if (q.length < 2) {+ list.innerHTML = '';+ return;+ }+ searchAc = new AbortController();+ list.innerHTML = '<li class="wx-hint">Searching...</li>';+ try {+ const res = await searchCity(q, { signal: searchAc.signal });+ if (!res.length) {+ list.innerHTML = `<li class="wx-hint">No city matches "${esc(q)}". Check the spelling or try a larger nearby city.</li>`;+ return;+ }+ list.replaceChildren(+ ...res.map((r) => {+ const li = h('li');+ const b = h('button', 'wx-result', `<b>${esc(r.name)}</b><span>${esc([r.admin1, r.country].filter(Boolean).join(', '))}</span>`);+ b.type = 'button';+ b.addEventListener('click', () => choose(r));+ li.append(b);+ return li;+ }),+ );+ } catch (err) {+ if (err.name === 'AbortError') return;+ list.innerHTML = `<li class="wx-hint err">Search failed: ${esc(err.message)}. Check your connection and try again.</li>`;+ }+ };+ input.addEventListener('input', () => {+ clearTimeout(timer);+ timer = setTimeout(run, 280);+ });+ form.addEventListener('submit', (e) => {+ e.preventDefault();+ clearTimeout(timer);+ run();+ });+ if (place) {+ const back = h('button', 'wx-secondary', 'Back to forecast');+ back.type = 'button';+ back.addEventListener('click', () => load());+ body.querySelector('.wx-search').append(back);+ }+ }++ // ---- forecast ----+ async function load() {+ if (!place) return showWelcome();+ ac?.abort();+ ac = new AbortController();+ const mine = ac;+ const p = place;+ showSkeleton();+ ctx.setTitle(`${p.name} - Weather`);+ try {+ const d = await fetchWeather(p.lat, p.lon, unit, { signal: mine.signal });+ if (disposed || mine.signal.aborted) return;+ render(p, d);+ } catch (err) {+ if (err.name === 'AbortError' || disposed) return;+ showError(err);+ }+ }+ const tempOf = (v) => `${Math.round(v)}°`;+ function render(p, d) {+ const c = d.current;+ const w = describeWeather(c.code, c.isDay);+ const today = d.daily[0];+ const nowIdx = Math.max(0, d.hourly.findIndex((x) => x.time >= c.time.slice(0, 13)));+ const hours = d.hourly.slice(nowIdx, nowIdx + 24);+ const wind = d.units.wind;+ const rangeLo = Math.min(...d.daily.map((x) => x.min));+ const rangeHi = Math.max(...d.daily.map((x) => x.max));+ const span = Math.max(1, rangeHi - rangeLo);+ body.innerHTML = `+ <div class="wx-hero ${w.kind}${w.night ? ' night' : ''}">+ <div class="wx-hero-main">+ <div class="wx-place">${esc(placeLabel(p))}</div>+ <div class="wx-temp">${tempOf(c.temp)}<small>${unit}</small></div>+ <div class="wx-cond">${esc(w.label)}</div>+ <div class="wx-hl">H ${tempOf(today.max)} L ${tempOf(today.min)} Feels like ${tempOf(c.feels)}</div>+ </div>+ ${iconSvg(w.kind, w.night, 120)}+ </div>+ ${d.stale ? `<div class="wx-stale" role="status">You are offline. Showing the forecast from ${esc(new Date(d.fetchedAt).toLocaleString([], { weekday: 'short', hour: 'numeric', minute: '2-digit' }))}.</div>` : `<div class="wx-updated">Updated ${esc(new Date(d.fetchedAt).toLocaleTimeString([], { hour: 'numeric', minute: '2-digit' }))}</div>`}+ <section aria-label="Hourly forecast"><h3>Next 24 hours</h3><div class="wx-hours" tabindex="0">${hours+ .map((x, i) => {+ const hw = describeWeather(x.code, x.isDay);+ return `<div class="wx-hour"><span>${i === 0 ? 'Now' : esc(hourFmt(x.time))}</span>${iconSvg(hw.kind, hw.night, 30)}<b>${tempOf(x.temp)}</b><em>${x.rain > 0 ? `${Math.round(x.rain)}%` : ''}</em></div>`;+ })+ .join('')}</div></section>+ <section aria-label="Seven day forecast"><h3>7-day forecast</h3><ul class="wx-days">${d.daily+ .map((x, i) => {+ const dw = describeWeather(x.code, true);+ const l = ((x.min - rangeLo) / span) * 100;+ const wd = Math.max(6, ((x.max - x.min) / span) * 100);+ return `<li><span class="day">${i === 0 ? 'Today' : esc(WEEKDAY.format(new Date(`${x.date}T12:00`)))}</span>${iconSvg(dw.kind, false, 28)}<span class="rain">${x.rain > 0 ? `${Math.round(x.rain)}%` : ''}</span><span class="lo">${tempOf(x.min)}</span><span class="bar"><i style="left:${l}%;width:${wd}%"></i></span><span class="hi">${tempOf(x.max)}</span></li>`;+ })+ .join('')}</ul></section>+ <section aria-label="Details"><h3>Details</h3><div class="wx-grid">+ <div class="wx-tile"><span>Wind</span><b>${Math.round(c.wind)} ${esc(wind)}</b><em>${esc(compass(c.windDir))}</em></div>+ <div class="wx-tile"><span>Humidity</span><b>${Math.round(c.humidity)}%</b><em> </em></div>+ <div class="wx-tile"><span>UV index</span><b>${Math.round(today.uv)}</b><em>${esc(uvLabel(today.uv))}</em></div>+ <div class="wx-tile"><span>Rain chance</span><b>${Math.round(today.rain)}%</b><em>${c.precip > 0 ? `${c.precip} mm now` : 'None now'}</em></div>+ <div class="wx-tile"><span>Sunrise</span><b>${esc(timeFmt(today.sunrise))}</b><em> </em></div>+ <div class="wx-tile"><span>Sunset</span><b>${esc(timeFmt(today.sunset))}</b><em> </em></div>+ <div class="wx-tile"><span>Pressure</span><b>${Math.round(c.pressure)} hPa</b><em> </em></div>+ </div></section>+ <p class="wx-credit">Data by Open-Meteo.com</p>`;+ }++ // ---- start ----+ syncBar();+ if (place) load();+ else showWelcome();++ return () => {+ disposed = true;+ ac?.abort();+ searchAc?.abort();+ };+}diff --git a/src/desktop/os/fs.js b/src/desktop/os/fs.jsnew file mode 100644index 000000000..716099545--- /dev/null+++ b/src/desktop/os/fs.js@@ -0,0 +1,321 @@+// The desktop's virtual file system. Real storage: every node lives in+// IndexedDB (`tws-os` / `fs`), keyed by absolute path, so files survive reloads+// and hold Blobs of any size the browser allows. Paths are POSIX-style+// ("/Documents/notes.txt"). Deleting moves to /Trash; purge() is permanent.++export const DIRS = ['Desktop', 'Documents', 'Pictures', 'Downloads', 'Music', 'Videos'];+export const TRASH = '/Trash';+const DB = 'tws-os';+const STORE = 'fs';++const MIME = {+ txt: 'text/plain', md: 'text/markdown', json: 'application/json', js: 'text/javascript', css: 'text/css', html: 'text/html', csv: 'text/csv', xml: 'text/xml', log: 'text/plain',+ png: 'image/png', jpg: 'image/jpeg', jpeg: 'image/jpeg', gif: 'image/gif', webp: 'image/webp', svg: 'image/svg+xml', avif: 'image/avif', bmp: 'image/bmp',+ mp3: 'audio/mpeg', wav: 'audio/wav', ogg: 'audio/ogg', m4a: 'audio/mp4', flac: 'audio/flac', weba: 'audio/webm',+ mp4: 'video/mp4', webm: 'video/webm', mov: 'video/quicktime', mkv: 'video/x-matroska',+ glb: 'model/gltf-binary', gltf: 'model/gltf+json', pdf: 'application/pdf', zip: 'application/zip',+};++export const extOf = (name) => {+ const i = String(name).lastIndexOf('.');+ return i > 0 ? name.slice(i + 1).toLowerCase() : '';+};+export const mimeOf = (name) => MIME[extOf(name)] || 'application/octet-stream';+/** 'text' | 'image' | 'audio' | 'video' | 'model' | 'other', from a file name or mime type. */+export function kindOf(nameOrMime) {+ const m = nameOrMime.includes('/') ? nameOrMime : mimeOf(nameOrMime);+ if (m.startsWith('text/') || m === 'application/json') return 'text';+ if (m.startsWith('image/')) return 'image';+ if (m.startsWith('audio/')) return 'audio';+ if (m.startsWith('video/')) return 'video';+ if (m.startsWith('model/')) return 'model';+ return 'other';+}++export function normalize(path) {+ const out = [];+ for (const seg of String(path).split('/')) {+ if (!seg || seg === '.') continue;+ if (seg === '..') out.pop();+ else out.push(seg);+ }+ return `/${out.join('/')}`;+}+export const parentOf = (p) => normalize(p).split('/').slice(0, -1).join('/') || '/';+export const nameOf = (p) => normalize(p).split('/').pop() || '';+export const join = (...parts) => normalize(parts.join('/'));+const validName = (n) => !!n && n.length <= 120 && !/[\\/]/.test(n) && n !== '.' && n !== '..';++let dbp = null;+const listeners = new Set();+const emit = (paths) => listeners.forEach((fn) => fn(paths));+export function subscribe(fn) {+ listeners.add(fn);+ return () => listeners.delete(fn);+}++function db() {+ dbp ||= new Promise((res, rej) => {+ const r = indexedDB.open(DB, 1);+ r.onupgradeneeded = () => {+ const s = r.result.createObjectStore(STORE, { keyPath: 'path' });+ s.createIndex('parent', 'parent');+ };+ r.onsuccess = () => res(r.result);+ r.onerror = () => rej(r.error);+ });+ return dbp;+}+async function tx(mode, fn) {+ const d = await db();+ return new Promise((res, rej) => {+ const t = d.transaction(STORE, mode);+ let out;+ Promise.resolve(fn(t.objectStore(STORE))).then((v) => (out = v), rej);+ t.oncomplete = () => res(out);+ t.onerror = t.onabort = () => rej(t.error || new Error('storage failed'));+ });+}+const req = (r) => new Promise((res, rej) => ((r.onsuccess = () => res(r.result)), (r.onerror = () => rej(r.error))));++let ready = null;+/** Create the standard folders once. Safe to call repeatedly. */+export function init() {+ ready ||= tx('readwrite', async (s) => {+ for (const n of [...DIRS, 'Trash']) {+ const path = `/${n}`;+ if (!(await req(s.get(path)))) s.put(dirNode(path));+ }+ });+ return ready;+}+const dirNode = (path) => ({ path, name: nameOf(path), parent: parentOf(path), type: 'dir', size: 0, mtime: Date.now(), ctime: Date.now() });+const meta = ({ data, ...n }) => n;++export async function stat(path) {+ await init();+ const p = normalize(path);+ if (p === '/') return { path: '/', name: '', parent: '', type: 'dir', size: 0, mtime: 0, ctime: 0 };+ const n = await tx('readonly', (s) => req(s.get(p)));+ return n ? meta(n) : null;+}+export const exists = async (path) => !!(await stat(path));++/** Children of a folder (metadata only), folders first then by name. */+export async function list(path) {+ await init();+ const p = normalize(path);+ const rows = await tx('readonly', (s) => req(s.index('parent').getAll(p)));+ return rows+ .map(meta)+ .sort((a, b) => (a.type === b.type ? a.name.localeCompare(b.name, undefined, { numeric: true, sensitivity: 'base' }) : a.type === 'dir' ? -1 : 1));+}++/** File content: { node, blob } (always a Blob), or null when the path is not a file. */+export async function read(path) {+ await init();+ const n = await tx('readonly', (s) => req(s.get(normalize(path))));+ if (!n || n.type !== 'file') return null;+ const blob = n.data instanceof Blob ? n.data : new Blob([n.data ?? ''], { type: n.mime });+ return { node: meta(n), blob };+}+export async function readText(path) {+ const f = await read(path);+ return f ? f.blob.text() : null;+}++/** Pick a name that does not exist in `dir`: "a.txt" -> "a (2).txt". */+export async function uniqueName(dir, name) {+ const taken = new Set((await list(dir)).map((n) => n.name.toLowerCase()));+ if (!taken.has(name.toLowerCase())) return name;+ const e = extOf(name);+ const base = e ? name.slice(0, -(e.length + 1)) : name;+ for (let i = 2; ; i++) {+ const c = e ? `${base} (${i}).${e}` : `${base} (${i})`;+ if (!taken.has(c.toLowerCase())) return c;+ }+}++async function ensureParent(s, path) {+ const par = parentOf(path);+ if (par === '/') return;+ const row = await req(s.get(par));+ if (!row) throw new Error(`Folder not found: ${par}`);+ if (row.type !== 'dir') throw new Error(`${par} is not a folder`);+}++/** Create or replace a file. `data` is a string or Blob. Returns the node. */+export async function write(path, data, { mime } = {}) {+ await init();+ const p = normalize(path);+ if (!validName(nameOf(p))) throw new Error('That file name is not allowed');+ const blob = data instanceof Blob ? data : null;+ const node = await tx('readwrite', async (s) => {+ await ensureParent(s, p);+ const prev = await req(s.get(p));+ if (prev && prev.type === 'dir') throw new Error('A folder with that name already exists');+ const n = {+ path: p, name: nameOf(p), parent: parentOf(p), type: 'file',+ mime: mime || blob?.type || mimeOf(p), size: blob ? blob.size : new Blob([data]).size,+ mtime: Date.now(), ctime: prev?.ctime || Date.now(), data,+ };+ s.put(n);+ return n;+ });+ emit([parentOf(p)]);+ return meta(node);+}++export async function mkdir(path) {+ await init();+ const p = normalize(path);+ if (!validName(nameOf(p))) throw new Error('That folder name is not allowed');+ await tx('readwrite', async (s) => {+ await ensureParent(s, p);+ if (await req(s.get(p))) throw new Error('Something with that name already exists');+ s.put(dirNode(p));+ });+ emit([parentOf(p)]);+ return p;+}++async function descendants(s, path) {+ const out = [];+ const walk = async (p) => {+ for (const c of await req(s.index('parent').getAll(p))) {+ out.push(c);+ if (c.type === 'dir') await walk(c.path);+ }+ };+ await walk(path);+ return out;+}++/** Move or rename. Folders move with their contents. Throws if the target exists. */+export async function move(from, to) {+ await init();+ const a = normalize(from);+ const b = normalize(to);+ if (a === b) return b;+ if (b.startsWith(`${a}/`)) throw new Error('A folder cannot be moved into itself');+ if (!validName(nameOf(b))) throw new Error('That name is not allowed');+ await tx('readwrite', async (s) => {+ const src = await req(s.get(a));+ if (!src) throw new Error('Source not found');+ if (await req(s.get(b))) throw new Error('Something with that name already exists');+ await ensureParent(s, b);+ const kids = src.type === 'dir' ? await descendants(s, a) : [];+ for (const n of [src, ...kids]) {+ s.delete(n.path);+ const np = b + n.path.slice(a.length);+ s.put({ ...n, path: np, name: nameOf(np), parent: parentOf(np), mtime: n === src ? Date.now() : n.mtime });+ }+ });+ emit([parentOf(a), parentOf(b)]);+ return b;+}+export const rename = (path, newName) => move(path, join(parentOf(path), newName));++export async function copy(from, to) {+ await init();+ const a = normalize(from);+ const b = normalize(to);+ if (b === a || b.startsWith(`${a}/`)) throw new Error('A folder cannot be copied into itself');+ await tx('readwrite', async (s) => {+ const src = await req(s.get(a));+ if (!src) throw new Error('Source not found');+ if (await req(s.get(b))) throw new Error('Something with that name already exists');+ await ensureParent(s, b);+ const kids = src.type === 'dir' ? await descendants(s, a) : [];+ for (const n of [src, ...kids]) {+ const np = b + n.path.slice(a.length);+ s.put({ ...n, path: np, name: nameOf(np), parent: parentOf(np), ctime: Date.now(), mtime: Date.now() });+ }+ });+ emit([parentOf(b)]);+ return b;+}++/** Move to the Trash, remembering where it came from. Items already in the Trash are purged. */+export async function remove(path) {+ const p = normalize(path);+ if (p === '/' || DIRS.includes(p.slice(1)) || p === TRASH) throw new Error('This folder is part of the system and cannot be deleted');+ if (p.startsWith(`${TRASH}/`)) return purge(p);+ const name = await uniqueName(TRASH, nameOf(p));+ const dest = join(TRASH, name);+ await move(p, dest);+ await tx('readwrite', async (s) => {+ const n = await req(s.get(dest));+ if (n) s.put({ ...n, trashedFrom: p, trashedAt: Date.now() });+ });+ return dest;+}+export async function restore(path) {+ const n = await tx('readonly', (s) => req(s.get(normalize(path))));+ if (!n || !n.trashedFrom) throw new Error('Nothing to restore');+ let dest = n.trashedFrom;+ if (!(await exists(parentOf(dest)))) dest = join('/Documents', nameOf(dest));+ if (await exists(dest)) dest = join(parentOf(dest), await uniqueName(parentOf(dest), nameOf(dest)));+ await move(n.path, dest);+ await tx('readwrite', async (s) => {+ const r = await req(s.get(dest));+ if (r) {+ delete r.trashedFrom;+ delete r.trashedAt;+ s.put(r);+ }+ });+ return dest;+}+/** Permanently delete a file or folder (and its contents). */+export async function purge(path) {+ await init();+ const p = normalize(path);+ if (p === '/' || DIRS.includes(p.slice(1)) || p === TRASH) throw new Error('This folder is part of the system and cannot be deleted');+ await tx('readwrite', async (s) => {+ for (const n of await descendants(s, p)) s.delete(n.path);+ s.delete(p);+ });+ emit([parentOf(p)]);+}+export async function emptyTrash() {+ for (const n of await list(TRASH)) await purge(n.path);+}++/** Every file under a folder (recursive), for search and totals. */+export async function walk(path = '/') {+ await init();+ const out = [];+ await tx('readonly', async (s) => {+ for (const n of await descendants(s, normalize(path))) out.push(meta(n));+ });+ return out;+}+export async function usage() {+ const files = (await walk('/')).filter((n) => n.type === 'file');+ return { files: files.length, bytes: files.reduce((t, n) => t + n.size, 0) };+}+/** Newest files first, excluding the Trash. */+export async function recentFiles(limit = 8) {+ return (await walk('/'))+ .filter((n) => n.type === 'file' && !n.path.startsWith(`${TRASH}/`))+ .sort((a, b) => b.mtime - a.mtime)+ .slice(0, limit);+}+/** A short-lived object URL for a file, or null. Call URL.revokeObjectURL when done. */+export async function urlFor(path) {+ const f = await read(path);+ return f ? URL.createObjectURL(f.blob) : null;+}+/** Save a download-style File/Blob into a folder with a unique name. Returns the path. */+export async function importFile(file, dir = '/Downloads') {+ const name = await uniqueName(dir, file.name || 'file');+ const p = join(dir, name);+ await write(p, file, { mime: file.type || mimeOf(name) });+ return p;+}+export async function wipe() {+ await tx('readwrite', async (s) => s.clear());+ ready = null;+ emit(['/']);+}diff --git a/src/desktop/os/host.js b/src/desktop/os/host.jsnew file mode 100644index 000000000..c33c6b15c--- /dev/null+++ b/src/desktop/os/host.js@@ -0,0 +1,71 @@+// Mounts a native OS app into a window body and hands it its `ctx`.+import * as fs from './fs.js';+import { icon, registerGlyph } from '../icons.js';++const esc = (s) => String(s).replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c]);+const h = (tag, cls, html) => {+ const el = document.createElement(tag);+ if (cls) el.className = cls;+ if (html != null) el.innerHTML = html;+ return el;+};++/** Which app opens a path: folders in Files, text in Notepad, pictures in Photos, media in the player. */+export function appForPath(path, type) {+ if (type === 'dir') return 'files';+ const kind = fs.kindOf(fs.nameOf(path));+ if (kind === 'text') return 'notepad';+ if (kind === 'image') return 'photos';+ if (kind === 'audio' || kind === 'video') return 'media';+ return 'files';+}++export async function mountOsApp(app, body, win, sh) {+ const host = h('div', `napp-host napp-${app.id}`);+ host.style.cssText = 'position:absolute;inset:0;display:flex;flex-direction:column;min-height:0;overflow:hidden';+ body.append(host);+ const ctx = {+ h, esc, icon, registerGlyph, fs,+ tile: sh.tile,+ toast: sh.toast,+ notify: sh.notify,+ arg: win?.arg,+ onArg: (fn) => {+ if (win) win.onArg = fn;+ },+ setTitle: (t) => sh.wm.setTitle(app.id, t),+ onClose: (fn) => win?.cleanups.push(fn),+ launchId: sh.launchId,+ openPath: async (path) => {+ const node = await fs.stat(path);+ sh.launchId(appForPath(path, node?.type), { arg: path });+ },+ get prefs() {+ return sh.prefs();+ },+ setPrefs: (patch) => sh.setPrefs(patch),+ onPrefs: (fn) => {+ const off = sh.onPrefs(fn);+ win?.cleanups.push(off);+ return off;+ },+ store: sh.store,+ windows: () => sh.wm.list(),+ closeWindow: (id) => sh.wm.close(id),+ focusWindow: (id) => sh.wm.focus(id),+ async fetchJson(url, init) {+ const r = await fetch(url, { credentials: 'include', ...init });+ if (!r.ok) throw new Error(`HTTP ${r.status}`);+ return r.json();+ },+ };+ try {+ await fs.init();+ const mod = await app.load();+ const cleanup = await mod.mount(host, ctx);+ if (typeof cleanup === 'function') win?.cleanups.push(cleanup);+ } catch (err) {+ console.error(`[desktop] ${app.id} failed to start`, err);+ host.replaceChildren(h('div', 'napp-error', `<b>${esc(app.title)} could not start.</b><p>${esc(err?.message || 'Unknown error')}</p>`));+ }+}diff --git a/src/desktop/os/registry.js b/src/desktop/os/registry.jsnew file mode 100644index 000000000..808b811ad--- /dev/null+++ b/src/desktop/os/registry.js@@ -0,0 +1,19 @@+// The native OS apps. Each one is a lazily loaded module in ./apps exporting+// `mount(host, ctx)` (see README.md). Titles, sizes and keywords live here so+// Start, search, the desktop and the taskbar know every app before its code loads.++const os = (a) => ({ native: true, os: true, dock: false, desktop: false, keywords: [], ...a });++export const OS_APPS = [+ os({ id: 'files', title: 'File Explorer', hue: 44, icon: 'files', size: { w: 920, h: 600 }, dock: true, desktop: true, desc: 'Browse, create and organize your files', keywords: ['folder', 'documents', 'downloads', 'explorer', 'file manager', 'this pc', 'trash', 'recycle'], load: () => import('./apps/files.js') }),+ os({ id: 'notepad', title: 'Notepad', hue: 205, icon: 'note', size: { w: 720, h: 520 }, desktop: true, desc: 'Write and edit text files', keywords: ['text', 'edit', 'txt', 'markdown', 'write', 'note'], load: () => import('./apps/notepad.js') }),+ os({ id: 'photos', title: 'Photos', hue: 190, icon: 'image', size: { w: 860, h: 600 }, desc: 'View pictures from your files', keywords: ['image', 'picture', 'png', 'jpg', 'viewer'], load: () => import('./apps/photos.js') }),+ os({ id: 'calculator', title: 'Calculator', hue: 215, icon: 'calc', size: { w: 360, h: 560 }, desktop: true, desc: 'Standard, scientific and unit conversion', keywords: ['math', 'calc', 'convert', 'units', 'scientific'], load: () => import('./apps/calculator.js') }),+ os({ id: 'clock', title: 'Clock', hue: 20, icon: 'clock', size: { w: 560, h: 560 }, desc: 'Alarms, timer, stopwatch and world clocks', keywords: ['alarm', 'timer', 'stopwatch', 'time zone', 'world clock'], load: () => import('./apps/clock.js') }),+ os({ id: 'weather', title: 'Weather', hue: 200, icon: 'cloud', size: { w: 760, h: 600 }, desktop: true, desc: 'Live forecast for any city', keywords: ['forecast', 'temperature', 'rain', 'wind'], load: () => import('./apps/weather.js') }),+ os({ id: 'camera', title: 'Camera', hue: 330, icon: 'camera', size: { w: 720, h: 560 }, desc: 'Take photos and record video', keywords: ['photo', 'webcam', 'video', 'record', 'selfie'], load: () => import('./apps/camera.js') }),+ os({ id: 'paint', title: 'Paint', hue: 12, icon: 'paint', size: { w: 900, h: 620 }, desktop: true, desc: 'Draw, sketch and annotate images', keywords: ['draw', 'sketch', 'whiteboard', 'canvas', 'brush'], load: () => import('./apps/paint.js') }),+ os({ id: 'terminal', title: 'Terminal', hue: 150, icon: 'terminal', size: { w: 760, h: 480 }, dock: true, desc: 'A real command line for your desktop and three.ws', keywords: ['shell', 'cli', 'command', 'bash', 'console', 'cmd'], load: () => import('./apps/terminal.js') }),+ os({ id: 'taskmgr', title: 'Task Manager', hue: 160, icon: 'taskmgr', size: { w: 820, h: 560 }, desc: 'Running apps and live system performance', keywords: ['processes', 'performance', 'cpu', 'memory', 'end task', 'monitor'], load: () => import('./apps/taskmgr.js') }),+ os({ id: 'media', title: 'Media Player', hue: 280, icon: 'music', size: { w: 760, h: 520 }, desc: 'Play audio and video files', keywords: ['music', 'audio', 'video', 'mp3', 'mp4', 'player'], load: () => import('./apps/media.js') }),+];diff --git a/src/desktop/wm.js b/src/desktop/wm.jsindex 5adbb64f7..7836050c9 100644--- a/src/desktop/wm.js+++ b/src/desktop/wm.js@@ -221,6 +221,13 @@ export function createWM({ layer, getMetrics, renderNative, onChange, notify, geif (!w) return;w.el.classList.add('is-closing');wins.delete(id);+ (w.cleanups || []).forEach((fn) => {+ try {+ fn();+ } catch {+ /* an app's teardown must never block closing its window */+ }+ });const done = () => w.el.remove();if (reducedMotion()) done();else {@@ -254,6 +261,9 @@ export function createWM({ layer, getMetrics, renderNative, onChange, notify, gez: 0,rect: null,frame: null,+ arg: opts.arg,+ cleanups: [],+ onArg: null,};const el = document.createElement('section');el.className = 'win';@@ -660,6 +670,7 @@ export function createWM({ layer, getMetrics, renderNative, onChange, notify, geexisting.frame.src = opts.path;existing.extLink.href = opts.path;}+ if (opts.arg !== undefined) existing.onArg?.(opts.arg);focus(app.id);return existing;}@@ -754,6 +765,14 @@ export function createWM({ layer, getMetrics, renderNative, onChange, notify, gehas: (id) => wins.has(id),focused: () => focusedId,list: () => [...wins.values()].map(publicView),+ setTitle(id, title) {+ const w = wins.get(id);+ if (!w) return;+ w.title = String(title || w.app.title).slice(0, 80);+ w.el.querySelector('.win-name').textContent = w.title;+ w.el.setAttribute('aria-label', w.title);+ emit();+ },closeAll: () => [...wins.keys()].forEach(close),};}diff --git a/tests/desktop-os-apps.test.js b/tests/desktop-os-apps.test.jsnew file mode 100644index 000000000..a8eef5a09--- /dev/null+++ b/tests/desktop-os-apps.test.js@@ -0,0 +1,324 @@+// Pure logic behind the native desktop apps: calculator engine, unit table, clock logic, weather codes.+import { describe, it, expect } from 'vitest';+import { evaluate, formatNumber, evalProgrammer, toBase, parseInBase, factorial, CalcError } from '../src/desktop/os/apps/calc-engine.js';+import { convert, CATEGORIES } from '../src/desktop/os/apps/unit-convert.js';+import { nextAlarmTime, repeatLabel, formatDuration, parseDuration, stopwatch, lapExtremes, zoneOffsetMinutes, offsetLabel, relativeOffset, isValidZone, checkAlarms, checkTimers, untilLabel } from '../src/desktop/os/apps/alarm-logic.js';+import { describe as wx, compass, uvLabel } from '../src/desktop/os/apps/weather-codes.js';+import { normalise } from '../src/desktop/os/apps/weather-data.js';++describe('calc-engine evaluate', () => {+ it('respects precedence and associativity', () => {+ expect(evaluate('2+3*4')).toBe(14);+ expect(evaluate('(2+3)*4')).toBe(20);+ expect(evaluate('2^3^2')).toBe(512);+ expect(evaluate('-2^2')).toBe(-4);+ expect(evaluate('2^-1')).toBe(0.5);+ expect(evaluate('10-4-3')).toBe(3);+ expect(evaluate('8/2/2')).toBe(2);+ });+ it('handles implicit multiplication, percent, factorial', () => {+ expect(evaluate('2(3+1)')).toBe(8);+ expect(evaluate('2pi')).toBeCloseTo(Math.PI * 2);+ expect(evaluate('50%')).toBe(0.5);+ expect(evaluate('200*10%')).toBe(20);+ expect(evaluate('10%3')).toBe(1);+ expect(evaluate('5!')).toBe(120);+ expect(factorial(0)).toBe(1);+ });+ it('applies degrees and radians to trig', () => {+ expect(evaluate('sin(90)', { angle: 'deg' })).toBeCloseTo(1);+ expect(evaluate('sin(180)', { angle: 'deg' })).toBe(0);+ expect(evaluate('cos(pi)', { angle: 'rad' })).toBeCloseTo(-1);+ expect(evaluate('asin(1)', { angle: 'deg' })).toBeCloseTo(90);+ });+ it('supports logs, roots, multi-arg functions and ans', () => {+ expect(evaluate('log(1000)')).toBeCloseTo(3);+ expect(evaluate('ln(e)')).toBeCloseTo(1);+ expect(evaluate('sqrt(16)+cbrt(27)')).toBe(7);+ expect(evaluate('root(27,3)')).toBeCloseTo(3);+ expect(evaluate('max(2,9)-min(4,1)')).toBe(8);+ expect(evaluate('ans*2', { ans: 21 })).toBe(42);+ expect(evaluate('×'.length ? '6×7÷2' : '')).toBe(21);+ });+ it('rejects bad input without evaluating code', () => {+ expect(() => evaluate('2+')).toThrow(CalcError);+ expect(() => evaluate('(2')).toThrow(/parentheses/);+ expect(() => evaluate('1/0')).toThrow(/zero/);+ expect(() => evaluate('sqrt(-1)')).toThrow(/Not a number/);+ expect(() => evaluate('alert(1)')).toThrow(/Unknown name/);+ expect(() => evaluate('constructor')).toThrow(CalcError);+ expect(() => evaluate('sin 30')).toThrow(/parentheses/);+ expect(() => evaluate('(-1)!')).toThrow(/whole number/);+ expect(() => evaluate('')).toThrow(CalcError);+ });+ it('formats results', () => {+ expect(formatNumber(1234567.891)).toBe('1,234,567.891');+ expect(formatNumber(0.1 + 0.2)).toBe('0.3');+ expect(formatNumber(-1000)).toBe('-1,000');+ expect(formatNumber(1e21)).toMatch(/e21$/);+ expect(formatNumber(0)).toBe('0');+ });+});++describe('calc-engine programmer mode', () => {+ it('evaluates bitwise operators and masks to the width', () => {+ expect(evalProgrammer('F0 & 3C', 'hex', 8)).toBe(0x30n);+ expect(evalProgrammer('1 << 4 | 1', 'dec', 16)).toBe(17n);+ expect(evalProgrammer('~0', 'dec', 8)).toBe(255n);+ expect(evalProgrammer('255 + 1', 'dec', 8)).toBe(0n);+ expect(evalProgrammer('-1', 'dec', 16)).toBe(0xffffn);+ expect(evalProgrammer('(2+3)*4', 'dec', 32)).toBe(20n);+ expect(evalProgrammer('1010 XOR 0110', 'bin', 8)).toBe(0b1100n);+ expect(evalProgrammer('0xFF + 1', 'dec', 16)).toBe(256n);+ });+ it('divides signed and rejects bad digits', () => {+ expect(() => evalProgrammer('5/0', 'dec', 8)).toThrow(/zero/);+ expect(() => evalProgrammer('9', 'oct', 8)).toThrow(CalcError);+ expect(evalProgrammer('-8/2', 'dec', 8)).toBe(BigInt.asUintN(8, -4n));+ });+ it('converts between bases', () => {+ expect(toBase(255n, 'hex', 16)).toBe('FF');+ expect(toBase(5n, 'bin', 8)).toBe('0000 0101');+ expect(toBase(8n, 'oct', 8)).toBe('10');+ expect(parseInBase('ff', 'hex')).toBe(255n);+ expect(() => parseInBase('12', 'bin')).toThrow(CalcError);+ });+});++describe('unit-convert', () => {+ it('converts linear units', () => {+ expect(convert('length', 'km', 'mi', 1)).toBeCloseTo(0.621371, 5);+ expect(convert('length', 'ft', 'in', 1)).toBeCloseTo(12);+ expect(convert('mass', 'lb', 'kg', 10)).toBeCloseTo(4.5359237);+ expect(convert('data', 'GiB', 'MiB', 1)).toBe(1024);+ expect(convert('time', 'h', 'min', 2)).toBe(120);+ expect(convert('speed', 'mph', 'kmh', 60)).toBeCloseTo(96.56064);+ expect(convert('volume', 'gal', 'l', 1)).toBeCloseTo(3.785411784);+ expect(convert('area', 'ac', 'ha', 1)).toBeCloseTo(0.404686, 5);+ });+ it('converts temperature including absolute zero', () => {+ expect(convert('temperature', 'C', 'F', 100)).toBe(212);+ expect(convert('temperature', 'F', 'C', -40)).toBeCloseTo(-40);+ expect(convert('temperature', 'K', 'C', 0)).toBeCloseTo(-273.15);+ expect(() => convert('temperature', 'K', 'C', -1)).toThrow(/absolute zero/);+ });+ it('round-trips every unit in every category', () => {+ for (const [cat, def] of Object.entries(CATEGORIES)) {+ const keys = Object.keys(def.units);+ for (const a of keys) for (const b of keys) {+ const v = convert(cat, b, a, convert(cat, a, b, 37));+ expect(v).toBeCloseTo(37, 6);+ }+ }+ });+ it('rejects unknown units and non-numbers', () => {+ expect(() => convert('length', 'm', 'zz', 1)).toThrow();+ expect(() => convert('nope', 'm', 'm', 1)).toThrow();+ expect(() => convert('length', 'm', 'km', NaN)).toThrow();+ });+});++describe('alarm-logic', () => {+ it('finds the next one-shot and repeating alarm time', () => {+ const from = new Date(2026, 9, 11, 10, 0, 0); // Sunday+ expect(nextAlarmTime({ on: true, h: 11, m: 30, days: [] }, from)).toEqual(new Date(2026, 9, 11, 11, 30));+ expect(nextAlarmTime({ on: true, h: 9, m: 0, days: [] }, from)).toEqual(new Date(2026, 9, 12, 9, 0));+ expect(nextAlarmTime({ on: true, h: 9, m: 0, days: [3] }, from)).toEqual(new Date(2026, 9, 14, 9, 0));+ expect(nextAlarmTime({ on: false, h: 9, m: 0, days: [] }, from)).toBeNull();+ });+ it('fires alarms that crossed their time since the last tick, once', () => {+ const a = { id: 'a', on: true, h: 10, m: 0, days: [] };+ const last = new Date(2026, 9, 11, 9, 59, 0).getTime();+ const now = new Date(2026, 9, 11, 10, 0, 1).getTime();+ const r = checkAlarms([a], now, last);+ expect(r.fired).toHaveLength(1);+ expect(r.alarms[0].on).toBe(false);+ expect(checkAlarms(r.alarms, now + 1000, now).fired).toHaveLength(0);+ const rep = { ...a, days: [0] };+ expect(checkAlarms([rep], now, last).alarms[0].on).toBe(true);+ });+ it('finishes timers at their end time', () => {+ const t = { id: 't', endsAt: 1000, done: false };+ expect(checkTimers([t], 999).fired).toHaveLength(0);+ const r = checkTimers([t], 1000);+ expect(r.fired).toHaveLength(1);+ expect(r.timers[0].done).toBe(true);+ });+ it('labels repeats and durations', () => {+ expect(repeatLabel([])).toBe('Once');+ expect(repeatLabel([1, 2, 3, 4, 5])).toBe('Weekdays');+ expect(repeatLabel([0, 6])).toBe('Weekends');+ expect(repeatLabel([1, 3])).toBe('Mon, Wed');+ expect(formatDuration(65000)).toBe('01:05');+ expect(formatDuration(3723450, true)).toBe('1:02:03.45');+ expect(parseDuration('1:30')).toBe(90000);+ expect(parseDuration('5m 30s')).toBe(330000);+ expect(parseDuration('45')).toBe(45000);+ expect(parseDuration('abc')).toBeNull();+ expect(untilLabel(new Date(2026, 0, 1, 12, 20), new Date(2026, 0, 1, 9, 0))).toBe('in 3 h 20 min');+ });+ it('runs a stopwatch with laps', () => {+ let s = stopwatch.start(stopwatch.fresh(), 1000);+ s = stopwatch.lap(s, 2500);+ s = stopwatch.lap(s, 3000);+ expect(s.laps.map((l) => l.split)).toEqual([1500, 500]);+ expect(lapExtremes(s.laps)).toEqual({ fastest: 2, slowest: 1 });+ s = stopwatch.pause(s, 4000);+ expect(stopwatch.now(s, 9999)).toBe(3000);+ });+ it('computes real zone offsets through Intl', () => {+ const d = new Date(Date.UTC(2026, 0, 15, 12, 0, 0));+ expect(zoneOffsetMinutes('UTC', d)).toBe(0);+ expect(zoneOffsetMinutes('Asia/Kolkata', d)).toBe(330);+ expect(zoneOffsetMinutes('America/New_York', d)).toBe(-300);+ expect(zoneOffsetMinutes('America/New_York', new Date(Date.UTC(2026, 6, 15)))).toBe(-240);+ expect(isValidZone('Europe/Paris')).toBe(true);+ expect(isValidZone('Mars/Olympus')).toBe(false);+ expect(offsetLabel(330)).toBe('UTC+5:30');+ expect(offsetLabel(-300)).toBe('UTC-5');+ expect(relativeOffset(330, 0)).toBe('+5 h 30 min');+ expect(relativeOffset(0, 0)).toBe('Same time');+ });+});++describe('weather codes and data', () => {+ it('maps WMO codes', () => {+ expect(wx(0, true)).toEqual({ label: 'Clear sky', kind: 'clear', night: false });+ expect(wx(0, false).label).toBe('Clear night');+ expect(wx(63).kind).toBe('rain');+ expect(wx(95).kind).toBe('storm');+ expect(wx(999).label).toBe('Unknown');+ expect(compass(0)).toBe('N');+ expect(compass(225)).toBe('SW');+ expect(uvLabel(7)).toBe('High');+ });+ it('normalises an Open-Meteo response', () => {+ const times = Array.from({ length: 48 }, (_, i) => `2026-10-11T${String(i % 24).padStart(2, '0')}:00`);+ const raw = {+ timezone: 'Europe/Paris',+ current: { time: '2026-10-11T10:15', temperature_2m: 12, apparent_temperature: 10, relative_humidity_2m: 70, weather_code: 3, is_day: 1, precipitation: 0, wind_speed_10m: 9, wind_direction_10m: 200, surface_pressure: 1010 },+ hourly: { time: times, temperature_2m: times.map((_, i) => i), precipitation_probability: times.map(() => 5), weather_code: times.map(() => 1), is_day: times.map(() => 1) },+ daily: { time: ['2026-10-11'], weather_code: [3], temperature_2m_max: [15], temperature_2m_min: [8], sunrise: ['2026-10-11T07:50'], sunset: ['2026-10-11T18:55'], uv_index_max: [3], precipitation_probability_max: [20], wind_speed_10m_max: [18] },+ };+ const n = normalise(raw, 'C');+ expect(n.hourly).toHaveLength(24);+ expect(n.hourly[0].time).toBe('2026-10-11T10:00');+ expect(n.current.isDay).toBe(true);+ expect(n.daily[0].max).toBe(15);+ expect(n.units.wind).toBe('km/h');+ });+});++import { captureName, pickRecorderType, extForRecorderType, classifyMediaError, elapsedLabel } from '../src/desktop/os/apps/camera-logic.js';++describe('camera-logic', () => {+ it('names captures with a valid, sortable file name', () => {+ expect(captureName(new Date(2026, 9, 11, 7, 5, 9), 'png')).toBe('Camera 2026-10-11 07.05.09.png');+ });+ it('picks the first supported recorder type', () => {+ expect(pickRecorderType((t) => t === 'video/webm')).toBe('video/webm');+ expect(pickRecorderType(() => false)).toBe('');+ expect(extForRecorderType('video/mp4')).toBe('mp4');+ expect(extForRecorderType('video/webm;codecs=vp9,opus')).toBe('webm');+ });+ it('maps getUserMedia errors to recovery steps', () => {+ expect(classifyMediaError({ name: 'NotAllowedError' }).kind).toBe('denied');+ expect(classifyMediaError({ name: 'NotFoundError' }).kind).toBe('none');+ expect(classifyMediaError({ name: 'NotReadableError' }).kind).toBe('busy');+ expect(classifyMediaError({ name: 'Weird', message: 'boom' }).steps[0]).toBe('boom');+ expect(classifyMediaError(null, { hasMediaDevices: false }).kind).toBe('unsupported');+ expect(classifyMediaError(null, { secure: false }).kind).toBe('insecure');+ expect(classifyMediaError({ name: 'NotAllowedError' }).steps.length).toBeGreaterThan(1);+ });+ it('formats elapsed recording time', () => {+ expect(elapsedLabel(0)).toBe('0:00');+ expect(elapsedLabel(65000)).toBe('1:05');+ });+});++import { floodFill, History, hexToRgb, rgbToHex, stepZoom, fitZoom, constrain, pressureWidth, clampDim, formatForName } from '../src/desktop/os/apps/paint-logic.js';++function img(w, h, fill = [255, 255, 255, 255]) {+ const data = new Uint8ClampedArray(w * h * 4);+ for (let i = 0; i < w * h; i++) data.set(fill, i * 4);+ return { data, width: w, height: h };+}+const px = (im, x, y) => [...im.data.slice((y * im.width + x) * 4, (y * im.width + x) * 4 + 4)];++describe('paint-logic', () => {+ it('flood fills a bounded region only', () => {+ const im = img(5, 5);+ for (let i = 0; i < 5; i++) im.data.set([0, 0, 0, 255], (2 * 5 + i) * 4); // black wall across row 2+ const n = floodFill(im, 0, 0, [255, 0, 0]);+ expect(n).toBe(10);+ expect(px(im, 4, 1)).toEqual([255, 0, 0, 255]);+ expect(px(im, 0, 3)).toEqual([255, 255, 255, 255]);+ expect(px(im, 2, 2)).toEqual([0, 0, 0, 255]);+ });+ it('fills diagonal-gap regions without leaking through 4-connected walls', () => {+ const im = img(3, 3);+ [[1, 0], [0, 1]].forEach(([x, y]) => im.data.set([0, 0, 0, 255], (y * 3 + x) * 4));+ expect(floodFill(im, 0, 0, [9, 9, 9])).toBe(1);+ });+ it('honours tolerance and opacity', () => {+ const im = img(4, 1);+ im.data.set([250, 250, 250, 255], 4);+ expect(floodFill(img(4, 1), 0, 0, [0, 0, 0], { tolerance: 0, opacity: 0.5 })).toBe(4);+ expect(floodFill(im, 0, 0, [0, 0, 0], { tolerance: 0 })).toBe(1);+ const im2 = img(4, 1);+ im2.data.set([250, 250, 250, 255], 4);+ expect(floodFill(im2, 0, 0, [0, 0, 0], { tolerance: 10 })).toBe(4);+ const half = img(1, 1);+ floodFill(half, 0, 0, [0, 0, 0], { opacity: 0.5 });+ expect(px(half, 0, 0)[0]).toBe(128);+ });+ it('ignores out-of-bounds starts and fills large areas without recursion limits', () => {+ const im = img(2, 2);+ expect(floodFill(im, -1, 0, [0, 0, 0])).toBe(0);+ expect(floodFill(im, 5, 5, [0, 0, 0])).toBe(0);+ expect(floodFill(img(600, 600), 10, 10, [1, 2, 3])).toBe(360000);+ });+ it('undoes and redoes snapshots and bounds memory', () => {+ const h = new History({ maxCount: 3 });+ const s = (n) => ({ data: new Uint8Array(n), tag: n });+ h.push(s(1));+ h.push(s(2));+ expect(h.canUndo).toBe(true);+ const prev = h.undo(s(3));+ expect(prev.tag).toBe(2);+ expect(h.canRedo).toBe(true);+ expect(h.redo(prev).tag).toBe(3);+ h.push(s(4));+ expect(h.canRedo).toBe(false);+ h.push(s(5));+ h.push(s(6));+ expect(h.undoStack.length).toBe(3);+ const big = new History({ maxBytes: 100 });+ big.push(s(60));+ big.push(s(60));+ expect(big.undoStack.length).toBe(1);+ expect(new History().undo(s(1))).toBeNull();+ });+ it('parses colours and zoom and shapes', () => {+ expect(hexToRgb('#ff8000')).toEqual([255, 128, 0]);+ expect(hexToRgb('f00')).toEqual([255, 0, 0]);+ expect(hexToRgb('nope')).toBeNull();+ expect(rgbToHex(255, 128, 0)).toBe('#ff8000');+ expect(stepZoom(1, 1)).toBe(1.25);+ expect(stepZoom(1, -1)).toBe(0.75);+ expect(stepZoom(8, 1)).toBe(8);+ expect(fitZoom(2000, 1000, 1000, 1000)).toBe(0.5);+ expect(fitZoom(100, 100, 1000, 1000)).toBe(1);+ const [sx, sy] = constrain('rect', 0, 0, 10, 4);+ expect([sx, sy]).toEqual([10, 10]);+ const [lx, ly] = constrain('line', 0, 0, 10, 1);+ expect(Math.round(lx)).toBe(10);+ expect(Math.abs(ly)).toBeLessThan(1e-9);+ expect(pressureWidth(10, 'mouse', 0.9)).toBe(10);+ expect(pressureWidth(10, 'pen', 0.5)).toBeCloseTo(10);+ expect(clampDim(99999)).toBe(8192);+ expect(clampDim('abc')).toBe(1);+ expect(formatForName('a.JPG').mime).toBe('image/jpeg');+ expect(formatForName('a.bin').ext).toBe('png');+ });+});diff --git a/tests/desktop-os-files.test.js b/tests/desktop-os-files.test.jsnew file mode 100644index 000000000..bd7cd7f0c--- /dev/null+++ b/tests/desktop-os-files.test.js@@ -0,0 +1,226 @@+// Pure logic behind the native File Explorer, Notepad and Photos apps.+import { describe, it, expect } from 'vitest';+import {+ formatSize, sortNodes, buildCrumbs, parseAddress, filterByName, rangeSelect, moveIndex, movablePaths,+ selectionSummary, statusText, locationName, typeLabel, iconName,+} from '../src/desktop/os/apps/files.js';+import {+ findMatches, replaceAll, nextMatchIndex, lineCol, offsetOfLine, countLines, clampSize, zoomPercent,+ titleFor, fileNameFrom, parseDrafts, MIN_SIZE, MAX_SIZE,+} from '../src/desktop/os/apps/notepad.js';+import {+ newestFirst, byName, stepIndex, fitScale, rotatedSize, clampPan, zoomAt, clampZoom, positionLabel, isImageName,+} from '../src/desktop/os/apps/photos.js';++const f = (name, extra = {}) => ({ type: 'file', name, path: `/Documents/${name}`, parent: '/Documents', size: 10, mtime: 1, ...extra });+const d = (name, extra = {}) => ({ type: 'dir', name, path: `/Documents/${name}`, parent: '/Documents', size: 0, mtime: 1, ...extra });++describe('files: formatting', () => {+ it('formats sizes', () => {+ expect(formatSize(0)).toBe('0 B');+ expect(formatSize(-5)).toBe('0 B');+ expect(formatSize(NaN)).toBe('0 B');+ expect(formatSize(812)).toBe('812 B');+ expect(formatSize(1024)).toBe('1 KB');+ expect(formatSize(1536)).toBe('1.5 KB');+ expect(formatSize(12 * 1024)).toBe('12 KB');+ expect(formatSize(1.5 * 1024 * 1024)).toBe('1.5 MB');+ expect(formatSize(3 * 1024 ** 3)).toBe('3 GB');+ });+ it('labels types and locations', () => {+ expect(typeLabel(d('a'))).toBe('File folder');+ expect(typeLabel(f('pic.png'))).toBe('PNG file');+ expect(typeLabel(f('README'))).toBe('File');+ expect(locationName('@home')).toBe('Home');+ expect(locationName('/')).toBe('This PC');+ expect(locationName('/Trash')).toBe('Recycle Bin');+ expect(locationName('/Documents/Notes')).toBe('Notes');+ });+ it('picks icons', () => {+ expect(iconName({ type: 'dir', path: '/Pictures', parent: '/', name: 'Pictures' })).toBe('image');+ expect(iconName({ type: 'dir', path: '/Trash', parent: '/', name: 'Trash' })).toBe('trash');+ expect(iconName(d('x'))).toBe('folder');+ expect(iconName(f('a.mp3'))).toBe('music');+ expect(iconName(f('a.txt'))).toBe('note');+ expect(iconName(f('a.bin'))).toBe('fx-file');+ });+});++describe('files: sorting and filtering', () => {+ const nodes = [f('b.txt', { size: 5, mtime: 30 }), d('Zed'), f('a10.txt', { size: 50, mtime: 10 }), f('a2.txt', { size: 1, mtime: 20 }), d('alpha')];+ it('keeps folders first and sorts naturally by name', () => {+ expect(sortNodes(nodes).map((n) => n.name)).toEqual(['alpha', 'Zed', 'a2.txt', 'a10.txt', 'b.txt']);+ });+ it('reverses within each group only', () => {+ expect(sortNodes(nodes, { key: 'name', dir: 'desc' }).map((n) => n.name)).toEqual(['Zed', 'alpha', 'b.txt', 'a10.txt', 'a2.txt']);+ });+ it('sorts by size, date and type without mutating the input', () => {+ const copy = [...nodes];+ expect(sortNodes(nodes, { key: 'size' }).filter((n) => n.type === 'file').map((n) => n.name)).toEqual(['a2.txt', 'b.txt', 'a10.txt']);+ expect(sortNodes(nodes, { key: 'date', dir: 'desc' }).filter((n) => n.type === 'file').map((n) => n.name)).toEqual(['b.txt', 'a2.txt', 'a10.txt']);+ expect(sortNodes([f('b.png'), f('a.txt')], { key: 'type' }).map((n) => n.name)).toEqual(['b.png', 'a.txt']);+ expect(nodes).toEqual(copy);+ });+ it('filters by name, case-insensitively', () => {+ expect(filterByName(nodes, 'A').length).toBe(3);+ expect(filterByName(nodes, ' zed ').map((n) => n.name)).toEqual(['Zed']);+ expect(filterByName(nodes, '')).toBe(nodes);+ expect(filterByName(nodes, 'nope')).toEqual([]);+ });+});++describe('files: navigation', () => {+ it('builds breadcrumbs', () => {+ expect(buildCrumbs('@home')).toEqual([{ name: 'Home', path: '@home' }]);+ expect(buildCrumbs('/')).toEqual([{ name: 'This PC', path: '/' }]);+ expect(buildCrumbs('/Documents/a b')).toEqual([+ { name: 'This PC', path: '/' }, { name: 'Documents', path: '/Documents' }, { name: 'a b', path: '/Documents/a b' },+ ]);+ expect(buildCrumbs('/Trash')[1]).toEqual({ name: 'Recycle Bin', path: '/Trash' });+ });+ it('parses typed addresses', () => {+ expect(parseAddress('')).toBe('/');+ expect(parseAddress('This PC')).toBe('/');+ expect(parseAddress('home')).toBe('@home');+ expect(parseAddress('Recycle Bin')).toBe('/Trash');+ expect(parseAddress('This PC\\Documents\\x')).toBe('/Documents/x');+ expect(parseAddress('/Pictures/../Music/')).toBe('/Music');+ expect(parseAddress('Documents')).toBe('/Documents');+ });+ it('moves the cursor through list and grid layouts', () => {+ expect(moveIndex(-1, 'ArrowDown', 5)).toBe(0);+ expect(moveIndex(-1, 'ArrowUp', 5)).toBe(4);+ expect(moveIndex(0, 'ArrowUp', 5)).toBe(0);+ expect(moveIndex(4, 'ArrowDown', 5)).toBe(4);+ expect(moveIndex(2, 'ArrowLeft', 5)).toBe(2);+ expect(moveIndex(2, 'ArrowLeft', 5, 3)).toBe(1);+ expect(moveIndex(1, 'ArrowDown', 9, 3)).toBe(4);+ expect(moveIndex(8, 'ArrowDown', 9, 3)).toBe(8);+ expect(moveIndex(3, 'Home', 9)).toBe(0);+ expect(moveIndex(3, 'End', 9)).toBe(8);+ expect(moveIndex(0, 'ArrowDown', 0)).toBe(-1);+ });+});++describe('files: selection', () => {+ const order = ['a', 'b', 'c', 'd', 'e'];+ it('selects ranges in either direction', () => {+ expect(rangeSelect(order, 'b', 'd')).toEqual(['b', 'c', 'd']);+ expect(rangeSelect(order, 'd', 'b')).toEqual(['b', 'c', 'd']);+ expect(rangeSelect(order, null, 'c')).toEqual(['c']);+ expect(rangeSelect(order, 'a', 'zzz')).toEqual([]);+ });+ it('only lets legal moves through', () => {+ expect(movablePaths(['/Documents/a', '/Pictures/b'], '/Documents')).toEqual(['/Pictures/b']);+ expect(movablePaths(['/Documents/dir'], '/Documents/dir')).toEqual([]);+ expect(movablePaths(['/Documents/dir'], '/Documents/dir/inner')).toEqual([]);+ expect(movablePaths(['/Documents/dir2'], '/Documents/dir')).toEqual(['/Documents/dir2']);+ });+ it('summarises and words the status bar', () => {+ const s = selectionSummary([f('a', { size: 1024 }), f('b', { size: 1024 }), d('x')]);+ expect(s).toEqual({ count: 3, bytes: 2048, dirs: 1 });+ expect(statusText(1, { count: 0, bytes: 0, dirs: 0 })).toBe('1 item');+ expect(statusText(12, { count: 0, bytes: 0, dirs: 0 })).toBe('12 items');+ expect(statusText(12, s)).toBe('12 items 3 selected 2 KB');+ expect(statusText(2, { count: 1, bytes: 0, dirs: 1 })).toBe('2 items 1 selected');+ });+});++describe('notepad: find and replace', () => {+ it('finds matches with and without case', () => {+ expect(findMatches('Abc abc ABC', 'abc')).toEqual([0, 4, 8]);+ expect(findMatches('Abc abc ABC', 'abc', true)).toEqual([4]);+ expect(findMatches('aaaa', 'aa')).toEqual([0, 2]);+ expect(findMatches('text', '')).toEqual([]);+ expect(findMatches('', 'x')).toEqual([]);+ });+ it('replaces all matches', () => {+ expect(replaceAll('one two one', 'one', '1')).toEqual({ text: '1 two 1', count: 2 });+ expect(replaceAll('One one', 'one', 'x', true)).toEqual({ text: 'One x', count: 1 });+ expect(replaceAll('abc', 'z', 'y')).toEqual({ text: 'abc', count: 0 });+ expect(replaceAll('a.b.c', '.', '')).toEqual({ text: 'abc', count: 2 });+ });+ it('wraps to the next match', () => {+ const m = [3, 10, 20];+ expect(nextMatchIndex(m, 0)).toBe(0);+ expect(nextMatchIndex(m, 10)).toBe(1);+ expect(nextMatchIndex(m, 21)).toBe(0);+ expect(nextMatchIndex(m, 10, true)).toBe(0);+ expect(nextMatchIndex(m, 3, true)).toBe(2);+ expect(nextMatchIndex([], 5)).toBe(-1);+ });+});++describe('notepad: positions and names', () => {+ it('computes line and column', () => {+ expect(lineCol('', 0)).toEqual({ line: 1, col: 1 });+ expect(lineCol('ab\ncd', 4)).toEqual({ line: 2, col: 2 });+ expect(lineCol('ab\n', 3)).toEqual({ line: 2, col: 1 });+ });+ it('finds line starts and counts lines', () => {+ expect(offsetOfLine('ab\ncd\nef', 1)).toBe(0);+ expect(offsetOfLine('ab\ncd\nef', 3)).toBe(6);+ expect(offsetOfLine('ab\ncd', 99)).toBe(3);+ expect(countLines('a\nb\nc')).toBe(3);+ expect(countLines('')).toBe(1);+ });+ it('clamps zoom and builds titles and names', () => {+ expect(clampSize(2)).toBe(MIN_SIZE);+ expect(clampSize(900)).toBe(MAX_SIZE);+ expect(zoomPercent(14)).toBe(100);+ expect(zoomPercent(28)).toBe(200);+ expect(titleFor('a.txt', true)).toBe('*a.txt - Notepad');+ expect(titleFor('a.txt', false)).toBe('a.txt - Notepad');+ expect(fileNameFrom(' notes ')).toBe('notes.txt');+ expect(fileNameFrom('a.md')).toBe('a.md');+ expect(fileNameFrom(' ')).toBe('');+ });+ it('rejects malformed drafts', () => {+ const good = { id: 'd1', name: 'a.txt', text: 'hi', path: '/Documents/a.txt', extra: 1 };+ expect(parseDrafts(JSON.stringify([good, { id: 3 }, null, { id: 'x', name: 'n', text: 't' }]))).toEqual([+ { id: 'd1', name: 'a.txt', text: 'hi', path: '/Documents/a.txt' },+ { id: 'x', name: 'n', text: 't', path: null },+ ]);+ expect(parseDrafts('not json')).toEqual([]);+ expect(parseDrafts('{"a":1}')).toEqual([]);+ expect(parseDrafts(null)).toEqual([]);+ });+});++describe('photos', () => {+ it('keeps only images and orders them', () => {+ const nodes = [f('a.png', { mtime: 5 }), f('b.txt'), d('dir.png'), f('c.JPG', { mtime: 9 }), f('d.webp', { mtime: 5 })];+ expect(newestFirst(nodes).map((n) => n.name)).toEqual(['c.JPG', 'a.png', 'd.webp']);+ expect(byName([f('img10.png'), f('img2.png'), f('x.md')]).map((n) => n.name)).toEqual(['img2.png', 'img10.png']);+ expect(isImageName('x.svg')).toBe(true);+ expect(isImageName('x.glb')).toBe(false);+ });+ it('steps with wraparound', () => {+ expect(stepIndex(0, -1, 4)).toBe(3);+ expect(stepIndex(3, 1, 4)).toBe(0);+ expect(stepIndex(1, 1, 4)).toBe(2);+ expect(stepIndex(0, 1, 0)).toBe(-1);+ expect(positionLabel(2, 12)).toBe('3 of 12');+ expect(positionLabel(-1, 12)).toBe('');+ });+ it('fits pictures and handles rotation', () => {+ expect(rotatedSize(400, 200, 90)).toEqual({ w: 200, h: 400 });+ expect(rotatedSize(400, 200, 180)).toEqual({ w: 400, h: 200 });+ expect(rotatedSize(400, 200, -90)).toEqual({ w: 200, h: 400 });+ expect(fitScale(2000, 1000, 1000, 1000)).toBe(0.5);+ expect(fitScale(100, 100, 1000, 1000)).toBe(1);+ expect(fitScale(2000, 1000, 1000, 1000, 90)).toBe(0.5);+ expect(fitScale(1000, 2000, 1000, 500, 90)).toBe(0.5);+ expect(fitScale(0, 0, 100, 100)).toBe(1);+ });+ it('clamps pan and zoom, and zooms about the cursor', () => {+ expect(clampPan(9999, 400, 600)).toBe(452);+ expect(clampPan(-9999, 400, 600)).toBe(-452);+ expect(clampPan(10, 400, 600)).toBe(10);+ expect(clampZoom(100)).toBe(16);+ expect(clampZoom(0)).toBe(0.05);+ const z = zoomAt({ s: 1, x: 0, y: 0 }, 2, 100, 50);+ expect(z).toEqual({ s: 2, x: -100, y: -50 });+ expect(zoomAt({ s: 16, x: 3, y: 4 }, 2, 10, 10)).toEqual({ s: 16, x: 3, y: 4 });+ });+});diff --git a/tests/desktop-os-system.test.js b/tests/desktop-os-system.test.jsnew file mode 100644index 000000000..afc2a1ac6--- /dev/null+++ b/tests/desktop-os-system.test.js@@ -0,0 +1,366 @@+// Terminal command language, Task Manager maths and Media Player queue logic.+// The terminal runs against an in-memory file system that implements the same+// API as src/desktop/os/fs.js (whose path helpers are used as-is).+import { describe, it, expect, beforeEach } from 'vitest';+import * as realFs from '../src/desktop/os/fs.js';+import { parseLine, runLine, createEnv, complete, suggest, editDistance, commonPrefix, formatBytes as tBytes } from '../src/desktop/os/apps/term-commands.js';+import * as perf from '../src/desktop/os/apps/perf-logic.js';+import * as pl from '../src/desktop/os/apps/playlist-logic.js';++function memFs() {+ const nodes = new Map();+ const dir = (path) => ({ path, name: realFs.nameOf(path), parent: realFs.parentOf(path), type: 'dir', size: 0, mtime: 1 });+ for (const d of ['/', '/Documents', '/Music', '/Trash']) nodes.set(d, dir(d));+ const meta = ({ data, ...n }) => n;+ return {+ normalize: realFs.normalize, join: realFs.join, nameOf: realFs.nameOf, parentOf: realFs.parentOf, kindOf: realFs.kindOf,+ async stat(p) {+ p = realFs.normalize(p);+ return nodes.has(p) ? meta(nodes.get(p)) : null;+ },+ async list(p) {+ p = realFs.normalize(p);+ return [...nodes.values()].filter((n) => n.path !== '/' && n.parent === (p === '/' ? '' : p) || (n.path !== '/' && realFs.parentOf(n.path) === p)).map(meta).sort((a, b) => a.name.localeCompare(b.name));+ },+ async read(p) {+ const n = nodes.get(realFs.normalize(p));+ return n && n.type === 'file' ? { node: meta(n), blob: new Blob([n.data]) } : null;+ },+ async readText(p) {+ return nodes.get(realFs.normalize(p))?.data ?? null;+ },+ async write(p, data) {+ p = realFs.normalize(p);+ if (!nodes.has(realFs.parentOf(p))) throw new Error(`Folder not found: ${realFs.parentOf(p)}`);+ const text = typeof data === 'string' ? data : await data.text();+ nodes.set(p, { path: p, name: realFs.nameOf(p), parent: realFs.parentOf(p), type: 'file', size: text.length, mtime: 2, data: text });+ },+ async mkdir(p) {+ p = realFs.normalize(p);+ if (nodes.has(p)) throw new Error('Something with that name already exists');+ nodes.set(p, dir(p));+ },+ async move(a, b) {+ a = realFs.normalize(a);+ b = realFs.normalize(b);+ const n = nodes.get(a);+ if (!n) throw new Error('Source not found');+ nodes.delete(a);+ nodes.set(b, { ...n, path: b, name: realFs.nameOf(b), parent: realFs.parentOf(b) });+ },+ async copy(a, b) {+ const n = nodes.get(realFs.normalize(a));+ if (!n) throw new Error('Source not found');+ b = realFs.normalize(b);+ nodes.set(b, { ...n, path: b, name: realFs.nameOf(b), parent: realFs.parentOf(b) });+ },+ async remove(p) {+ p = realFs.normalize(p);+ const n = nodes.get(p);+ nodes.delete(p);+ const t = `/Trash/${n.name}`;+ nodes.set(t, { ...n, path: t, parent: '/Trash' });+ return t;+ },+ async walk(p) {+ p = realFs.normalize(p);+ return [...nodes.values()].filter((n) => n.path !== p && (p === '/' ? n.path !== '/' : n.path.startsWith(`${p}/`))).map(meta);+ },+ _nodes: nodes,+ };+}++const res = (body, ok = true, status = 200) => ({ ok, status, statusText: ok ? 'OK' : 'Err', headers: { get: () => 'application/json' }, json: async () => body, text: async () => JSON.stringify(body) });++let env;+let fetched;+const sh = async (line) => {+ const r = await runLine(line, env);+ return { text: r.out.text(), code: r.code, r };+};++beforeEach(() => {+ fetched = [];+ let t = 0;+ const routes = {+ '/api/three-token/stats': { token: { price_usd: 0.00123, price_change_24h: -4.5, market_cap: 1230000, volume_24h: 5000, holders: 321 } },+ '/api/agents/public': { agents: [{ name: 'Nova', description: 'First' }, { name: 'Atlas', description: 'Second' }] },+ '/api/pump/launches': { data: { launches: [{ symbol: 'ABC', name: 'Alpha Coin', mint: 'So11111111111111111111111111111111111111112' }] } },+ };+ env = createEnv({+ fs: memFs(),+ fetch: async (url) => {+ fetched.push(String(url));+ const u = new URL(url);+ if (u.host === 'geocoding-api.open-meteo.com') return res({ results: [{ name: 'Paris', country: 'France', latitude: 1, longitude: 2 }] });+ if (u.host === 'api.open-meteo.com') return res({ current: { temperature_2m: 12, apparent_temperature: 10, relative_humidity_2m: 70, wind_speed_10m: 9, weather_code: 3 }, current_units: { temperature_2m: 'C', wind_speed_10m: 'km/h' }, daily: { time: ['2026-01-01'], temperature_2m_min: [5], temperature_2m_max: [13], weather_code: [61] } });+ if (u.pathname in routes) return res(routes[u.pathname]);+ if (u.pathname === '/boom') throw new TypeError('Failed to fetch');+ return res({ error: 'nope' }, false, 404);+ },+ perfNow: () => (t += 25),+ host: { userName: () => 'sam', apps: [{ id: 'notepad', title: 'Notepad' }], launchId: (id, o) => env.launched.push([id, o]), openPath: async (p) => env.launched.push(['open', p]), windows: () => [{ id: 'files', title: 'File Explorer' }], closeWindow: (id) => env.closed.push(id), setTheme: (m) => (env.theme = m), uptimeMs: () => 65000, sysinfo: () => ({ cores: 8, gpu: 'Test GPU', browser: 'Chrome 140' }) },+ baseUrl: 'https://three.ws/',+ });+ env.launched = [];+ env.closed = [];+});++describe('parseLine', () => {+ it('splits words, quotes, pipes and redirects', () => {+ expect(parseLine('echo "a b" c')).toEqual([{ argv: ['echo', 'a b', 'c'], redirect: null }]);+ expect(parseLine('cat f | grep x | wc -l').map((s) => s.argv[0])).toEqual(['cat', 'grep', 'wc']);+ expect(parseLine('echo hi >> out.txt')[0].redirect).toEqual({ mode: 'append', target: 'out.txt' });+ expect(parseLine("echo 'a | b'")[0].argv).toEqual(['echo', 'a | b']);+ });+ it('rejects broken syntax', () => {+ expect(() => parseLine('echo "oops')).toThrow(/quote/);+ expect(() => parseLine('ls |')).toThrow(/empty/);+ expect(() => parseLine('echo >')).toThrow(/file name/);+ });+});++describe('terminal on the file system', () => {+ it('echo redirect writes and appends, cat reads', async () => {+ await sh('echo hello > /Documents/a.txt');+ await sh('echo world >> /Documents/a.txt');+ expect((await sh('cat /Documents/a.txt')).text).toBe('hello\nworld\n');+ });+ it('cd and pwd resolve relative paths', async () => {+ await sh('cd Documents');+ expect((await sh('pwd')).text).toBe('/Documents\n');+ await sh('cd ..');+ expect(env.cwd).toBe('/');+ expect((await sh('cd nowhere')).code).toBe(1);+ });+ it('ls -l lists names, sizes and folders', async () => {+ await sh('echo abc > /Documents/x.txt');+ const { text } = await sh('ls -l /Documents');+ expect(text).toMatch(/x\.txt/);+ expect(text).toMatch(/4 B/);+ expect((await sh('ls /')).text).toContain('Documents/');+ });+ it('mkdir, touch, cp, mv, rm move through the file system', async () => {+ await sh('mkdir /Documents/sub');+ await sh('touch /Documents/sub/n.txt');+ await sh('cp /Documents/sub/n.txt /Documents/sub/m.txt');+ await sh('mv /Documents/sub/m.txt /Documents/k.txt');+ expect(await env.fs.stat('/Documents/k.txt')).toBeTruthy();+ const r = await sh('rm /Documents/sub');+ expect(r.code).toBe(1);+ expect((await sh('rm -r /Documents/sub')).code).toBe(0);+ expect(await env.fs.stat('/Trash/sub')).toBeTruthy();+ });+ it('pipes grep, head, tail and wc', async () => {+ await env.fs.write('/Documents/l.txt', 'one\ntwo\nthree\nfour\n');+ expect((await sh('cat /Documents/l.txt | grep o')).text).toBe('one\ntwo\nfour\n');+ expect((await sh('cat /Documents/l.txt | head -n 2')).text).toBe('one\ntwo\n');+ expect((await sh('tail -n 1 /Documents/l.txt')).text).toBe('four\n');+ expect((await sh('cat /Documents/l.txt | grep -v e | wc -l')).text.trim()).toBe('2');+ expect((await sh('grep -n thr /Documents/l.txt')).text).toBe('3:three\n');+ });+ it('find searches names and skips the Trash', async () => {+ await sh('echo x > /Documents/report.txt');+ await sh('rm /Documents/report.txt');+ await sh('echo x > /Documents/report2.txt');+ const { text } = await sh('find report');+ expect(text).toContain('/Documents/report2.txt');+ expect(text).not.toContain('/Trash');+ });+ it('open and edit call the desktop', async () => {+ await sh('echo x > /Documents/n.txt');+ await sh('open /Documents/n.txt');+ await sh('open notepad');+ await sh('edit /Documents/fresh.txt');+ expect(env.launched).toEqual([['open', '/Documents/n.txt'], ['notepad', undefined], ['notepad', { arg: '/Documents/fresh.txt' }]]);+ expect((await sh('open nothing')).code).toBe(1);+ });+ it('kill, theme, whoami, apps, history', async () => {+ expect((await sh('kill files')).text).toMatch(/Closed File Explorer/);+ expect(env.closed).toEqual(['files']);+ await sh('theme light');+ expect(env.theme).toBe('light');+ expect((await sh('theme purple')).code).toBe(1);+ expect((await sh('whoami')).text).toBe('sam\n');+ expect((await sh('apps')).text).toContain('notepad');+ });+ it('suggests the closest command for a typo', async () => {+ const r = await sh('lss');+ expect(r.code).toBe(127);+ expect(r.text).toContain('Did you mean "ls"');+ expect((await sh('zzzzzzzzzz')).text).toContain('Type help');+ });+ it('clear flags the screen', async () => {+ expect((await sh('clear')).r.cleared).toBe(true);+ });+});++describe('terminal network commands', () => {+ it('three price reads the real stats route', async () => {+ const { text } = await sh('three price');+ expect(fetched[0]).toBe('https://three.ws/api/three-token/stats');+ expect(text).toContain('$THREE');+ expect(text).toContain('-4.50% 24h');+ });+ it('three agents and launches use the real response shapes', async () => {+ expect((await sh('three agents 2')).text).toMatch(/Nova[\s\S]*Atlas/);+ expect(fetched[0]).toContain('/api/agents/public?limit=2');+ expect((await sh('three launches')).text).toMatch(/ABC\s+Alpha Coin\s+So1111\.\.\.1112/);+ });+ it('weather geocodes then forecasts', async () => {+ const { text } = await sh('weather Paris');+ expect(text).toContain('Paris');+ expect(text).toContain('Overcast');+ expect(fetched.some((u) => u.includes('api.open-meteo.com/v1/forecast'))).toBe(true);+ });+ it('curl prints status and body, and survives failure', async () => {+ const ok = await sh('curl /api/agents/public');+ expect(ok.text).toMatch(/^HTTP 200 OK/);+ const bad = await sh('curl /missing');+ expect(bad.code).toBe(22);+ const down = await sh('curl /boom');+ expect(down.code).toBe(7);+ expect(down.text).toMatch(/request failed/);+ });+ it('ping measures round trips', async () => {+ const { text, code } = await sh('ping');+ expect(code).toBe(0);+ expect(text).toMatch(/4 replies, min 25\.0 ms/);+ });+ it('reports an API failure instead of throwing', async () => {+ env.fetch = async () => res({}, false, 503);+ const r = await sh('three price');+ expect(r.code).toBe(1);+ expect(r.text).toMatch(/HTTP 503/);+ });+});++describe('completion and helpers', () => {+ it('completes commands and paths', async () => {+ expect((await complete('mkd', env)).matches).toEqual(['mkdir']);+ const r = await complete('cd Doc', env);+ expect(r.matches).toEqual(['Documents/']);+ expect(r.start).toBe(3);+ expect((await complete('ls | gr', env)).matches).toEqual(['grep']);+ });+ it('edit distance and suggestions', () => {+ expect(editDistance('kitten', 'sitting')).toBe(3);+ expect(suggest('hepl')).toBe('help');+ expect(commonPrefix(['abc', 'abd'])).toBe('ab');+ expect(tBytes(2048)).toBe('2.0 KB');+ });+});++describe('perf-logic', () => {+ it('ring buffer keeps the newest samples in order', () => {+ const b = new perf.RingBuffer(3);+ [1, 2, 3, 4].forEach((v) => b.push(v));+ expect(b.toArray()).toEqual([2, 3, 4]);+ expect(b.last()).toBe(4);+ expect(b.max()).toBe(4);+ const e = new perf.RingBuffer(3);+ e.push(null);+ expect(e.max()).toBe(0);+ });+ it('formats bytes, time and percentages', () => {+ expect(perf.formatBytes(1536)).toBe('1.50 KB');+ expect(perf.formatBytes(null)).toBe('n/a');+ expect(perf.formatMs(1500)).toBe('1.50 s');+ expect(perf.formatPct(0.256)).toBe('26%');+ expect(perf.formatDuration(65000)).toBe('1:05');+ });+ it('fps from frame times', () => {+ const t = Array.from({ length: 61 }, (_, i) => 5000 + i * (1000 / 60));+ expect(perf.fpsFromFrames(t, 6000)).toBeCloseTo(60, 0);+ expect(perf.fpsFromFrames([5990], 6000)).toBeNull();+ });+ it('main-thread load from long tasks and drift', () => {+ expect(perf.longTaskLoad([{ startTime: 100, duration: 250 }], 0, 1000)).toBeCloseTo(0.25);+ expect(perf.longTaskLoad([{ startTime: -100, duration: 300 }], 0, 1000)).toBeCloseTo(0.2);+ expect(perf.longTaskLoad([{ startTime: 0, duration: 5000 }], 0, 1000)).toBe(1);+ expect(perf.driftLoad(1000, 1300)).toBeCloseTo(0.3);+ expect(perf.driftLoad(1000, 900)).toBe(0);+ expect(perf.mainThreadLoad({ tasks: [{ startTime: 0, duration: 100 }], t0: 0, t1: 1000, expectedMs: 1000, actualMs: 1400 })).toBeCloseTo(0.4);+ });+ it('splits a total by weight', () => {+ const s = perf.shareTotal(100, [1, 3]);+ expect(s).toEqual([25, 75]);+ expect(perf.shareTotal(null, [1])).toEqual([0]);+ expect(perf.shareTotal(100, [0, 0])).toEqual([0, 0]);+ });+ it('summarizes resources and sorts rows with nulls last', () => {+ const sum = perf.summarizeResources([+ { name: 'https://a/x.js', initiatorType: 'script', duration: 50, transferSize: 1000 },+ { name: 'https://a/y.png', initiatorType: 'img', duration: 200, transferSize: 0 },+ { name: 'https://a/z.js', initiatorType: 'script', duration: 10, transferSize: 500 },+ ]);+ expect(sum.total).toBe(3);+ expect(sum.transfer).toBe(1500);+ expect(sum.byType[0]).toMatchObject({ type: 'script', count: 2, bytes: 1500 });+ expect(sum.slowest[0].name).toBe('https://a/y.png');+ const rows = perf.sortRows([{ k: 2 }, { k: null }, { k: 1 }], 'k', -1);+ expect(rows.map((r) => r.k)).toEqual([2, 1, null]);+ expect(perf.sortRows([{ k: 'b' }, { k: 'A' }], 'k').map((r) => r.k)).toEqual(['A', 'b']);+ });+ it('page timing', () => {+ expect(perf.pageTiming(null)).toBeNull();+ const t = perf.pageTiming({ domainLookupStart: 1, domainLookupEnd: 4, connectStart: 4, connectEnd: 10, responseStart: 30, domInteractive: 80, domContentLoadedEventEnd: 90, loadEventEnd: 0, transferSize: 5 });+ expect(t).toMatchObject({ dns: 3, connect: 6, ttfb: 30, load: null });+ });+});++describe('playlist-logic', () => {+ it('detects media kinds', () => {+ expect(pl.mediaKind('a.MP3')).toBe('audio');+ expect(pl.mediaKind('clip.webm')).toBe('video');+ expect(pl.mediaKind('x', 'audio/ogg')).toBe('audio');+ expect(pl.mediaKind('readme.txt')).toBeNull();+ });+ it('formats time', () => {+ expect(pl.formatTime(187)).toBe('3:07');+ expect(pl.formatTime(3729)).toBe('1:02:09');+ expect(pl.formatTime(NaN)).toBe('0:00');+ expect(pl.titleFromName('my_song.final.mp3')).toBe('my song.final');+ });+ it('builds orders; shuffle is a permutation starting with the current item', () => {+ expect(pl.buildOrder(4)).toEqual([0, 1, 2, 3]);+ const o = pl.buildOrder(6, { shuffle: true, current: 3, rng: () => 0.3 });+ expect(o[0]).toBe(3);+ expect([...o].sort()).toEqual([0, 1, 2, 3, 4, 5]);+ });+ it('next and previous honour repeat modes', () => {+ const o = [0, 1, 2];+ expect(pl.nextIndex(o, 0)).toBe(1);+ expect(pl.nextIndex(o, 2)).toBeNull();+ expect(pl.nextIndex(o, 2, { repeat: 'all' })).toBe(0);+ expect(pl.nextIndex(o, 1, { repeat: 'one', auto: true })).toBe(1);+ expect(pl.nextIndex(o, 1, { repeat: 'one', auto: false })).toBe(2);+ expect(pl.nextIndex([], 0)).toBeNull();+ expect(pl.prevIndex(o, 0)).toBe(0);+ expect(pl.prevIndex(o, 0, { repeat: 'all' })).toBe(2);+ expect(pl.prevIndex(o, 2)).toBe(1);+ });+ it('library keeps only media, audio before video, natural order', () => {+ const lib = pl.buildLibrary([+ { type: 'file', path: '/Videos/b.mp4', name: 'b.mp4' },+ { type: 'file', path: '/Music/10.mp3', name: '10.mp3' },+ { type: 'file', path: '/Music/2.mp3', name: '2.mp3' },+ { type: 'file', path: '/Music/n.txt', name: 'n.txt' },+ { type: 'dir', path: '/Music/sub', name: 'sub' },+ ]);+ expect(lib.map((l) => l.name)).toEqual(['2.mp3', '10.mp3', 'b.mp4']);+ });+ it('resume positions: remembered mid-track, dropped at the ends, bounded', () => {+ expect(pl.shouldRemember(3, 200)).toBe(false);+ expect(pl.shouldRemember(100, 200)).toBe(true);+ expect(pl.shouldRemember(198, 200)).toBe(false);+ expect(pl.shouldRemember(100, NaN)).toBe(false);+ let m = pl.updateResume({}, '/a', 100, 200);+ expect(m).toEqual({ '/a': 100 });+ m = pl.updateResume(m, '/a', 199, 200);+ expect(m).toEqual({});+ let big = {};+ for (let i = 0; i < 5; i++) big = pl.updateResume(big, `/f${i}`, 50, 200, 3);+ expect(Object.keys(big)).toEqual(['/f2', '/f3', '/f4']);+ });+});