From 92e4db8409a131eb7e8b5edb1e3085a452031b06 Mon Sep 17 00:00:00 2001 From: Suvankar Das <137081476+ShadowSD10@users.noreply.github.com> Date: Sat, 26 Sep 2026 02:29:07 +0530 Subject: [PATCH 1/3] feat: complete M1 runtime and boot shell (#1) * feat: add SHADOW OS runtime lifecycle * feat: add SHADOW OS boot shell * test: verify M1 boot workflows * chore: support cross-platform line endings * docs: record M1 implementation status * fix: refine m1 boot experience and system clock --- .prettierrc.json | 3 +- CHANGELOG.md | 9 + docs/AFTERBOOT_PROJECT.md | 14 +- src/bootstrap/host-model.ts | 15 - src/bootstrap/render-host.ts | 51 --- src/bootstrap/start-afterboot.ts | 55 ++- src/core/disposable.ts | 1 + src/core/events/typed-event.ts | 25 ++ src/core/runtime/shadow-runtime.ts | 211 +++++++++++ src/core/time/clock.ts | 6 + src/main.ts | 16 +- src/platform/browser-clock.ts | 14 + src/platform/motion-preference.ts | 3 + src/shell/shell-view.ts | 353 ++++++++++++++++++ src/shell/system-time.ts | 30 ++ src/styles/main.css | 493 ++++++++++++++++++++++--- tests/e2e/host.smoke.spec.ts | 154 +++++++- tests/helpers/fake-clock.ts | 74 ++++ tests/integration/runtime-boot.test.ts | 42 +++ tests/unit/host-model.test.ts | 17 - tests/unit/shadow-runtime.test.ts | 136 +++++++ tests/unit/system-time.test.ts | 33 ++ tests/unit/typed-event.test.ts | 35 ++ vite.config.ts | 2 +- 24 files changed, 1633 insertions(+), 159 deletions(-) delete mode 100644 src/bootstrap/host-model.ts delete mode 100644 src/bootstrap/render-host.ts create mode 100644 src/core/disposable.ts create mode 100644 src/core/events/typed-event.ts create mode 100644 src/core/runtime/shadow-runtime.ts create mode 100644 src/core/time/clock.ts create mode 100644 src/platform/browser-clock.ts create mode 100644 src/platform/motion-preference.ts create mode 100644 src/shell/shell-view.ts create mode 100644 src/shell/system-time.ts create mode 100644 tests/helpers/fake-clock.ts create mode 100644 tests/integration/runtime-boot.test.ts delete mode 100644 tests/unit/host-model.test.ts create mode 100644 tests/unit/shadow-runtime.test.ts create mode 100644 tests/unit/system-time.test.ts create mode 100644 tests/unit/typed-event.test.ts diff --git a/.prettierrc.json b/.prettierrc.json index d0280c2..fa7eb54 100644 --- a/.prettierrc.json +++ b/.prettierrc.json @@ -1,4 +1,5 @@ { "printWidth": 100, - "proseWrap": "preserve" + "proseWrap": "preserve", + "endOfLine": "auto" } diff --git a/CHANGELOG.md b/CHANGELOG.md index 3a64b3e..2c2aa3f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,8 +6,17 @@ All notable changes to AFTERBOOT are documented here. ### Added +- A DOM-independent SHADOW OS runtime with typed lifecycle snapshots, reset/failure commands, synchronous fact events, and explicit disposal. +- Injectable clock infrastructure with deterministic runtime, system-time, and boot/reset integration tests. +- An accessible staged boot-to-desktop shell with keyboard skip, reduced-motion handling, a browser-local system clock, and in-place restart behavior. +- Browser coverage for boot, reduced motion, desktop readiness, restart without reload, responsive layouts, console errors, and failed requests. - A minimal responsive AFTERBOOT host surface with SHADOW OS preparation state and startup fallback. - A Vite and strict TypeScript foundation using vanilla browser APIs and CSS. - ESLint, Prettier, Vitest, and Playwright quality tooling with unit and browser smoke coverage. - GitHub Actions workflows for continuous integration and static GitHub Pages deployment. - Contributor setup, command, browser-baseline, and static-deployment documentation. + +### Changed + +- Replaced the Milestone 0 static host projection with a disposable shell view driven exclusively by runtime snapshots. +- Made Prettier line-ending checks portable across Windows and Unix worktrees. diff --git a/docs/AFTERBOOT_PROJECT.md b/docs/AFTERBOOT_PROJECT.md index 3e97880..80f6d6a 100644 --- a/docs/AFTERBOOT_PROJECT.md +++ b/docs/AFTERBOOT_PROJECT.md @@ -2,7 +2,7 @@ > **Status:** Living architectural reference > **Last updated:** 2026-09-26 -> **Current stage:** Milestone 0 foundation implemented and locally verified; hosted workflow verification pending +> **Current stage:** Milestone 1 runtime and boot shell implemented and locally verified; final milestone review pending ## Status vocabulary @@ -142,6 +142,8 @@ Core services never depend on application UI or browser DOM nodes. A single composition root should construct services, register applications, seed initial state, and start the shell. Dependencies should be passed explicitly rather than imported from mutable global singletons. A small `OSContext`/`SystemServices` interface can expose approved capabilities to applications. +Milestone 1 implements this pattern for the lifecycle slice: the composition root injects a clock into the DOM-independent runtime, isolates browser time and motion queries behind platform adapters, and mounts the shell as a disposable projection of runtime snapshots. Boot progression is an explicit ordered stage model owned by the runtime, with one cancellable scheduled transition at a time; the shell only projects the current stage. + ### State model Each service owns its domain state and offers: @@ -168,19 +170,19 @@ No UI technology is permanently mandated at this stage. | Subsystem | Status | Purpose | | -------------------------- | ----------------------- | ----------------------------------------------------------------------------------------------------------------- | -| Bootstrap/composition root | Proposed | Builds the runtime, injects adapters, seeds initial data, registers applications, and starts SHADOW OS. | -| OS runtime | Proposed | Coordinates lifecycle and cross-service workflows without becoming a general-purpose god object. | -| Event system | Proposed | Provides typed, synchronous domain notifications with explicit subscription disposal. | +| Bootstrap/composition root | Implemented (M1 base) | Builds the runtime, injects adapters, seeds initial data, registers applications, and starts SHADOW OS. | +| OS runtime | Implemented (M1 base) | Coordinates lifecycle and cross-service workflows without becoming a general-purpose god object. | +| Event system | Implemented (M1 base) | Provides typed, synchronous domain notifications with explicit subscription disposal. | | Window manager | Proposed | Owns windows, focus order, geometry, modes, and lifecycle transitions. | | Application framework | Proposed | Defines app manifests, registration, launch requests, instances, and access to approved OS services. | | Virtual filesystem | Proposed | Owns paths, nodes, file contents, metadata, directory operations, and filesystem events. | | Process/task service | Proposed, later Phase 1 | Tracks running application instances and simulated system tasks; it does not represent real browser/OS processes. | -| Shell | Proposed | Renders desktop surfaces, task area, launcher, notifications, context menus, and global keyboard/focus behavior. | +| Shell | Partial (M1 boot shell) | Renders desktop surfaces, task area, launcher, notifications, context menus, and global keyboard/focus behavior. | | Settings/configuration | Proposed | Stores typed runtime preferences and system configuration, initially in memory. | | Notifications | Proposed | Accepts structured notifications and manages their visible lifecycle. | | Search | Future idea | Queries indexed resources through provider interfaces rather than knowing every subsystem. | | Scenario engine | Deferred to Phase 2 | Loads scenario definitions, applies setup, evaluates objectives, and records scenario state. | -| Platform adapters | Proposed | Isolate browser-specific APIs such as storage, time, animation, and viewport behavior where testability benefits. | +| Platform adapters | Partial (M1) | Isolate browser-specific APIs such as storage, time, animation, and viewport behavior where testability benefits. | ## 9. Subsystem responsibilities and boundaries diff --git a/src/bootstrap/host-model.ts b/src/bootstrap/host-model.ts deleted file mode 100644 index b2c201b..0000000 --- a/src/bootstrap/host-model.ts +++ /dev/null @@ -1,15 +0,0 @@ -export interface HostModel { - readonly productName: "AFTERBOOT"; - readonly systemName: "SHADOW OS"; - readonly phase: "preparing"; - readonly statusMessage: string; -} - -export function createInitialHostModel(): Readonly { - return Object.freeze({ - productName: "AFTERBOOT", - systemName: "SHADOW OS", - phase: "preparing", - statusMessage: "System environment is being prepared", - }); -} diff --git a/src/bootstrap/render-host.ts b/src/bootstrap/render-host.ts deleted file mode 100644 index 8ff275a..0000000 --- a/src/bootstrap/render-host.ts +++ /dev/null @@ -1,51 +0,0 @@ -import type { HostModel } from "./host-model"; - -export function renderHost(root: HTMLElement, model: HostModel): void { - const host = document.createElement("main"); - host.className = "host"; - - const header = document.createElement("header"); - header.className = "host__header"; - - const headerProduct = document.createElement("span"); - headerProduct.textContent = model.productName; - - const phase = document.createElement("span"); - phase.className = "host__phase"; - phase.textContent = `STATE / ${model.phase.toUpperCase()}`; - - header.append(headerProduct, phase); - - const identity = document.createElement("section"); - identity.className = "host__identity"; - identity.setAttribute("aria-labelledby", "afterboot-title"); - - const systemName = document.createElement("p"); - systemName.className = "host__system-name"; - systemName.textContent = model.systemName; - - const title = document.createElement("h1"); - title.id = "afterboot-title"; - title.textContent = model.productName; - - const status = document.createElement("div"); - status.className = "host__status"; - status.setAttribute("role", "status"); - - const indicator = document.createElement("span"); - indicator.className = "host__indicator"; - indicator.setAttribute("aria-hidden", "true"); - - const statusMessage = document.createElement("span"); - statusMessage.textContent = model.statusMessage; - - status.append(indicator, statusMessage); - identity.append(systemName, title, status); - - const footer = document.createElement("footer"); - footer.className = "host__footer"; - footer.textContent = "LOCAL SIMULATION / STATIC RUNTIME"; - - host.append(header, identity, footer); - root.replaceChildren(host); -} diff --git a/src/bootstrap/start-afterboot.ts b/src/bootstrap/start-afterboot.ts index a2e1ad0..9d094a8 100644 --- a/src/bootstrap/start-afterboot.ts +++ b/src/bootstrap/start-afterboot.ts @@ -1,14 +1,61 @@ -import { createInitialHostModel } from "./host-model"; -import { renderHost } from "./render-host"; +import { ShadowRuntime, type BootStageDurations } from "../core/runtime/shadow-runtime"; +import { BrowserClock } from "../platform/browser-clock"; +import { prefersReducedMotion } from "../platform/motion-preference"; +import { ShellView } from "../shell/shell-view"; -export function startAfterboot(document: Document): void { +const STANDARD_BOOT_STAGE_DURATIONS: BootStageDurations = { + "power-on": 700, + firmware: 1_600, + "system-initialization": 700, + "system-core": 900, + "system-clock": 850, + "display-system": 850, + "desktop-environment": 950, + finalizing: 650, +}; + +const REDUCED_MOTION_BOOT_STAGE_DURATIONS: BootStageDurations = { + "power-on": 300, + firmware: 700, + "system-initialization": 300, + "system-core": 350, + "system-clock": 350, + "display-system": 350, + "desktop-environment": 400, + finalizing: 300, +}; + +export interface AfterbootApplication { + readonly runtime: ShadowRuntime; + dispose(): void; +} + +export function startAfterboot(document: Document, browserWindow: Window): AfterbootApplication { const root = document.querySelector("#app"); if (!root) { throw new Error("AFTERBOOT host element was not found."); } - renderHost(root, createInitialHostModel()); + const clock = new BrowserClock(); + const reducedMotion = prefersReducedMotion(browserWindow); + const runtime = new ShadowRuntime(clock, { + bootStageDurations: reducedMotion + ? REDUCED_MOTION_BOOT_STAGE_DURATIONS + : STANDARD_BOOT_STAGE_DURATIONS, + }); + const shellView = new ShellView(root, document, runtime, clock, reducedMotion); + const disposeShell = shellView.mount(); + + runtime.boot(); + + return { + runtime, + dispose(): void { + disposeShell(); + runtime.dispose(); + }, + }; } export function renderStartupFailure(document: Document): void { diff --git a/src/core/disposable.ts b/src/core/disposable.ts new file mode 100644 index 0000000..7ee19cf --- /dev/null +++ b/src/core/disposable.ts @@ -0,0 +1 @@ +export type Disposable = () => void; diff --git a/src/core/events/typed-event.ts b/src/core/events/typed-event.ts new file mode 100644 index 0000000..b9476c3 --- /dev/null +++ b/src/core/events/typed-event.ts @@ -0,0 +1,25 @@ +import type { Disposable } from "../disposable"; + +export type EventListener = (event: Readonly) => void; + +export class TypedEvent { + readonly #listeners = new Set>(); + + subscribe(listener: EventListener): Disposable { + this.#listeners.add(listener); + + return () => { + this.#listeners.delete(listener); + }; + } + + emit(event: Readonly): void { + for (const listener of [...this.#listeners]) { + listener(event); + } + } + + clear(): void { + this.#listeners.clear(); + } +} diff --git a/src/core/runtime/shadow-runtime.ts b/src/core/runtime/shadow-runtime.ts new file mode 100644 index 0000000..8aa6e2a --- /dev/null +++ b/src/core/runtime/shadow-runtime.ts @@ -0,0 +1,211 @@ +import type { Disposable } from "../disposable"; +import { TypedEvent, type EventListener } from "../events/typed-event"; +import type { Clock } from "../time/clock"; + +export type RuntimePhase = "startup" | "booting" | "ready" | "resetting" | "failed"; + +export const BOOT_STAGES = [ + "power-on", + "firmware", + "system-initialization", + "system-core", + "system-clock", + "display-system", + "desktop-environment", + "finalizing", +] as const; + +export type BootStage = (typeof BOOT_STAGES)[number]; +export type BootStageDurations = Readonly>; + +export type RuntimeTransitionReason = + | "boot-requested" + | "boot-stage-advanced" + | "boot-completed" + | "boot-skipped" + | "reset-requested" + | "reset-completed" + | "runtime-failed"; + +export interface RuntimeSnapshot { + readonly phase: RuntimePhase; + readonly bootCycle: number; + readonly bootStage: BootStage | null; + readonly failureMessage: string | null; +} + +export interface RuntimeStateChanged { + readonly type: "runtime-state-changed"; + readonly previous: RuntimePhase; + readonly current: RuntimePhase; + readonly reason: RuntimeTransitionReason; + readonly occurredAt: number; + readonly snapshot: RuntimeSnapshot; +} + +export interface ShadowRuntimeOptions { + readonly bootStageDurations: BootStageDurations; +} + +const ALLOWED_TRANSITIONS: Readonly> = { + startup: ["booting", "resetting", "failed"], + booting: ["booting", "ready", "resetting", "failed"], + ready: ["resetting", "failed"], + resetting: ["startup", "failed"], + failed: ["resetting"], +}; + +export class RuntimeTransitionError extends Error { + constructor(previous: RuntimePhase, current: RuntimePhase) { + super(`Invalid SHADOW OS runtime transition: ${previous} -> ${current}`); + this.name = "RuntimeTransitionError"; + } +} + +export class ShadowRuntime { + readonly #clock: Clock; + readonly #options: ShadowRuntimeOptions; + readonly #stateChanged = new TypedEvent(); + #snapshot: RuntimeSnapshot = freezeSnapshot("startup", 0, null, null); + #cancelBoot: Disposable | null = null; + + constructor(clock: Clock, options: ShadowRuntimeOptions) { + for (const stage of BOOT_STAGES) { + const durationMs = options.bootStageDurations[stage]; + + if (!Number.isFinite(durationMs) || durationMs < 0) { + throw new RangeError(`Boot stage duration for ${stage} must be finite and non-negative.`); + } + } + + this.#clock = clock; + this.#options = options; + } + + get snapshot(): RuntimeSnapshot { + return this.#snapshot; + } + + onStateChanged(listener: EventListener): Disposable { + return this.#stateChanged.subscribe(listener); + } + + boot(): void { + if (this.#snapshot.phase !== "startup") { + throw new RuntimeTransitionError(this.#snapshot.phase, "booting"); + } + + const nextCycle = this.#snapshot.bootCycle + 1; + const firstStage = BOOT_STAGES[0]; + this.#transition("booting", "boot-requested", nextCycle, firstStage, null); + this.#scheduleStageCompletion(firstStage); + } + + skipBoot(): boolean { + if (this.#snapshot.phase !== "booting") { + return false; + } + + this.#cancelPendingBoot(); + this.#transition("ready", "boot-skipped", this.#snapshot.bootCycle, null, null); + return true; + } + + reset(): void { + this.#cancelPendingBoot(); + this.#transition("resetting", "reset-requested", this.#snapshot.bootCycle, null, null); + this.#transition("startup", "reset-completed", this.#snapshot.bootCycle, null, null); + this.boot(); + } + + fail(error: unknown): void { + if (this.#snapshot.phase === "failed") { + return; + } + + this.#cancelPendingBoot(); + this.#transition( + "failed", + "runtime-failed", + this.#snapshot.bootCycle, + null, + toFailureMessage(error), + ); + } + + dispose(): void { + this.#cancelPendingBoot(); + this.#stateChanged.clear(); + } + + #cancelPendingBoot(): void { + this.#cancelBoot?.(); + this.#cancelBoot = null; + } + + #scheduleStageCompletion(stage: BootStage): void { + this.#cancelBoot = this.#clock.schedule(() => { + this.#cancelBoot = null; + this.#advanceBoot(stage); + }, this.#options.bootStageDurations[stage]); + } + + #advanceBoot(completedStage: BootStage): void { + if (this.#snapshot.phase !== "booting" || this.#snapshot.bootStage !== completedStage) { + return; + } + + const nextStage = BOOT_STAGES[BOOT_STAGES.indexOf(completedStage) + 1]; + + if (!nextStage) { + this.#transition("ready", "boot-completed", this.#snapshot.bootCycle, null, null); + return; + } + + this.#transition("booting", "boot-stage-advanced", this.#snapshot.bootCycle, nextStage, null); + this.#scheduleStageCompletion(nextStage); + } + + #transition( + phase: RuntimePhase, + reason: RuntimeTransitionReason, + bootCycle: number, + bootStage: BootStage | null, + failureMessage: string | null, + ): void { + const previous = this.#snapshot.phase; + + if (!ALLOWED_TRANSITIONS[previous].includes(phase)) { + throw new RuntimeTransitionError(previous, phase); + } + + this.#snapshot = freezeSnapshot(phase, bootCycle, bootStage, failureMessage); + this.#stateChanged.emit( + Object.freeze({ + type: "runtime-state-changed", + previous, + current: phase, + reason, + occurredAt: this.#clock.now(), + snapshot: this.#snapshot, + }), + ); + } +} + +function freezeSnapshot( + phase: RuntimePhase, + bootCycle: number, + bootStage: BootStage | null, + failureMessage: string | null, +): RuntimeSnapshot { + return Object.freeze({ phase, bootCycle, bootStage, failureMessage }); +} + +function toFailureMessage(error: unknown): string { + if (error instanceof Error && error.message.length > 0) { + return error.message; + } + + return "An unknown runtime failure occurred."; +} diff --git a/src/core/time/clock.ts b/src/core/time/clock.ts new file mode 100644 index 0000000..bf63a4c --- /dev/null +++ b/src/core/time/clock.ts @@ -0,0 +1,6 @@ +import type { Disposable } from "../disposable"; + +export interface Clock { + now(): number; + schedule(task: () => void, delayMs: number): Disposable; +} diff --git a/src/main.ts b/src/main.ts index df23728..56d2b0c 100644 --- a/src/main.ts +++ b/src/main.ts @@ -1,7 +1,12 @@ import "./styles/main.css"; -import { renderStartupFailure, startAfterboot } from "./bootstrap/start-afterboot"; +import { + renderStartupFailure, + startAfterboot, + type AfterbootApplication, +} from "./bootstrap/start-afterboot"; let startupHasFailed = false; +let application: AfterbootApplication | null = null; function handleStartupFailure(error: unknown): void { if (startupHasFailed) { @@ -10,14 +15,19 @@ function handleStartupFailure(error: unknown): void { startupHasFailed = true; console.error("AFTERBOOT startup failed.", error); - renderStartupFailure(document); + + if (application) { + application.runtime.fail(error); + } else { + renderStartupFailure(document); + } } window.addEventListener("error", (event) => handleStartupFailure(event.error)); window.addEventListener("unhandledrejection", (event) => handleStartupFailure(event.reason)); try { - startAfterboot(document); + application = startAfterboot(document, window); } catch (error: unknown) { handleStartupFailure(error); } diff --git a/src/platform/browser-clock.ts b/src/platform/browser-clock.ts new file mode 100644 index 0000000..d861523 --- /dev/null +++ b/src/platform/browser-clock.ts @@ -0,0 +1,14 @@ +import type { Disposable } from "../core/disposable"; +import type { Clock } from "../core/time/clock"; + +export class BrowserClock implements Clock { + now(): number { + return Date.now(); + } + + schedule(task: () => void, delayMs: number): Disposable { + const timeoutId = globalThis.setTimeout(task, delayMs); + + return () => globalThis.clearTimeout(timeoutId); + } +} diff --git a/src/platform/motion-preference.ts b/src/platform/motion-preference.ts new file mode 100644 index 0000000..73df0b8 --- /dev/null +++ b/src/platform/motion-preference.ts @@ -0,0 +1,3 @@ +export function prefersReducedMotion(browserWindow: Window): boolean { + return browserWindow.matchMedia("(prefers-reduced-motion: reduce)").matches; +} diff --git a/src/shell/shell-view.ts b/src/shell/shell-view.ts new file mode 100644 index 0000000..cec1c18 --- /dev/null +++ b/src/shell/shell-view.ts @@ -0,0 +1,353 @@ +import type { Disposable } from "../core/disposable"; +import { + BOOT_STAGES, + type BootStage, + type RuntimeSnapshot, + type ShadowRuntime, +} from "../core/runtime/shadow-runtime"; +import type { Clock } from "../core/time/clock"; +import { formatSystemTime } from "./system-time"; + +const CLOCK_UPDATE_INTERVAL_MS = 1_000; +const SKIP_BOOT_ACTION = "skip-boot"; + +interface BootService { + readonly stage: BootStage; + readonly label: string; +} + +const BOOT_SERVICES: readonly BootService[] = [ + { stage: "system-core", label: "System core" }, + { stage: "system-clock", label: "System clock" }, + { stage: "display-system", label: "Display system" }, + { stage: "desktop-environment", label: "Desktop environment" }, +]; + +export class ShellView { + readonly #root: HTMLElement; + readonly #document: Document; + readonly #runtime: ShadowRuntime; + readonly #clock: Clock; + readonly #reducedMotion: boolean; + #unsubscribeRuntime: Disposable | null = null; + #cancelClockUpdate: Disposable | null = null; + + constructor( + root: HTMLElement, + document: Document, + runtime: ShadowRuntime, + clock: Clock, + reducedMotion: boolean, + ) { + this.#root = root; + this.#document = document; + this.#runtime = runtime; + this.#clock = clock; + this.#reducedMotion = reducedMotion; + } + + mount(): Disposable { + this.#document.documentElement.dataset.motion = this.#reducedMotion ? "reduced" : "full"; + this.#unsubscribeRuntime = this.#runtime.onStateChanged((event) => { + this.render(event.snapshot); + }); + this.render(this.#runtime.snapshot); + + return () => this.dispose(); + } + + render(snapshot: RuntimeSnapshot): void { + this.#cancelClock(); + this.#root.dataset.runtimePhase = snapshot.phase; + const restoreSkipFocus = + this.#document.activeElement instanceof HTMLElement && + this.#document.activeElement.dataset.action === SKIP_BOOT_ACTION; + let content: HTMLElement; + + if (snapshot.bootStage) { + this.#root.dataset.bootStage = snapshot.bootStage; + } else { + delete this.#root.dataset.bootStage; + } + + switch (snapshot.phase) { + case "startup": + case "resetting": + content = this.#renderStartup(snapshot); + break; + case "booting": + content = this.#renderBoot(snapshot); + break; + case "ready": + content = this.#renderDesktop(snapshot); + break; + case "failed": + content = this.#renderFailure(snapshot); + break; + } + + this.#root.replaceChildren(content); + + if (restoreSkipFocus) { + this.#root.querySelector(`[data-action="${SKIP_BOOT_ACTION}"]`)?.focus(); + } + } + + dispose(): void { + this.#cancelClock(); + this.#unsubscribeRuntime?.(); + this.#unsubscribeRuntime = null; + delete this.#document.documentElement.dataset.motion; + } + + #renderStartup(snapshot: RuntimeSnapshot): HTMLElement { + const main = this.#element("main", "startup-screen"); + main.setAttribute("aria-labelledby", "startup-title"); + + const systemName = this.#element("p", "system-mark", "SHADOW SYSTEMS"); + const title = this.#element("h1", "startup-screen__title", "System restart"); + title.id = "startup-title"; + const state = this.#element( + "p", + "startup-screen__state", + snapshot.phase === "resetting" ? "Clearing active system state" : "Powering on", + ); + state.setAttribute("role", "status"); + + main.append(systemName, title, state); + return main; + } + + #renderBoot(snapshot: RuntimeSnapshot): HTMLElement { + if (snapshot.bootStage === "power-on") { + return this.#renderPowerOn(); + } + + if (snapshot.bootStage === "firmware") { + return this.#renderFirmware(); + } + + const main = this.#element("main", "boot-screen"); + main.setAttribute("aria-labelledby", "boot-title"); + + const header = this.#element("header", "system-header"); + header.append( + this.#element("span", "system-header__brand", "SHADOW OS"), + this.#element("span", "system-header__state", "STATE / BOOTING"), + ); + + const content = this.#element("section", "boot-screen__content"); + const cycle = this.#element( + "p", + "boot-screen__cycle", + `BOOT CYCLE ${snapshot.bootCycle.toString().padStart(2, "0")}`, + ); + const title = this.#element("h1", "boot-screen__title", "System initialization"); + title.id = "boot-title"; + const status = this.#element( + "p", + "boot-screen__status", + snapshot.bootStage === "finalizing" + ? "System services ready. Preparing desktop environment." + : "Initializing system services", + ); + status.setAttribute("role", "status"); + + const diagnostics = this.#element("ol", "boot-diagnostics"); + diagnostics.setAttribute("aria-label", "System service initialization"); + diagnostics.append( + ...BOOT_SERVICES.map((service, index) => + this.#diagnostic(index + 1, service.label, this.#serviceState(snapshot, service.stage)), + ), + ); + + const skipButton = this.#createSkipButton("boot-screen__skip"); + + content.append(cycle, title, status, diagnostics, skipButton); + + const footer = this.#element("footer", "system-footer", "AFTERBOOT HOST / LOCAL SIMULATION"); + main.append(header, content, footer); + return main; + } + + #renderPowerOn(): HTMLElement { + const main = this.#element("main", "power-on-screen"); + main.setAttribute("aria-labelledby", "power-on-title"); + + const title = this.#element("h1", "visually-hidden", "SHADOW OS power on"); + title.id = "power-on-title"; + const signal = this.#element("p", "power-on-screen__signal", "DISPLAY SIGNAL / ACTIVE"); + signal.setAttribute("role", "status"); + main.append(title, signal, this.#createSkipButton("power-on-screen__skip")); + return main; + } + + #renderFirmware(): HTMLElement { + const main = this.#element("main", "firmware-screen"); + main.setAttribute("aria-labelledby", "firmware-title"); + + const output = this.#element("section", "firmware-screen__output"); + const title = this.#element("h1", "firmware-screen__title", "SHADOW SYSTEMS"); + title.id = "firmware-title"; + const revision = this.#element("p", "firmware-screen__revision", "FIRMWARE REVISION 1.0"); + const checks = this.#element("div", "firmware-checks"); + checks.append( + this.#firmwareCheck("MEMORY", "OK"), + this.#firmwareCheck("STORAGE", "ONLINE"), + this.#firmwareCheck("DISPLAY", "ONLINE"), + ); + const status = this.#element("p", "firmware-screen__status", "INITIALIZING SHADOW OS..."); + status.setAttribute("role", "status"); + output.append(title, revision, checks, status); + main.append(output, this.#createSkipButton("firmware-screen__skip")); + return main; + } + + #renderDesktop(snapshot: RuntimeSnapshot): HTMLElement { + const main = this.#element("main", "desktop-shell"); + main.setAttribute("aria-labelledby", "desktop-title"); + + const header = this.#element("header", "system-header desktop-shell__header"); + header.append( + this.#element("span", "system-header__brand", "SHADOW OS"), + this.#element("span", "system-header__state", "SYSTEM / READY"), + ); + + const workspace = this.#element("section", "desktop-shell__workspace"); + const identity = this.#element("div", "desktop-shell__identity"); + const environment = this.#element( + "p", + "desktop-shell__environment", + `ENVIRONMENT / CYCLE ${snapshot.bootCycle.toString().padStart(2, "0")}`, + ); + const title = this.#element("h1", "desktop-shell__title", "Desktop ready"); + title.id = "desktop-title"; + const description = this.#element( + "p", + "desktop-shell__description", + "Core runtime online. Workspace services awaiting installation.", + ); + identity.append(environment, title, description); + + const clockPanel = this.#element("section", "system-clock"); + clockPanel.setAttribute("aria-label", "SHADOW OS system clock"); + const clockLabel = this.#element("span", "system-clock__label", "LOCAL SYSTEM TIME"); + const time = this.#element("time", "system-clock__time"); + const date = this.#element("span", "system-clock__date"); + clockPanel.append(clockLabel, time, date); + this.#startClock(time, date); + + workspace.append(identity, clockPanel); + + const footer = this.#element("footer", "desktop-shell__footer"); + const runtimeState = this.#element("span", "desktop-shell__runtime", "RUNTIME STABLE"); + const resetButton = this.#element("button", "desktop-shell__reset", "Restart SHADOW OS"); + resetButton.type = "button"; + resetButton.title = "Restart SHADOW OS"; + resetButton.addEventListener("click", () => this.#runtime.reset()); + footer.append(runtimeState, resetButton); + + main.append(header, workspace, footer); + return main; + } + + #renderFailure(snapshot: RuntimeSnapshot): HTMLElement { + const main = this.#element("main", "runtime-failure"); + main.setAttribute("aria-labelledby", "failure-title"); + + const systemName = this.#element("p", "system-mark", "SHADOW OS"); + const title = this.#element("h1", "runtime-failure__title", "Runtime halted"); + title.id = "failure-title"; + const message = this.#element( + "p", + "runtime-failure__message", + snapshot.failureMessage ?? "An unknown runtime failure occurred.", + ); + message.setAttribute("role", "alert"); + const resetButton = this.#element("button", "runtime-failure__reset", "Restart SHADOW OS"); + resetButton.type = "button"; + resetButton.addEventListener("click", () => this.#runtime.reset()); + + main.append(systemName, title, message, resetButton); + return main; + } + + #diagnostic(index: number, label: string, state: string): HTMLElement { + const row = this.#element("li", "boot-diagnostics__row"); + row.append( + this.#element("span", "boot-diagnostics__index", index.toString().padStart(2, "0")), + this.#element("span", "boot-diagnostics__label", label), + this.#element( + "span", + `boot-diagnostics__state boot-diagnostics__state--${state}`, + `[ ${state} ]`, + ), + ); + return row; + } + + #firmwareCheck(label: string, state: string): HTMLElement { + const row = this.#element("p", "firmware-checks__row"); + row.append( + this.#element("span", "firmware-checks__label", label), + this.#element("span", "firmware-checks__leader", "................"), + this.#element("span", "firmware-checks__state", state), + ); + return row; + } + + #serviceState(snapshot: RuntimeSnapshot, serviceStage: BootStage): string { + const currentStageIndex = snapshot.bootStage ? BOOT_STAGES.indexOf(snapshot.bootStage) : -1; + const serviceStageIndex = BOOT_STAGES.indexOf(serviceStage); + + if (currentStageIndex < serviceStageIndex) { + return "waiting"; + } + + if (currentStageIndex === serviceStageIndex) { + return "initializing"; + } + + return "ok"; + } + + #createSkipButton(className: string): HTMLButtonElement { + const button = this.#element("button", className, "Skip boot sequence"); + button.type = "button"; + button.dataset.action = SKIP_BOOT_ACTION; + button.addEventListener("click", () => this.#runtime.skipBoot()); + return button; + } + + #startClock(timeElement: HTMLTimeElement, dateElement: HTMLElement): void { + const update = (): void => { + const systemTime = formatSystemTime(this.#clock.now()); + timeElement.dateTime = systemTime.iso; + timeElement.textContent = systemTime.time; + dateElement.textContent = systemTime.date; + this.#cancelClockUpdate = this.#clock.schedule(update, CLOCK_UPDATE_INTERVAL_MS); + }; + + update(); + } + + #cancelClock(): void { + this.#cancelClockUpdate?.(); + this.#cancelClockUpdate = null; + } + + #element( + tagName: K, + className: string, + text?: string, + ): HTMLElementTagNameMap[K] { + const element = this.#document.createElement(tagName); + element.className = className; + + if (text !== undefined) { + element.textContent = text; + } + + return element; + } +} diff --git a/src/shell/system-time.ts b/src/shell/system-time.ts new file mode 100644 index 0000000..17decab --- /dev/null +++ b/src/shell/system-time.ts @@ -0,0 +1,30 @@ +export interface SystemTime { + readonly iso: string; + readonly time: string; + readonly date: string; +} + +export function formatSystemTime(timestamp: number): SystemTime { + const value = new Date(timestamp); + + if (Number.isNaN(value.getTime())) { + throw new RangeError("System time requires a valid timestamp."); + } + + const year = value.getFullYear(); + const month = pad(value.getMonth() + 1); + const day = pad(value.getDate()); + const hours = pad(value.getHours()); + const minutes = pad(value.getMinutes()); + const seconds = pad(value.getSeconds()); + + return Object.freeze({ + iso: value.toISOString(), + time: `${hours}:${minutes}:${seconds}`, + date: `${year}.${month}.${day}`, + }); +} + +function pad(value: number): string { + return value.toString().padStart(2, "0"); +} diff --git a/src/styles/main.css b/src/styles/main.css index 830de93..4fa8e7d 100644 --- a/src/styles/main.css +++ b/src/styles/main.css @@ -7,11 +7,13 @@ text-rendering: optimizeLegibility; --color-surface: #080b0c; --color-panel: #101719; + --color-panel-raised: #162023; --color-ink: #edf7f1; --color-muted: #8fa39b; --color-signal: #8ff0bd; --color-alert: #ff6b55; --color-rule: #31423c; + --color-rule-strong: #536a61; --space-page: clamp(1.25rem, 4vw, 3.5rem); } @@ -36,34 +38,34 @@ body { background-size: 2.5rem 2.5rem; } -button, -input, -textarea, -select { +button { font: inherit; } -.host { - position: relative; - display: grid; - grid-template-rows: auto 1fr auto; - min-height: 100vh; - padding: var(--space-page); - isolation: isolate; +button:focus-visible { + outline: 2px solid var(--color-signal); + outline-offset: 0.25rem; } -.host::before { +button:hover { + border-color: var(--color-signal); + color: var(--color-ink); +} + +.visually-hidden { position: absolute; - z-index: -1; - inset: 0; - border-left: 0.35rem solid var(--color-alert); - background: linear-gradient(112deg, transparent 58%, rgb(143 240 189 / 7%) 58%); - content: ""; - pointer-events: none; + width: 1px; + height: 1px; + padding: 0; + margin: -1px; + overflow: hidden; + clip: rect(0, 0, 0, 0); + white-space: nowrap; + border: 0; } -.host__header, -.host__footer { +.system-header, +.system-footer { display: flex; align-items: center; justify-content: space-between; @@ -74,23 +76,29 @@ select { text-transform: uppercase; } -.host__header { +.system-header { padding-bottom: 1rem; border-bottom: 1px solid var(--color-rule); } -.host__phase { +.system-header__brand { + color: var(--color-ink); + font-weight: 700; +} + +.system-header__state { color: var(--color-signal); text-align: right; } -.host__identity { - align-self: center; - width: min(100%, 72rem); - padding-block: 4rem; +.system-footer { + justify-content: flex-end; + padding-top: 1rem; + border-top: 1px solid var(--color-rule); + text-align: right; } -.host__system-name { +.system-mark { margin: 0 0 1rem; color: var(--color-signal); font-size: 0.875rem; @@ -98,45 +106,319 @@ select { text-transform: uppercase; } -.host h1 { +.startup-screen, +.runtime-failure { + display: grid; + min-height: 100vh; + place-content: center; + padding: 2rem; + text-align: center; +} + +.startup-screen__title, +.runtime-failure__title { + margin: 0; + font-family: Impact, Haettenschweiler, "Arial Narrow Bold", sans-serif; + font-size: 4rem; + font-weight: 400; + line-height: 0.95; + letter-spacing: 0; + text-transform: uppercase; +} + +.startup-screen__state, +.runtime-failure__message { + margin: 1.5rem 0 0; + color: var(--color-muted); + line-height: 1.6; +} + +.power-on-screen, +.firmware-screen { + display: grid; + grid-template-rows: 1fr auto; + min-height: 100vh; + padding: var(--space-page); + color: #cbd6d1; + background: #010202; +} + +.power-on-screen__signal { + align-self: center; + margin: 0; + color: #839189; + font-size: 0.7rem; + text-align: center; + text-transform: uppercase; + animation: signal-in 300ms 200ms both; +} + +.power-on-screen__skip, +.firmware-screen__skip { + justify-self: end; + min-height: 2.75rem; + padding-inline: 1rem; + border: 1px solid #26302c; + border-radius: 0; + color: #718078; + background: transparent; + cursor: pointer; +} + +.firmware-screen__output { + align-self: start; + width: min(100%, 42rem); + padding-top: 2rem; +} + +.firmware-screen__title, +.firmware-screen__revision, +.firmware-screen__status, +.firmware-checks__row { + font-size: 0.8rem; + line-height: 1.65; + letter-spacing: 0; +} + +.firmware-screen__title { + margin: 0; + color: var(--color-ink); + font-weight: 700; +} + +.firmware-screen__revision { + margin: 0; + color: #839189; +} + +.firmware-checks { + margin-top: 2rem; +} + +.firmware-checks__row { + display: grid; + grid-template-columns: auto minmax(2rem, 1fr) auto; + gap: 0.5rem; + margin: 0; +} + +.firmware-checks__leader { + overflow: hidden; + color: #3a4841; +} + +.firmware-checks__state, +.firmware-screen__status { + color: var(--color-signal); +} + +.firmware-screen__status { + margin: 2rem 0 0; +} + +.boot-screen, +.desktop-shell { + position: relative; + display: grid; + grid-template-rows: auto 1fr auto; + min-height: 100vh; + padding: var(--space-page); + isolation: isolate; +} + +.boot-screen::before, +.desktop-shell::before { + position: absolute; + z-index: -1; + inset: 0; + border-left: 0.35rem solid var(--color-alert); + background: linear-gradient(112deg, transparent 58%, rgb(143 240 189 / 7%) 58%); + content: ""; + pointer-events: none; +} + +.boot-screen__content { + position: relative; + align-self: center; + width: min(100%, 68rem); + padding-block: 3rem; + overflow: hidden; +} + +.boot-screen__content::after { + position: absolute; + bottom: 0; + left: 0; + width: 45%; + height: 1px; + background: var(--color-signal); + box-shadow: 0 0 1rem rgb(143 240 189 / 60%); + content: ""; + animation: boot-scan 1.5s ease-in-out infinite alternate; +} + +.boot-screen__cycle, +.desktop-shell__environment { + margin: 0 0 1rem; + color: var(--color-signal); + font-size: 0.75rem; + line-height: 1.5; + text-transform: uppercase; +} + +.boot-screen__title, +.desktop-shell__title { max-width: 100%; margin: 0; color: var(--color-ink); font-family: Impact, Haettenschweiler, "Arial Narrow Bold", sans-serif; - font-size: clamp(3.4rem, 15vw, 11rem); + font-size: 7rem; font-weight: 400; - line-height: 0.82; + line-height: 0.86; letter-spacing: 0; + text-transform: uppercase; overflow-wrap: anywhere; } -.host__status { - display: flex; - align-items: center; - gap: 0.75rem; - width: fit-content; - max-width: 100%; - margin-top: clamp(2rem, 6vw, 4.5rem); - padding-top: 1rem; - border-top: 1px solid var(--color-rule); +.boot-screen__status { + margin: 2rem 0 0; color: var(--color-muted); font-size: 0.875rem; line-height: 1.6; } -.host__indicator { - flex: 0 0 auto; - width: 0.65rem; - height: 0.65rem; - background: var(--color-signal); - box-shadow: 0 0 1rem rgb(143 240 189 / 55%); +.boot-diagnostics { + width: min(100%, 38rem); + margin-top: 2rem; + padding: 0; + border-top: 1px solid var(--color-rule); + list-style: none; } -.host__footer { - justify-content: flex-end; +.boot-diagnostics__row { + display: grid; + grid-template-columns: 2rem minmax(0, 1fr) auto; + align-items: center; + gap: 1rem; + min-height: 2.5rem; + border-bottom: 1px solid var(--color-rule); + color: var(--color-muted); + font-size: 0.75rem; + text-transform: uppercase; +} + +.boot-diagnostics__index { + color: var(--color-signal); +} + +.boot-diagnostics__state { + text-align: right; +} + +.boot-diagnostics__state--waiting { + color: #65756e; +} + +.boot-diagnostics__state--initializing { + color: var(--color-ink); + animation: service-pulse 900ms ease-in-out infinite alternate; +} + +.boot-diagnostics__state--ok { + color: var(--color-signal); +} + +.boot-screen__skip, +.desktop-shell__reset, +.runtime-failure__reset { + min-height: 2.75rem; + border: 1px solid var(--color-rule-strong); + border-radius: 0; + color: var(--color-muted); + background: var(--color-panel); + cursor: pointer; +} + +.boot-screen__skip { + margin-top: 2rem; + padding-inline: 1.25rem; +} + +.desktop-shell { + background-image: linear-gradient(135deg, transparent 73%, rgb(255 107 85 / 5%) 73%); +} + +.desktop-shell__workspace { + display: grid; + grid-template-columns: minmax(0, 1fr) auto; + align-items: center; + gap: 4rem; + width: min(100%, 78rem); + padding-block: 3rem; + animation: desktop-enter 350ms ease-out both; +} + +.desktop-shell__description { + max-width: 36rem; + margin: 1.75rem 0 0; + color: var(--color-muted); + line-height: 1.7; +} + +.system-clock { + display: grid; + justify-items: end; + min-width: 17rem; + padding: 1.5rem 0 1.5rem 2rem; + border-left: 1px solid var(--color-rule-strong); +} + +.system-clock__label { + color: var(--color-muted); + font-size: 0.7rem; +} + +.system-clock__time { + margin-top: 0.5rem; + color: var(--color-signal); + font-family: Impact, Haettenschweiler, "Arial Narrow Bold", sans-serif; + font-size: 4rem; + line-height: 1; + letter-spacing: 0; +} + +.system-clock__date { + margin-top: 0.5rem; + color: var(--color-ink); + font-size: 0.875rem; +} + +.desktop-shell__footer { + display: flex; + align-items: center; + justify-content: space-between; + gap: 1rem; padding-top: 1rem; border-top: 1px solid var(--color-rule); - text-align: right; +} + +.desktop-shell__runtime { + color: var(--color-signal); + font-size: 0.75rem; +} + +.desktop-shell__reset, +.runtime-failure__reset { + padding-inline: 1rem; +} + +.runtime-failure__title { + color: var(--color-alert); +} + +.runtime-failure__reset { + justify-self: center; + margin-top: 2rem; } .startup-failure { @@ -144,7 +426,6 @@ select { min-height: 100vh; place-content: center; padding: 2rem; - color: var(--color-ink); text-align: center; } @@ -153,12 +434,120 @@ select { color: var(--color-alert); } +@keyframes boot-scan { + from { + transform: translateX(-100%); + } + + to { + transform: translateX(225%); + } +} + +@keyframes desktop-enter { + from { + opacity: 0; + transform: translateY(0.75rem); + } + + to { + opacity: 1; + transform: translateY(0); + } +} + +@keyframes signal-in { + from { + opacity: 0; + } + + to { + opacity: 1; + } +} + +@keyframes service-pulse { + from { + opacity: 0.55; + } + + to { + opacity: 1; + } +} + @media (max-width: 35rem) { - .host__header { + .system-header { align-items: flex-start; } - .host__identity { - padding-block: 3rem; + .boot-screen__content, + .desktop-shell__workspace { + padding-block: 2rem; + } + + .boot-screen__title, + .desktop-shell__title { + font-size: 3.5rem; + } + + .boot-diagnostics__row { + grid-template-columns: 1.5rem minmax(0, 1fr); + } + + .boot-diagnostics__state { + grid-column: 2; + padding-bottom: 0.65rem; + text-align: left; + } + + .firmware-screen__output { + padding-top: 1rem; + } + + .firmware-checks__row { + grid-template-columns: auto 1fr auto; + gap: 0.35rem; + } + + .desktop-shell__workspace { + grid-template-columns: 1fr; + align-content: center; + gap: 2.5rem; + } + + .system-clock { + justify-items: start; + min-width: 0; + padding: 1.25rem 0 0; + border-top: 1px solid var(--color-rule-strong); + border-left: 0; + } + + .system-clock__time { + font-size: 3.25rem; + } + + .desktop-shell__footer { + align-items: flex-start; + } + + .desktop-shell__reset { + max-width: 11rem; + } +} + +@media (prefers-reduced-motion: reduce) { + *, + *::before, + *::after { + scroll-behavior: auto !important; + animation-duration: 0.01ms !important; + animation-iteration-count: 1 !important; + } + + .boot-screen__content::after { + width: 100%; + transform: none; } } diff --git a/tests/e2e/host.smoke.spec.ts b/tests/e2e/host.smoke.spec.ts index b8a5071..9a618f9 100644 --- a/tests/e2e/host.smoke.spec.ts +++ b/tests/e2e/host.smoke.spec.ts @@ -1,20 +1,156 @@ -import { expect, test } from "@playwright/test"; +import { expect, test, type Page } from "@playwright/test"; -test("loads the AFTERBOOT host with SHADOW OS branding", async ({ page }) => { - const pageFailures: string[] = []; +function monitorPageFailures(page: Page): string[] { + const failures: string[] = []; page.on("console", (message) => { if (message.type() === "error") { - pageFailures.push(message.text()); + failures.push(`console: ${message.text()}`); } }); - page.on("pageerror", (error) => pageFailures.push(error.message)); + page.on("pageerror", (error) => failures.push(`page: ${error.message}`)); + page.on("requestfailed", (request) => { + failures.push(`request: ${request.url()} ${request.failure()?.errorText ?? "unknown failure"}`); + }); + + return failures; +} + +test("progresses from power-on through firmware and sequential services", async ({ page }) => { + const failures = monitorPageFailures(page); + const app = page.locator("#app"); const response = await page.goto("/"); expect(response?.ok()).toBe(true); - await expect(page.getByRole("heading", { name: "AFTERBOOT" })).toBeVisible(); - await expect(page.getByText("SHADOW OS")).toBeVisible(); - await expect(page.getByRole("status")).toContainText("being prepared"); - expect(pageFailures).toEqual([]); + await expect(page.getByRole("heading", { name: "SHADOW OS power on" })).toBeAttached(); + await expect(app).toHaveAttribute("data-boot-stage", "power-on"); + + await expect(page.getByRole("heading", { name: "SHADOW SYSTEMS" })).toBeVisible(); + await expect(app).toHaveAttribute("data-boot-stage", "firmware"); + await expect(page.getByText("MEMORY")).toBeVisible(); + + await expect(page.getByRole("heading", { name: "System initialization" })).toBeVisible(); + await expect(app).toHaveAttribute("data-boot-stage", "system-initialization"); + + const coreService = page.getByRole("listitem").filter({ hasText: "System core" }); + const clockService = page.getByRole("listitem").filter({ hasText: "System clock" }); + const displayService = page.getByRole("listitem").filter({ hasText: "Display system" }); + + await expect(app).toHaveAttribute("data-boot-stage", "system-core"); + await expect(coreService).toContainText("[ initializing ]", { ignoreCase: true }); + await expect(clockService).toContainText("[ waiting ]", { ignoreCase: true }); + + await expect(app).toHaveAttribute("data-boot-stage", "system-clock"); + await expect(coreService).toContainText("[ ok ]", { ignoreCase: true }); + await expect(clockService).toContainText("[ initializing ]", { ignoreCase: true }); + + await expect(app).toHaveAttribute("data-boot-stage", "display-system"); + await expect(clockService).toContainText("[ ok ]", { ignoreCase: true }); + await expect(displayService).toContainText("[ initializing ]", { ignoreCase: true }); + + await expect(app).toHaveAttribute("data-boot-stage", "finalizing"); + await expect(displayService).toContainText("[ ok ]", { ignoreCase: true }); + await expect(page.getByText("Preparing desktop environment")).toBeVisible(); + + await expect(page.getByRole("heading", { name: "Desktop ready" })).toBeVisible(); + await expect(app).toHaveAttribute("data-runtime-phase", "ready"); + expect(failures).toEqual([]); +}); + +test("boots into the desktop through a keyboard-accessible skip", async ({ page }) => { + const failures = monitorPageFailures(page); + await page.goto("/"); + + await page.keyboard.press("Tab"); + const skipButton = page.getByRole("button", { name: "Skip boot sequence" }); + await expect(skipButton).toBeFocused(); + await page.keyboard.press("Enter"); + + await expect(page.getByRole("heading", { name: "Desktop ready" })).toBeVisible(); + await expect(page.locator("#app")).toHaveAttribute("data-runtime-phase", "ready"); + expect(failures).toEqual([]); +}); + +test("reduced motion preserves a shorter coherent boot sequence", async ({ page }) => { + const failures = monitorPageFailures(page); + await page.emulateMedia({ reducedMotion: "reduce" }); + + await page.goto("/"); + + await expect(page.locator("html")).toHaveAttribute("data-motion", "reduced"); + await expect(page.getByRole("heading", { name: "SHADOW SYSTEMS" })).toBeVisible(); + await expect(page.getByRole("heading", { name: "System initialization" })).toBeVisible(); + await expect(page.locator("#app")).toHaveAttribute("data-boot-stage", "system-core"); + await expect(page.getByRole("heading", { name: "Desktop ready" })).toBeVisible(); + await expect(page.locator("#app")).toHaveAttribute("data-runtime-phase", "ready"); + expect(failures).toEqual([]); +}); + +test("resets and completes another boot cycle without reloading", async ({ page }) => { + const failures = monitorPageFailures(page); + await page.goto("/"); + await page.getByRole("button", { name: "Skip boot sequence" }).click(); + await expect(page.getByText("ENVIRONMENT / CYCLE 01")).toBeVisible(); + const navigationEntriesBefore = await page.evaluate( + () => performance.getEntriesByType("navigation").length, + ); + + await page.getByRole("button", { name: "Restart SHADOW OS" }).click(); + await expect(page.getByRole("heading", { name: "SHADOW OS power on" })).toBeAttached(); + await expect(page.locator("#app")).toHaveAttribute("data-boot-stage", "power-on"); + await page.getByRole("button", { name: "Skip boot sequence" }).click(); + + await expect(page.getByText("ENVIRONMENT / CYCLE 02")).toBeVisible(); + expect(await page.evaluate(() => performance.getEntriesByType("navigation").length)).toBe( + navigationEntriesBefore, + ); + expect(failures).toEqual([]); +}); + +test("displays the local browser time while preserving the ISO instant", async ({ page }) => { + const failures = monitorPageFailures(page); + await page.goto("/"); + await page.getByRole("button", { name: "Skip boot sequence" }).click(); + + const clockPanel = page.getByLabel("SHADOW OS system clock"); + const timeElement = clockPanel.getByRole("time"); + const iso = await timeElement.getAttribute("datetime"); + expect(iso).not.toBeNull(); + const expected = await page.evaluate((timestamp) => { + const value = new Date(timestamp!); + const pad = (part: number): string => part.toString().padStart(2, "0"); + + return { + time: `${pad(value.getHours())}:${pad(value.getMinutes())}:${pad(value.getSeconds())}`, + date: `${value.getFullYear()}.${pad(value.getMonth() + 1)}.${pad(value.getDate())}`, + }; + }, iso); + + await expect(timeElement).toHaveText(expected.time); + await expect(clockPanel.locator(".system-clock__date")).toHaveText(expected.date); + expect(new Date(iso!).toISOString()).toBe(iso); + expect(failures).toEqual([]); }); + +for (const viewport of [ + { name: "desktop", width: 1440, height: 900 }, + { name: "mobile", width: 360, height: 740 }, +] as const) { + test(`keeps the ready shell usable at the ${viewport.name} viewport`, async ({ page }) => { + const failures = monitorPageFailures(page); + await page.setViewportSize({ width: viewport.width, height: viewport.height }); + await page.goto("/"); + await page.getByRole("button", { name: "Skip boot sequence" }).click(); + + await expect(page.getByRole("heading", { name: "Desktop ready" })).toBeVisible(); + await expect(page.getByRole("button", { name: "Restart SHADOW OS" })).toBeVisible(); + const pageSize = await page.locator("body").evaluate((body) => ({ + scrollWidth: body.scrollWidth, + viewportWidth: document.documentElement.clientWidth, + })); + + expect(pageSize.scrollWidth).toBeLessThanOrEqual(pageSize.viewportWidth); + expect(failures).toEqual([]); + }); +} diff --git a/tests/helpers/fake-clock.ts b/tests/helpers/fake-clock.ts new file mode 100644 index 0000000..e00fda7 --- /dev/null +++ b/tests/helpers/fake-clock.ts @@ -0,0 +1,74 @@ +import type { Disposable } from "../../src/core/disposable"; +import type { Clock } from "../../src/core/time/clock"; + +interface ScheduledTask { + readonly id: number; + readonly runAt: number; + readonly task: () => void; + cancelled: boolean; +} + +export class FakeClock implements Clock { + readonly #tasks: ScheduledTask[] = []; + #currentTime: number; + #nextTaskId = 1; + + constructor(initialTime = 0) { + this.#currentTime = initialTime; + } + + now(): number { + return this.#currentTime; + } + + schedule(task: () => void, delayMs: number): Disposable { + if (!Number.isFinite(delayMs) || delayMs < 0) { + throw new RangeError("Scheduled delay must be a finite, non-negative number."); + } + + const scheduledTask: ScheduledTask = { + id: this.#nextTaskId, + runAt: this.#currentTime + delayMs, + task, + cancelled: false, + }; + this.#nextTaskId += 1; + this.#tasks.push(scheduledTask); + + return () => { + scheduledTask.cancelled = true; + }; + } + + advanceBy(durationMs: number): void { + if (!Number.isFinite(durationMs) || durationMs < 0) { + throw new RangeError("Advance duration must be a finite, non-negative number."); + } + + const targetTime = this.#currentTime + durationMs; + + while (true) { + const nextTask = this.#nextTaskAtOrBefore(targetTime); + + if (!nextTask) { + break; + } + + this.#currentTime = nextTask.runAt; + nextTask.cancelled = true; + nextTask.task(); + } + + this.#currentTime = targetTime; + } + + get pendingTaskCount(): number { + return this.#tasks.filter((task) => !task.cancelled).length; + } + + #nextTaskAtOrBefore(targetTime: number): ScheduledTask | undefined { + return this.#tasks + .filter((task) => !task.cancelled && task.runAt <= targetTime) + .sort((left, right) => left.runAt - right.runAt || left.id - right.id)[0]; + } +} diff --git a/tests/integration/runtime-boot.test.ts b/tests/integration/runtime-boot.test.ts new file mode 100644 index 0000000..abff21a --- /dev/null +++ b/tests/integration/runtime-boot.test.ts @@ -0,0 +1,42 @@ +import { describe, expect, it } from "vitest"; + +import { + BOOT_STAGES, + ShadowRuntime, + type BootStageDurations, +} from "../../src/core/runtime/shadow-runtime"; +import { FakeClock } from "../helpers/fake-clock"; + +const STAGE_DURATIONS: BootStageDurations = Object.fromEntries( + BOOT_STAGES.map((stage) => [stage, 10]), +) as unknown as BootStageDurations; + +describe("SHADOW OS boot workflow", () => { + it("boots, resets, and completes another boot cycle deterministically", () => { + const clock = new FakeClock(Date.UTC(2042, 6, 9, 4, 5, 6)); + const runtime = new ShadowRuntime(clock, { bootStageDurations: STAGE_DURATIONS }); + const observedStages: string[] = []; + const unsubscribe = runtime.onStateChanged((event) => { + if (event.snapshot.bootStage) { + observedStages.push(`${event.snapshot.bootCycle}:${event.snapshot.bootStage}`); + } + }); + + runtime.boot(); + clock.advanceBy(BOOT_STAGES.length * 10); + runtime.reset(); + clock.advanceBy(BOOT_STAGES.length * 10); + unsubscribe(); + + expect(runtime.snapshot).toEqual({ + phase: "ready", + bootCycle: 2, + bootStage: null, + failureMessage: null, + }); + expect(observedStages).toEqual([ + ...BOOT_STAGES.map((stage) => `1:${stage}`), + ...BOOT_STAGES.map((stage) => `2:${stage}`), + ]); + }); +}); diff --git a/tests/unit/host-model.test.ts b/tests/unit/host-model.test.ts deleted file mode 100644 index 2667b9d..0000000 --- a/tests/unit/host-model.test.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { describe, expect, it } from "vitest"; - -import { createInitialHostModel } from "../../src/bootstrap/host-model"; - -describe("createInitialHostModel", () => { - it("describes the initial AFTERBOOT preparation state", () => { - const model = createInitialHostModel(); - - expect(model).toEqual({ - productName: "AFTERBOOT", - systemName: "SHADOW OS", - phase: "preparing", - statusMessage: "System environment is being prepared", - }); - expect(Object.isFrozen(model)).toBe(true); - }); -}); diff --git a/tests/unit/shadow-runtime.test.ts b/tests/unit/shadow-runtime.test.ts new file mode 100644 index 0000000..cb6fb6c --- /dev/null +++ b/tests/unit/shadow-runtime.test.ts @@ -0,0 +1,136 @@ +import { describe, expect, it } from "vitest"; + +import { + BOOT_STAGES, + RuntimeTransitionError, + ShadowRuntime, + type BootStageDurations, + type RuntimeStateChanged, +} from "../../src/core/runtime/shadow-runtime"; +import { FakeClock } from "../helpers/fake-clock"; + +const TEST_STAGE_DURATIONS: BootStageDurations = { + "power-on": 10, + firmware: 20, + "system-initialization": 30, + "system-core": 40, + "system-clock": 50, + "display-system": 60, + "desktop-environment": 70, + finalizing: 80, +}; + +function createRuntime(clock = new FakeClock()): ShadowRuntime { + return new ShadowRuntime(clock, { bootStageDurations: TEST_STAGE_DURATIONS }); +} + +describe("ShadowRuntime", () => { + it("advances through every boot stage deterministically before becoming ready", () => { + const clock = new FakeClock(1_000); + const runtime = createRuntime(clock); + const observedStages: Array = []; + runtime.onStateChanged((event) => observedStages.push(event.snapshot.bootStage)); + + runtime.boot(); + + expect(runtime.snapshot).toEqual({ + phase: "booting", + bootCycle: 1, + bootStage: "power-on", + failureMessage: null, + }); + for (const stage of BOOT_STAGES) { + expect(runtime.snapshot.bootStage).toBe(stage); + clock.advanceBy(TEST_STAGE_DURATIONS[stage]); + } + + expect(runtime.snapshot.phase).toBe("ready"); + expect(runtime.snapshot.bootStage).toBeNull(); + expect(observedStages).toEqual([...BOOT_STAGES, null]); + }); + + it.each(["power-on", "system-core", "finalizing"] as const)( + "skips safely during %s and cancels pending progression", + (targetStage) => { + const clock = new FakeClock(); + const runtime = createRuntime(clock); + + runtime.boot(); + while (runtime.snapshot.bootStage !== targetStage) { + const currentStage = runtime.snapshot.bootStage; + expect(currentStage).not.toBeNull(); + clock.advanceBy(TEST_STAGE_DURATIONS[currentStage!]); + } + + expect(runtime.skipBoot()).toBe(true); + expect(runtime.snapshot.phase).toBe("ready"); + expect(runtime.snapshot.bootStage).toBeNull(); + expect(clock.pendingTaskCount).toBe(0); + clock.advanceBy(1_000); + expect(runtime.snapshot.phase).toBe("ready"); + expect(runtime.skipBoot()).toBe(false); + }, + ); + + it("resets into a fresh boot sequence without stale callbacks", () => { + const clock = new FakeClock(); + const runtime = createRuntime(clock); + const events: RuntimeStateChanged[] = []; + runtime.onStateChanged((event) => events.push(event)); + + runtime.boot(); + clock.advanceBy(TEST_STAGE_DURATIONS["power-on"]); + runtime.reset(); + + expect(runtime.snapshot).toEqual({ + phase: "booting", + bootCycle: 2, + bootStage: "power-on", + failureMessage: null, + }); + expect(clock.pendingTaskCount).toBe(1); + clock.advanceBy(TEST_STAGE_DURATIONS["power-on"]); + expect(runtime.snapshot.bootStage).toBe("firmware"); + expect(clock.pendingTaskCount).toBe(1); + expect(events.at(-1)?.snapshot.bootCycle).toBe(2); + }); + + it("enters failure state and recovers only through reset", () => { + const clock = new FakeClock(); + const runtime = createRuntime(clock); + + runtime.boot(); + runtime.fail(new Error("Boot integrity check failed.")); + + expect(runtime.snapshot).toEqual({ + phase: "failed", + bootCycle: 1, + bootStage: null, + failureMessage: "Boot integrity check failed.", + }); + expect(() => runtime.boot()).toThrow(RuntimeTransitionError); + + runtime.reset(); + expect(runtime.snapshot.phase).toBe("booting"); + expect(runtime.snapshot.bootCycle).toBe(2); + }); + + it("rejects invalid lifecycle transitions", () => { + const runtime = createRuntime(); + + runtime.boot(); + + expect(() => runtime.boot()).toThrow( + "Invalid SHADOW OS runtime transition: booting -> booting", + ); + }); + + it("rejects an invalid boot stage duration", () => { + expect( + () => + new ShadowRuntime(new FakeClock(), { + bootStageDurations: { ...TEST_STAGE_DURATIONS, firmware: Number.NaN }, + }), + ).toThrow("Boot stage duration for firmware must be finite and non-negative."); + }); +}); diff --git a/tests/unit/system-time.test.ts b/tests/unit/system-time.test.ts new file mode 100644 index 0000000..0ba3d79 --- /dev/null +++ b/tests/unit/system-time.test.ts @@ -0,0 +1,33 @@ +import { describe, expect, it } from "vitest"; + +import { formatSystemTime } from "../../src/shell/system-time"; + +describe("formatSystemTime", () => { + it("formats an injected timestamp in the machine's local timezone", () => { + const timestamp = new Date(2042, 6, 9, 4, 5, 6).getTime(); + + expect(formatSystemTime(timestamp)).toEqual({ + iso: new Date(timestamp).toISOString(), + time: "04:05:06", + date: "2042.07.09", + }); + }); + + it("uses the local date when an injected timestamp crosses local midnight", () => { + const beforeMidnight = new Date(2042, 11, 31, 23, 59, 59).getTime(); + const afterMidnight = beforeMidnight + 1_000; + + expect(formatSystemTime(beforeMidnight)).toMatchObject({ + time: "23:59:59", + date: "2042.12.31", + }); + expect(formatSystemTime(afterMidnight)).toMatchObject({ + time: "00:00:00", + date: "2043.01.01", + }); + }); + + it("rejects invalid timestamps", () => { + expect(() => formatSystemTime(Number.NaN)).toThrow("System time requires a valid timestamp."); + }); +}); diff --git a/tests/unit/typed-event.test.ts b/tests/unit/typed-event.test.ts new file mode 100644 index 0000000..ce64f1c --- /dev/null +++ b/tests/unit/typed-event.test.ts @@ -0,0 +1,35 @@ +import { describe, expect, it, vi } from "vitest"; + +import { TypedEvent } from "../../src/core/events/typed-event"; + +describe("TypedEvent", () => { + it("delivers facts synchronously and supports disposal", () => { + const event = new TypedEvent<{ readonly value: number }>(); + const listener = vi.fn(); + const unsubscribe = event.subscribe(listener); + + event.emit({ value: 1 }); + unsubscribe(); + event.emit({ value: 2 }); + + expect(listener).toHaveBeenCalledOnce(); + expect(listener).toHaveBeenCalledWith({ value: 1 }); + }); + + it("uses a listener snapshot when subscriptions change during dispatch", () => { + const event = new TypedEvent<{ readonly value: number }>(); + const calls: string[] = []; + let unsubscribeSecond = (): void => undefined; + + event.subscribe(() => { + calls.push("first"); + unsubscribeSecond(); + }); + unsubscribeSecond = event.subscribe(() => calls.push("second")); + + event.emit({ value: 1 }); + event.emit({ value: 2 }); + + expect(calls).toEqual(["first", "second", "first"]); + }); +}); diff --git a/vite.config.ts b/vite.config.ts index 7e686f9..0b69ba4 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -3,6 +3,6 @@ import { defineConfig } from "vitest/config"; export default defineConfig({ base: "./", test: { - include: ["tests/unit/**/*.test.ts"], + include: ["tests/{unit,integration}/**/*.test.ts"], }, }); From 0135404d61219ac1e3071123179d45911c04e44a Mon Sep 17 00:00:00 2001 From: Suvankar Das <137081476+ShadowSD10@users.noreply.github.com> Date: Sat, 26 Sep 2026 03:26:56 +0530 Subject: [PATCH 2/3] feat: complete M2 windows and applications (#2) * docs: record milestone 2 architecture plan * feat: implement milestone 2 windows and applications * docs: record milestone 2 implementation --- CHANGELOG.md | 7 + README.md | 15 +- docs/AFTERBOOT_PROJECT.md | 18 +- docs/SESSION_RESULTS.md | 582 ++++++++++++++++++ .../built-in/system-diagnostics.ts | 120 ++++ .../framework/application-manager.ts | 267 ++++++++ .../framework/application-registry.ts | 62 ++ src/applications/framework/application.ts | 74 +++ src/bootstrap/start-afterboot.ts | 29 +- src/core/identity/identifiers.ts | 39 ++ src/main.ts | 1 + src/shell/desktop/desktop-view.ts | 224 +++++++ src/shell/shell-view.ts | 105 +--- src/shell/windows/window-layer-view.ts | 311 ++++++++++ src/shell/windows/window-manager.ts | 405 ++++++++++++ src/shell/windows/window-state.ts | 63 ++ src/styles/windows.css | 358 +++++++++++ tests/e2e/windows-applications.spec.ts | 168 +++++ tests/helpers/fake-id-generator.ts | 11 + .../application-window-lifecycle.test.ts | 53 ++ tests/unit/application-manager.test.ts | 134 ++++ tests/unit/application-registry.test.ts | 47 ++ tests/unit/window-manager.test.ts | 166 +++++ 23 files changed, 3175 insertions(+), 84 deletions(-) create mode 100644 src/applications/built-in/system-diagnostics.ts create mode 100644 src/applications/framework/application-manager.ts create mode 100644 src/applications/framework/application-registry.ts create mode 100644 src/applications/framework/application.ts create mode 100644 src/core/identity/identifiers.ts create mode 100644 src/shell/desktop/desktop-view.ts create mode 100644 src/shell/windows/window-layer-view.ts create mode 100644 src/shell/windows/window-manager.ts create mode 100644 src/shell/windows/window-state.ts create mode 100644 src/styles/windows.css create mode 100644 tests/e2e/windows-applications.spec.ts create mode 100644 tests/helpers/fake-id-generator.ts create mode 100644 tests/integration/application-window-lifecycle.test.ts create mode 100644 tests/unit/application-manager.test.ts create mode 100644 tests/unit/application-registry.test.ts create mode 100644 tests/unit/window-manager.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 2c2aa3f..12657cb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,11 @@ All notable changes to AFTERBOOT are documented here. ### Added +- A DOM-independent window manager with deterministic placement, focus ordering, constrained movement/resizing, minimize, maximize, restore, close, responsive work-area handling, and typed fact events. +- A startup-only immutable application registry and single-instance application manager with stable identities, scoped auxiliary windows, primary-window close semantics, and explicit disposal/reset behavior. +- A responsive SHADOW OS desktop with an application launcher, open-window task strip, accessible window chrome, pointer dragging/resizing, desktop floating windows, and active-window small-screen presentation. +- A minimal System Diagnostics application that proves public application mounting and multi-window lifecycle behavior without introducing filesystem or later-milestone services. +- Unit, integration, and Playwright coverage for application/window lifecycle, geometry, focus, pointer interaction, keyboard controls, responsive behavior, and reset cleanup. - A DOM-independent SHADOW OS runtime with typed lifecycle snapshots, reset/failure commands, synchronous fact events, and explicit disposal. - Injectable clock infrastructure with deterministic runtime, system-time, and boot/reset integration tests. - An accessible staged boot-to-desktop shell with keyboard skip, reduced-motion handling, a browser-local system clock, and in-place restart behavior. @@ -18,5 +23,7 @@ All notable changes to AFTERBOOT are documented here. ### Changed +- Replaced the static ready-desktop projection with a disposable desktop/window projection composed from explicit application and window services. +- Resolved the initial M2 interaction policies: startup-only registration, single-instance applications, centered/cascaded desktop placement, primary-window disposal, pointer-only move/resize, no global window-cycling shortcut, and active-window small-screen presentation. - Replaced the Milestone 0 static host projection with a disposable shell view driven exclusively by runtime snapshots. - Made Prettier line-ending checks portable across Windows and Unix worktrees. diff --git a/README.md b/README.md index fce5d35..6d0696b 100644 --- a/README.md +++ b/README.md @@ -8,11 +8,11 @@ The product relationship is: AFTERBOOT → SHADOW OS → applications and scenarios ``` -AFTERBOOT is the host experience. SHADOW OS is the fictional operating system it will simulate. Applications, sandbox systems, and investigation scenarios will eventually operate inside SHADOW OS through shared OS services. Those systems are roadmap work and are not part of the current implementation. +AFTERBOOT is the host experience. SHADOW OS is the fictional operating system it simulates. The current implementation includes the first reusable application and window framework; filesystem, broader sandbox, and scenario systems remain roadmap work. ## Current Status -Milestone 0 — Foundation has been implemented and locally verified. AFTERBOOT is in active development and remains pre-v1.0. No `v0.1.0` release has been created yet. +Milestone 2 — Windows and Applications has been implemented and locally verified. Formal milestone review and CI verification remain pending. AFTERBOOT is in active development and remains pre-v1.0. No `v0.1.0` release has been created yet. The current implementation provides: @@ -20,9 +20,14 @@ The current implementation provides: - Vanilla TypeScript using standard DOM APIs and CSS - ESLint, Prettier, Vitest, and Playwright infrastructure - Continuous integration and GitHub Pages deployment workflows -- A minimal responsive AFTERBOOT / SHADOW OS preparation surface - -The full SHADOW OS runtime and desktop do not exist yet. +- A deterministic boot/reset runtime and responsive SHADOW OS desktop shell +- A DOM-independent window manager with focus, movement, resize, minimize, maximize, restore, and close transitions +- A startup-only application registry and single-instance application lifecycle +- Pointer-driven floating windows on desktop and active-window presentation on small screens +- Keyboard-accessible launch, focus, task restore, and window controls +- A minimal System Diagnostics application that proves application and multi-window lifecycle behavior + +The virtual filesystem, proof file applications, broader sandbox services, and scenarios do not exist yet. ## Project Direction diff --git a/docs/AFTERBOOT_PROJECT.md b/docs/AFTERBOOT_PROJECT.md index 80f6d6a..abdf1eb 100644 --- a/docs/AFTERBOOT_PROJECT.md +++ b/docs/AFTERBOOT_PROJECT.md @@ -2,7 +2,7 @@ > **Status:** Living architectural reference > **Last updated:** 2026-09-26 -> **Current stage:** Milestone 1 runtime and boot shell implemented and locally verified; final milestone review pending +> **Current stage:** Milestone 2 windows and applications implemented and locally verified; formal milestone review and CI verification pending ## Status vocabulary @@ -144,6 +144,8 @@ A single composition root should construct services, register applications, seed Milestone 1 implements this pattern for the lifecycle slice: the composition root injects a clock into the DOM-independent runtime, isolates browser time and motion queries behind platform adapters, and mounts the shell as a disposable projection of runtime snapshots. Boot progression is an explicit ordered stage model owned by the runtime, with one cancellable scheduled transition at a time; the shell only projects the current stage. +Milestone 2 extends the same pattern: the composition root constructs a startup-only application registry, application manager, and DOM-independent window manager. A disposable desktop view projects their snapshots, while a window-layer adapter owns DOM reconciliation and pointer capture. Application views receive only a host element and `Document` through a small mount/dispose contract. The initial application policy is single-instance; one instance may own a primary window plus scoped auxiliary windows. + ### State model Each service owns its domain state and offers: @@ -173,11 +175,11 @@ No UI technology is permanently mandated at this stage. | Bootstrap/composition root | Implemented (M1 base) | Builds the runtime, injects adapters, seeds initial data, registers applications, and starts SHADOW OS. | | OS runtime | Implemented (M1 base) | Coordinates lifecycle and cross-service workflows without becoming a general-purpose god object. | | Event system | Implemented (M1 base) | Provides typed, synchronous domain notifications with explicit subscription disposal. | -| Window manager | Proposed | Owns windows, focus order, geometry, modes, and lifecycle transitions. | -| Application framework | Proposed | Defines app manifests, registration, launch requests, instances, and access to approved OS services. | +| Window manager | Implemented (M2 base) | Owns windows, focus order, geometry, modes, and lifecycle transitions. | +| Application framework | Implemented (M2 base) | Defines immutable startup manifests, launch requests, single instances, scoped windows, and disposal. | | Virtual filesystem | Proposed | Owns paths, nodes, file contents, metadata, directory operations, and filesystem events. | | Process/task service | Proposed, later Phase 1 | Tracks running application instances and simulated system tasks; it does not represent real browser/OS processes. | -| Shell | Partial (M1 boot shell) | Renders desktop surfaces, task area, launcher, notifications, context menus, and global keyboard/focus behavior. | +| Shell | Partial (M2 shell) | Renders boot/desktop surfaces, launcher, task strip, application windows, and keyboard/pointer focus behavior. | | Settings/configuration | Proposed | Stores typed runtime preferences and system configuration, initially in memory. | | Notifications | Proposed | Accepts structured notifications and manages their visible lifecycle. | | Search | Future idea | Queries indexed resources through provider interfaces rather than knowing every subsystem. | @@ -351,12 +353,14 @@ Keep tests near modules if that proves easier to maintain; the exact test layout ### Milestone 2 — windows and applications +**Status:** Implemented and locally verified; formal review and CI verification pending. + - Implement window state transitions independently of the DOM. - Add focus, movement, resize, minimize, maximize, restore, and close behavior. - Define the application registry and application context. - Build one diagnostic/sample app to exercise lifecycle behavior. -**Exit criterion:** Multiple app instances can be operated through pointer and keyboard input with tested state transitions. +**Exit criterion:** Multiple application windows can be operated through pointer and keyboard-accessible controls with tested state transitions. M2 applications are single-instance; the diagnostic instance proves simultaneous primary and auxiliary windows. ### Milestone 3 — virtual filesystem and proof applications @@ -463,9 +467,9 @@ Root-level `CHANGELOG.md` records notable changes under `[Unreleased]` until a r | A-005 | Decided | TypeScript is the primary implementation language. | Supports explicit contracts and safe evolution of interconnected systems. | | A-006 | Decided | Begin with vanilla TypeScript rather than a UI framework. | Avoids committing to framework abstractions before UI needs are understood. Reassess after the first substantial apps. | | A-007 | Decided | Use Vite as the development/build tool. | Produces static assets, supports TypeScript well, and allows GitHub Pages base configuration. | -| A-008 | Proposed | Use service-owned state plus typed events rather than a universal global store. | Matches subsystem authority while keeping the first implementation small. | +| A-008 | Decided | Use service-owned state plus typed events rather than a universal global store. | Proven by the runtime, application, and window services without introducing shared mutable DOM state. | | A-009 | Proposed | Start with an in-memory filesystem behind a storage-neutral interface. | Meets the no-persistence requirement while preserving a future persistence path. | -| A-010 | Proposed | Use one composition root and explicit dependency injection without a DI framework. | Keeps construction understandable and tests easy to isolate. | +| A-010 | Decided | Use one composition root and explicit dependency injection without a DI framework. | Proven by deterministic application/window composition and isolated service tests. | | A-011 | Proposed | Avoid URL-based in-OS navigation initially. | The desktop is a stateful single experience and GitHub Pages has route fallback constraints. | | A-012 | Decided | Scenario infrastructure is deferred until foundational OS contracts are proven. | Prevents scenario needs from being guessed and baked into unstable systems. | diff --git a/docs/SESSION_RESULTS.md b/docs/SESSION_RESULTS.md index 1488525..58de7ad 100644 --- a/docs/SESSION_RESULTS.md +++ b/docs/SESSION_RESULTS.md @@ -98,3 +98,585 @@ Hosted CI and Pages execution remains pending repository initialization and push ## Release Status No `v0.1.0` changelog entry, Git tag, GitHub Release, or release claim was created. + +--- + +# Milestone 2 Architecture Review + +- **Date:** 2026-09-26 +- **Branch:** `feature/m2-windows-applications` +- **Starting commit:** `92e4db8409a131eb7e8b5edb1e3085a452031b06` +- **Purpose:** Define the implementation boundary and architecture for Milestone 2 before changing application code. +- **Implementation status:** Not implemented — architecture review only + +## Review Inputs + +### Documentation Inspected + +- `README.md` +- `CHANGELOG.md` +- `docs/AFTERBOOT_PROJECT.md` +- `docs/SESSION_RESULTS.md` +- `docs/AFTERBOOT_MILESTONES.md` from `origin/documentation`, read without switching branches because that file is not present on this feature branch + +The current feature branch contains stale M0-era status text in `README.md`, `docs/AFTERBOOT_PROJECT.md`, and the earlier session entry. The canonical milestone document on `origin/documentation` records M1 complete and M2 not started. This review uses the current implementation as the source of truth for implemented behavior and the canonical milestone checklist as the source of truth for M2 scope. No stale documentation was edited during this review. + +### Implementation Inspected + +- `src/bootstrap/` +- `src/core/`, including runtime, events, time, and disposal contracts +- `src/platform/` +- `src/shell/`, including the boot/desktop projection and system time +- `src/styles/main.css` +- all unit, integration, helper, and Playwright tests +- `package.json`, `tsconfig.json`, `vite.config.ts`, `eslint.config.js`, and `playwright.config.ts` + +There is currently no `src/applications/` directory, application registry, application instance model, window model, or window manager. + +## Implemented Baseline + +M1 provides a DOM-independent `ShadowRuntime`, immutable runtime snapshots, synchronous typed fact events, an injectable `Clock`, deterministic fake time, explicit `Disposable` cleanup, browser clock/motion adapters, and a disposable `ShellView`. The composition root owns construction and dependency wiring. The shell translates runtime snapshots into semantic DOM and delegates lifecycle commands back to the runtime. + +The existing patterns are suitable for M2: + +- mutable domain state has one owner; +- commands request changes and typed events report completed facts; +- subscriptions and scheduled work have explicit disposal; +- browser APIs stay outside core domain services; +- tests can drive time and state without rendering DOM; +- the composition root is the place for cross-service wiring. + +The main pressure point is `ShellView`: it currently renders the entire ready desktop and replaces its root whenever the runtime phase changes. Adding window state, pointer geometry, application instances, and focus logic directly to this class would mix lifecycle projection, domain ownership, and browser interaction. M2 should extract the ready-state desktop into a dedicated disposable view while leaving boot/failure behavior and `ShadowRuntime` ownership intact. + +## A. M2 Scope + +M2 will implement exactly the window and application capabilities required by the milestone gate: + +1. A serializable window model with stable identity, application-instance ownership, title, bounds, constraints, mode, restoration state, focus order, and active-window state. +2. A DOM-independent window manager with validated commands for open, focus, move, resize, minimize, maximize, restore, and close. +3. Pointer and keyboard adapters that translate browser input into window-manager commands without owning window state. +4. Immutable application manifests and a registry with duplicate detection and declared launch policies. +5. Stable application-instance identity plus explicit creation, launch, close, reset, and disposal behavior. +6. A narrow application context containing only approved M2 capabilities. +7. Coordination from application launch to instance creation to primary-window creation, and from close to window cleanup and instance disposal. +8. Multiple application instances/windows according to launch policy. +9. One diagnostic application that proves registration, context injection, launch, rendering, multiple-instance behavior, window lifecycle, and disposal without requiring later services. +10. Desktop-shell integration with a minimal application launcher, window layer, window chrome, and focus behavior. +11. Accessible pointer and keyboard operation and supported responsive desktop/mobile layouts. +12. Deterministic unit/integration tests and Playwright coverage for the complete M2 lifecycle. + +The first M2 application instance should own one primary window. The architecture may permit future additional windows, but M2 does not need multi-window-per-instance behavior to prove the required multiple-instance workflow. + +## B. Explicit Non-Scope + +M2 must not implement: + +- a virtual filesystem, paths, files, directories, metadata, storage adapters, or file associations; +- file manager or text editor/viewer proof applications, which belong to M3; +- simulated process/task state, process inspection, task-manager behavior, or controlled process termination, which belong to M4; +- settings, notifications, search, terminal commands, persistence, recovery bins, or broad shell polish, which belong to M4 or later; +- scenarios, objectives, world setup, narrative state, packages, or replay, which belong to M5/Phase 2; +- backend services, accounts, authentication, networking dependencies, host OS access, or real filesystem/process access; +- URL-based in-OS navigation unless separately decided later; +- audio or unrelated M1 boot redesign; +- a universal state store, dependency-injection framework, asynchronous event bus, event replay, or speculative plugin system; +- empty future directories or interfaces created only to resemble the target project tree. + +The diagnostic application must use only M2 capabilities. It should not imitate future process monitoring, files, notifications, or settings merely to look more substantial. + +## C. Proposed Module/File Changes + +The paths below are a plan, not files created by this review. + +### New Domain and Service Files + +- `src/core/identifiers/id-generator.ts` + - Defines an injectable ID-generation contract and a deterministic sequential implementation. + - Belongs in core because both application and window services need IDs without depending on browser APIs or each other. + +- `src/shell/windows/window-state.ts` + - Defines branded `WindowId`, bounds, constraints, modes, restoration data, individual window state, and immutable manager snapshots. + - Belongs under shell/windows because window geometry and focus are shell-owned domain state, not application or runtime lifecycle state. + +- `src/shell/windows/window-manager.ts` + - Owns window state, work-area constraints, focus ordering, transitions, validation errors, snapshots, events, reset, and disposal. + - Belongs under shell/windows because it is the single authority for the window domain and contains no DOM nodes. + +- `src/applications/framework/application.ts` + - Defines branded application/application-instance IDs, immutable manifests, launch policy, application definition/instance contracts, public context, and serializable instance snapshots. + - Belongs in the application framework because these contracts describe applications independently from registry and rendering details. + +- `src/applications/framework/application-registry.ts` + - Registers immutable definitions, rejects duplicate IDs, and resolves/list manifests without owning running instances. + - Belongs in the framework because registration data and running lifecycle have separate authorities. + +- `src/applications/framework/application-manager.ts` + - Owns running application instances, enforces launch policies, creates the primary window through `WindowManager`, coordinates close/disposal, exposes snapshots/queries, and emits lifecycle facts. + - Belongs in the framework because application-instance lifecycle must not be owned by the shell DOM or `ShadowRuntime`. + +### New UI Adapter and Proof-Application Files + +- `src/shell/desktop/desktop-view.ts` + - Owns the ready-state desktop projection, launcher surface, system clock, window-layer mount, reset command, subscriptions, and view cleanup. + - Belongs under shell/desktop because it composes shell surfaces but does not own application/window domain state. + +- `src/shell/windows/window-layer-view.ts` + - Projects window snapshots, mounts application content, renders accessible window chrome, manages pointer capture, and translates pointer/keyboard input into commands. + - Belongs under shell/windows as the browser adapter for the DOM-independent manager. + +- `src/applications/built-in/system-diagnostics.ts` + - Defines the single M2 diagnostic manifest/definition and a minimal view that exposes safe instance/context facts useful for lifecycle verification. + - Belongs under built-in applications because it is product-visible proof code, not framework behavior. It must not present filesystem, process, settings, or notification features. + +- `src/styles/windows.css` + - Contains stable work-area, window chrome, controls, focus, geometry, interaction, reduced-motion, and responsive rules. + - Belongs in styles as a focused extension of the existing visual system rather than further growing one monolithic stylesheet. + +### Existing Files to Modify During Implementation + +- `src/bootstrap/start-afterboot.ts` + - Construct the ID generator, window manager, registry, application manager, diagnostic definition, and desktop projection; coordinate runtime reset/failure/disposal with M2 cleanup. + - This is the established composition root and should remain the only wiring location. + +- `src/shell/shell-view.ts` + - Retain startup/boot/failure projection but delegate ready-state rendering to `DesktopView`; dispose the active desktop projection before leaving ready state. + - This prevents the current shell class from becoming the window/application state owner. + +- `src/styles/main.css` + - Import the focused window stylesheet and adjust the current static ready workspace into a stable desktop work area while preserving M1 boot/failure styles. + +- `tests/e2e/host.smoke.spec.ts` + - Preserve existing M1 regression coverage. Add shared failure-monitor helpers only if reuse with a separate M2 specification materially reduces duplication. + +### New Test Files + +- `tests/helpers/fake-id-generator.ts`: deterministic identifiers and assertions for instance/window creation order. +- `tests/unit/window-manager.test.ts`: every transition, invalid transition, geometry constraint, focus-order, and work-area behavior. +- `tests/unit/application-registry.test.ts`: immutable registration, lookup/listing, duplicate and unknown-ID handling. +- `tests/unit/application-manager.test.ts`: launch policy, instance identity, rollback, close, reset, and exactly-once disposal. +- `tests/integration/application-window-lifecycle.test.ts`: registry -> launch -> instance -> window -> focus/transition -> close/dispose without DOM coupling. +- `tests/e2e/windows-applications.spec.ts`: complete pointer, keyboard, multiple-window, responsive, console, and request-failure workflows. + +No package, TypeScript, Vite, ESLint, or Playwright configuration change is expected. The existing test globs and browser project already cover the proposed test locations. + +## D. Data/State Model + +### Window State + +`WindowManager` is the sole mutable owner. Its public snapshot should be deeply read-only and contain serializable values only. + +Suggested concepts: + +- `WindowId`: branded stable identifier. +- `ApplicationInstanceId`: branded owner identifier; not interchangeable with `WindowId` or application definition ID. +- `WindowBounds`: finite `x`, `y`, `width`, and `height` values. +- `WindowConstraints`: minimum dimensions and optional maximum dimensions. +- `WindowMode`: `normal`, `minimized`, or `maximized`. +- `restoreBounds`: the normal bounds retained while maximized. +- `restoreMode`: whether restoring a minimized window returns it to normal or maximized. +- `focusOrder`: deterministic monotonic ordering used to derive stacking. +- `WindowState`: ID, owner, title, current bounds, mode, restoration data, focus order, and constraints. +- `WindowManagerSnapshot`: ordered read-only windows plus `activeWindowId` and current work area. + +The manager should enforce finite geometry, positive dimensions, constraints, work-area clamping, one active non-minimized window, and deterministic selection of the next active window after minimize/close. DOM elements, event handlers, pointer coordinates, application controllers, and render callbacks must never appear in snapshots. + +### Application State + +`ApplicationRegistry` owns immutable definitions and metadata. `ApplicationManager` separately owns running instance lifecycle. + +Suggested concepts: + +- `ApplicationId`: stable branded manifest identifier. +- `ApplicationInstanceId`: stable branded running-instance identifier. +- `ApplicationLaunchPolicy`: initially the smallest policies needed by the milestone, recommended as `single-instance` and `multiple-instance`. +- `ApplicationManifest`: frozen ID, display name, optional icon token, launch policy, and default primary-window metadata/constraints. Do not add file types/actions before M3 requires them. +- `ApplicationDefinition`: manifest plus a factory that receives the approved context. +- `ApplicationInstance`: private controller/view handle with stable IDs and idempotent `dispose()`. +- `ApplicationInstanceState`: serializable ID, application ID, primary window ID, and lifecycle status exposed in snapshots. +- `ApplicationManagerSnapshot`: read-only running instances. + +Factories/view handles may contain behavior privately, but registry/manager snapshots must not contain DOM nodes. Launch should be atomic: if instance creation or primary-window opening fails, dispose partial work and leave both managers unchanged. + +### Ownership Summary + +- `ShadowRuntime`: OS boot/reset/failure phase only. +- `ApplicationRegistry`: immutable available-application definitions. +- `ApplicationManager`: running application instances and launch/close orchestration. +- `WindowManager`: window state, geometry, modes, focus, and stacking. +- `DesktopView`: ready-shell DOM and subscriptions. +- `WindowLayerView`: rendered windows and browser input adaptation. +- diagnostic application: only its own private presentation/controller state. +- composition root: dependency wiring and cross-service cleanup policy. + +## E. Public APIs + +Exact names may be refined during implementation, but the capability boundaries should remain: + +### `IdGenerator` + +- `next(scope): string` or a typed factory wrapper used by the owning service. +- Must be injectable so unit tests can predict every generated ID. + +### `WindowManager` + +- read-only `snapshot`. +- `open(request): WindowId`. +- `focus(windowId): boolean`. +- `move(windowId, position): boolean`. +- `resize(windowId, boundsOrSize): boolean`. +- `minimize(windowId): boolean`. +- `maximize(windowId): boolean`. +- `restore(windowId): boolean`. +- `close(windowId): boolean`. +- `setWorkArea(bounds): void` for responsive constraint changes. +- `onStateChanged(listener): Disposable`. +- `reset()` and `dispose()`. + +Invalid IDs, impossible geometry, and forbidden mode transitions should have explicit typed errors or consistently documented no-op results. The implementation should choose one rule per command category and test it; it must not silently produce invalid state. + +### `ApplicationRegistry` + +- `register(definition): Disposable` only if dynamic unregistration is genuinely needed by composition/tests; otherwise registration can remain startup-only. +- `get(applicationId)` and `list()` as read-only queries. +- Duplicate registration must fail explicitly. +- No event is needed while registration is static at startup; adding one without a consumer would be speculative. + +### `ApplicationManager` + +- read-only `snapshot`. +- `launch(applicationId): ApplicationInstanceId`. +- `closeInstance(instanceId): boolean`. +- `closeWindow(windowId): boolean`, coordinating primary-window close with instance disposal. +- `getInstance(instanceId)` or a narrower view-resolution query for the shell adapter. +- `onStateChanged(listener): Disposable`. +- `reset()` and `dispose()`. + +For a `single-instance` manifest, `launch` should focus and return the existing instance instead of creating a duplicate. For `multiple-instance`, each request receives a new instance and primary window. + +### `ApplicationContext` + +The context must be narrower than internal system services. For M2 it should contain only what the diagnostic app needs, such as: + +- its own `applicationId` and `instanceId`; +- the injected read-only `Clock` if the diagnostic app uses time; +- scoped lifecycle/window requests that cannot mutate another application's windows. + +Do not expose filesystem, process, settings, notifications, registry mutation, unrestricted `WindowManager`, `Document`, or global `Window` through the public application context. + +### UI Adapter Contracts + +Application content should use a small mount contract such as `mount(host, document): Disposable`. This permits DOM UI without placing DOM state in application/window snapshots. The window layer owns the host element and lifecycle; application content owns only listeners/resources inside its host. + +## F. Event Model + +Commands remain synchronous requests. Events remain synchronous typed facts emitted only after successful changes, following the existing `TypedEvent` pattern. + +### Window Facts + +A focused union or a state-changed event with a strict reason union should cover: + +- `window-opened`; +- `window-focused`; +- `window-moved`; +- `window-resized`; +- `window-minimized`; +- `window-maximized`; +- `window-restored`; +- `window-closed`; +- `window-work-area-changed` when responsive geometry changes state. + +Each event should include the resulting immutable manager snapshot and the affected window ID/state where applicable. `WindowManager` owns and emits these events. `WindowLayerView` consumes them to render; `ApplicationManager` should not infer domain facts from DOM events. + +### Application Facts + +`ApplicationManager` should emit only facts with consumers: + +- `application-launched` after instance and window creation succeed; +- `application-focused-existing` if useful for observing single-instance launch policy; +- `application-closed` after windows close and disposal completes; +- `applications-reset` after all instances are disposed during reset. + +The desktop launcher/window layer consumes application snapshots for presentation and view mounting. Registry events are unnecessary while manifests are fixed at startup. + +### Command Flow + +- launcher intent -> `ApplicationManager.launch`; +- pointer/focus intent -> `WindowManager.focus`; +- drag/resize intent -> `WindowManager.move`/`resize`; +- chrome minimize/maximize/restore intent -> corresponding window-manager command; +- chrome close intent -> `ApplicationManager.closeWindow`, which coordinates window close and instance disposal; +- runtime reset/failure/disposal fact -> composition-level cleanup of application/window services and their views. + +The runtime must not absorb window or application snapshots. Cross-service cleanup belongs in bootstrap composition, keeping `ShadowRuntime` focused on OS lifecycle. + +## G. UI Behavior + +### Opening an Application + +- The ready desktop exposes a minimal launcher containing the registered diagnostic app. +- Launcher controls use native buttons with accessible names and visible focus. +- Activating the launcher asks `ApplicationManager` to launch; the registry resolves the definition, the manager creates an instance, and the window manager opens/focuses its primary window. +- A single-instance policy focuses an existing window. A multiple-instance policy creates a distinct instance/window. The diagnostic app should exercise the policy selected for M2 tests without implying future process behavior. + +### Focusing and Multiple Windows + +- Pointer down or `focusin` within a window requests focus through `WindowManager`. +- The active window has the highest focus order, clear visual treatment, and an accessible active-state cue that does not rely on color alone. +- Opening/focusing never reorders DOM state as the source of truth; DOM order/style derives from the manager snapshot. +- Closing or minimizing the active window activates the highest eligible remaining window deterministically. + +### Moving and Resizing + +- Pointer drag begins only from the title bar, uses pointer capture, and sends clamped position commands. +- Pointer resize uses explicit handles with stable hit areas and sends constrained size/bounds commands. +- Browser pointer state remains ephemeral in `WindowLayerView`; committed geometry belongs to `WindowManager`. +- M2 needs a keyboard equivalent. Recommended behavior is a keyboard-accessible window action menu: choosing Move or Resize enters a mode where arrow keys adjust geometry, Enter commits, and Escape restores the starting bounds. This decision should be confirmed before implementation. + +### Minimize, Maximize, Restore, and Close + +- Window chrome provides semantic buttons with accessible names/tooltips and fixed dimensions. +- Minimize removes the window from the visible work area without destroying its application instance. +- Maximize stores normal bounds and fills the current work area. +- Restore returns to the correct previous normal/maximized state, including minimize-from-maximized behavior. +- Close routes through application lifecycle coordination. Closing the primary/only M2 window disposes its application instance exactly once. + +### Keyboard Interaction + +- Tab/Shift+Tab reaches launcher and window controls in a predictable order. +- Enter/Space activates launcher and native window-control buttons. +- A documented shell command such as Alt+Tab cycles focus through non-minimized windows; the exact shortcut must avoid browser conflicts and be confirmed before implementation. +- Moving and resizing must have the explicit keyboard mode described above or another reviewed equivalent. +- Focus returns to a sensible launcher or next-window target after close/minimize; no focus is left on removed DOM. +- Escape exits temporary move/resize interaction without mutating committed state. + +### Responsive Layouts + +- Desktop layouts use bounded floating windows inside a measured work area. +- Domain geometry remains viewport-independent data constrained through `setWorkArea`; the DOM does not become the authority. +- The existing 360 x 740 support requires an explicit small-screen policy before implementation. Recommended: render only the active window as full-work-area presentation on small screens while retaining all domain windows and providing a minimal accessible window switcher. Do not add M4 process/task visibility. +- Viewport changes update work-area constraints deterministically and must not leave controls unreachable or create horizontal page overflow. +- Touch/pointer behavior may reuse Pointer Events, but gesture-heavy shell features are not required. + +## H. Testing Plan + +### Unit Tests + +`window-manager.test.ts` should cover: + +- open with deterministic IDs/default geometry; +- focus order and active-window selection; +- valid and invalid move/resize bounds; +- minimum/maximum/work-area constraints; +- minimize, maximize, restore, including minimize-from-maximized; +- close active/inactive windows and select the next active window; +- work-area changes and responsive re-clamping; +- every invalid transition and unknown identifier; +- immutable snapshots, emitted reasons, reset, listener disposal, and service disposal. + +`application-registry.test.ts` should cover: + +- immutable manifests/definitions; +- deterministic registration/listing/lookup; +- duplicate IDs and unknown IDs; +- optional unregistration only if that API is retained. + +`application-manager.test.ts` should cover: + +- stable deterministic instance/window identity; +- single-instance and multiple-instance launch policy; +- narrow context creation; +- atomic rollback after factory/window failure; +- focus-existing behavior; +- close by instance/window; +- exactly-once disposal; +- reset/dispose clearing instances and windows without stale events. + +### Integration Tests + +Use real registry, application manager, window manager, typed events, fake IDs, fake clock, and diagnostic definition without DOM. Cover: + +- register -> launch -> instance -> primary window; +- launch multiple instances -> distinct windows -> deterministic focus order; +- move/resize/mode transitions -> close -> instance disposal; +- single-instance relaunch -> existing instance/window focus; +- runtime reset/failure coordination -> all M2 state/disposables cleared -> fresh post-reset launch; +- public application context works without private imports or cross-module state access. + +### Playwright Tests + +- boot/skip to ready while retaining all M1 smoke coverage; +- launch one and then multiple diagnostic instances; +- focus windows using pointer and keyboard; +- drag and resize with pointer, asserting resulting visible geometry; +- exercise keyboard move/resize mode; +- minimize, restore, maximize, restore, and close; +- verify focus transfer after minimize/close; +- verify launcher and chrome with keyboard only; +- verify desktop and mobile policies without clipping/horizontal overflow; +- reset while applications are open, then verify fresh empty desktop and relaunch; +- reduced-motion behavior for window transitions; +- no console errors, page errors, failed requests, navigation reloads, or external dependencies. + +Tests should prefer roles, accessible names, runtime/window state markers, and manager results over arbitrary timeouts or CSS-animation timing. + +### Quality Gates + +Run formatting, strict typecheck, ESLint, all Vitest unit/integration tests, production build, all Playwright tests, and manual desktop/mobile/keyboard interaction review. Broaden tests based on risk rather than adding M3/M4 behavior as test fixtures. + +## I. Risks / Open Questions + +Decisions needed before UI implementation: + +1. **Small-screen policy:** Confirm the recommended single-active-window presentation or choose another constrained/snap policy. This is already an explicit project question and directly affects geometry/view design. +2. **Keyboard move/resize contract:** Confirm action-menu mode, shortcuts, step sizes, cancel/commit behavior, and announcements. +3. **Launch policies:** Confirm the initial policy names and whether the diagnostic app is multi-instance. Do not add policies without a milestone use case. +4. **Default geometry:** Choose deterministic cascade offsets, minimum dimensions, initial work-area padding, and behavior when the viewport is smaller than minimum constraints. +5. **Close semantics:** Confirm one primary window per M2 instance and that closing it terminates/disposes the instance. +6. **Application view contract:** Confirm the small mount/dispose interface and whether app UI receives `Document` explicitly rather than importing browser globals. +7. **Focus shortcut:** Confirm a keyboard focus-cycle shortcut that does not conflict unacceptably with browser/assistive-technology behavior. +8. **Registration mutability:** Decide whether startup-only registration is sufficient. Prefer it unless dynamic registration has a current M2 consumer. + +Architectural risks: + +- Re-rendering the whole desktop on every window event would destroy focus and application-local DOM state. The window layer should reconcile stable window IDs and update existing elements. +- Storing bounds or active state only in CSS/DOM would violate M2's primary boundary and make deterministic tests impossible. +- Giving applications unrestricted manager/runtime access would let one app mutate another and make M3/M4 contracts harder to secure. +- Conflating application instances with processes would prematurely implement M4 and make later process visibility semantics unclear. +- Treating minimized windows as disposed instances would break lifecycle and restoration behavior. +- Reset/failure without an explicit disposal order could leave event listeners, pointer capture, or app view resources alive. +- A viewport-observer browser adapter is needed for responsive work-area updates; it must translate measurements into commands rather than own geometry state. +- The current branch documentation is not synchronized with the canonical documentation branch. Implementation should use the canonical M2 gate and avoid opportunistic documentation rewrites on this feature branch. + +## J. Recommended Implementation Order + +1. Freeze the four decisions that shape contracts: small-screen policy, keyboard move/resize interaction, launch policy names, and one-primary-window close semantics. +2. Add branded IDs, deterministic ID generation, immutable window state, and exhaustive state-transition tests. +3. Implement `WindowManager` commands/events, geometry constraints, focus ordering, work-area updates, reset, and disposal; complete unit coverage before DOM work. +4. Define application contracts/context and implement `ApplicationRegistry` with duplicate/lookup tests. +5. Implement `ApplicationManager` launch policies, atomic instance/window creation, close/reset/disposal, and unit tests. +6. Add the diagnostic application and headless integration tests proving registry -> launch -> window -> close without DOM coupling. +7. Extract `DesktopView` from `ShellView`; preserve all M1 boot/failure behavior and tests. +8. Implement `WindowLayerView`, stable-ID reconciliation, application content mounting, pointer adapters, and accessible chrome. +9. Add keyboard focus cycling and reviewed keyboard move/resize behavior. +10. Implement the chosen responsive work-area/small-screen projection and reduced-motion window transitions. +11. Wire services and runtime reset/failure cleanup in `start-afterboot.ts`, with deterministic disposal order. +12. Add Playwright workflows incrementally: launch/close, focus/multiple windows, geometry/modes, keyboard, responsive, reset/disposal, and error/network checks. +13. Run all quality gates and manual browser verification, then perform a strict scope review excluding M3/M4/M5 capabilities. + +Each domain slice should be committed only after its focused tests pass. Do not start with draggable DOM elements before the window transition model and invariants are executable. + +## K. Final Architectural Sanity Check + +### 1. What M2 Should Look Like When Complete + +SHADOW OS boots into the existing desktop, exposes a minimal launcher, and can open multiple diagnostic application instances in real windows. Users can focus, move, resize, minimize, maximize, restore, and close those windows with pointer and keyboard input. Window and application lifecycle snapshots remain independent of DOM elements; reset/disposal leaves no stale windows, instances, listeners, or pointer state. Desktop/mobile layouts remain coherent, and all required quality gates pass. + +### 2. What M2 Deliberately Leaves for M3 + +M3 receives a stable application/window foundation but no filesystem implementation. It will add the in-memory virtual filesystem, file manager, text viewer/editor, metadata/errors/events, file associations, and file-open/edit/revisit workflows. M2 must not fake these capabilities in the diagnostic application. + +M4 remains responsible for process/task visibility, settings, notifications, broader sandbox polish/failure recovery, and any justified terminal. M5 remains responsible for scenarios and objectives. + +### 3. Decisions Required Before Implementation + +Confirm the small-screen window policy, keyboard move/resize interaction, initial launch policy vocabulary, one-primary-window close semantics, deterministic default geometry, and the app view mount/dispose contract. These decisions affect public contracts or accessibility and should not emerge accidentally from DOM code. + +### 4. Sufficiency of the M1 Architecture + +The M1 architecture is sufficient for M2: typed synchronous events, explicit disposables, injected clock, composition-root wiring, immutable snapshots, and DOM-independent runtime state are the right foundations. One specific adjustment is necessary: split the ready-state desktop projection out of `ShellView` and add dedicated application/window services plus a window DOM adapter. `ShadowRuntime` should not own M2 state, and no broad framework rewrite, global store, or new external dependency is justified. + +--- + +# Milestone 2 Implementation Session + +- **Date:** 2026-09-26 +- **Branch:** `feature/m2-windows-applications` +- **Starting commit:** `51d43d68b6b75644fd85abdc322ad3048a9c6d43` +- **Implementation commit:** `116f01f6e495639f55372588b3981e68a99badcf` +- **Purpose:** Implement the M2 window and application framework from the approved architecture review and locked interaction decisions. +- **Completion status:** Implemented and locally verified — formal milestone review and CI verification pending + +## Documentation Reviewed + +- `README.md` +- `CHANGELOG.md` +- `docs/AFTERBOOT_PROJECT.md` +- `docs/SESSION_RESULTS.md` +- canonical `docs/AFTERBOOT_MILESTONES.md` from `origin/documentation`, read without switching branches because the file is not present on this feature branch + +## Implementation Summary + +- Added branded application, application-instance, and window identities with injectable deterministic generation. +- Added serializable immutable window snapshots and a DOM-independent `WindowManager`. +- Implemented centered first-window placement and centralized deterministic cascade offsets. +- Implemented focus/z-order, constrained move/resize, minimize, maximize, restore, close, work-area updates, reset, disposal, and typed window facts. +- Added immutable startup-only application registration with explicit duplicate and unknown-application errors. +- Added a single-instance `ApplicationManager` that owns running instances, primary/auxiliary window relationships, view resolution, close semantics, reset, and exactly-once disposal. +- Added a narrow application contract using `mount(host, document): Disposable` plus a scoped auxiliary-window request. +- Added the minimal System Diagnostics proof application. Relaunch focuses/restores its existing primary window; the app can open auxiliary lifecycle-detail windows to prove simultaneous-window behavior without multi-instance support. +- Extracted the ready desktop from `ShellView` into a disposable `DesktopView`. +- Added a stable-ID `WindowLayerView` that reconciles existing DOM nodes, mounts each application view once, projects domain state, and translates pointer/focus/chrome interaction into commands. +- Added desktop pointer dragging/resizing, accessible minimize/maximize/restore/close controls, launcher and task-strip keyboard navigation, and deterministic focus recovery after minimize/close. +- Added responsive active-window presentation for small screens while preserving independent domain geometry and all window state. +- Wired runtime reset/failure and application/window disposal through the existing composition root without adding M2 state to `ShadowRuntime`. + +## Important Architectural Decisions + +- `ShadowRuntime` remains the authority only for boot/reset/failure lifecycle. +- `WindowManager` is the only owner of window geometry, mode, focus order, active identity, and work-area constraints. +- `ApplicationRegistry` is immutable after startup; no installation/uninstallation API was added. +- Every M2 application is single-instance. Relaunching restores or focuses the existing primary window. +- One application instance may own auxiliary windows. This reconciles the locked single-instance policy with the milestone requirement to prove simultaneous windows. +- Closing an auxiliary window leaves the instance running; closing the primary window closes all owned windows and disposes the instance exactly once. +- Move and resize are pointer interactions only. Keyboard users can launch, focus, restore, minimize, maximize, and close through native buttons and the task strip. +- No global Alt+Tab-style shortcut or keyboard move/resize mode was added. +- Small screens render only the active window as the full available work area; inactive windows remain in domain state and can be selected through the task strip. +- Application view objects remain private lifecycle handles. DOM nodes, callbacks, and pointer state never enter application/window snapshots. + +## Tests Added + +- `tests/unit/window-manager.test.ts`: 10 tests for placement, focus/z-order, geometry, all modes, close, responsive work areas, events, reset, immutability, and invalid inputs. +- `tests/unit/application-registry.test.ts`: 3 tests for immutable startup lookup and duplicate/unknown handling. +- `tests/unit/application-manager.test.ts`: 6 tests for launch, single-instance enforcement, auxiliary windows, primary close/disposal, reset, and unknown ownership. +- `tests/integration/application-window-lifecycle.test.ts`: service-level registration -> launch -> multiple windows -> relaunch -> close/dispose workflow. +- `tests/e2e/windows-applications.spec.ts`: 6 Chromium workflows for launch, simultaneous windows/focus, pointer drag/resize, minimize/maximize/restore/close, keyboard controls, mobile presentation, reset, console errors, and failed requests. + +Existing M1 unit, integration, and Playwright tests remain unchanged and pass as regression coverage. + +## Verification + +- Prettier formatting check: passed. +- Strict TypeScript typecheck: passed. +- ESLint: passed. +- Vitest: 34 tests passed across 8 files. +- Production Vite build: passed. +- Playwright Chromium: 13 tests passed. +- Desktop visual inspection with two simultaneous windows: passed. +- Mobile 360 x 740 visual inspection with active-window fill and task switching: passed. +- Keyboard launch, focus, task restore, and window controls: passed. +- Console errors, page errors, and failed requests in M2 workflows: none. +- Reset with open primary/auxiliary windows returns to a clean second boot cycle without page reload: passed. + +## Deviations From the Architecture Review + +- The review left launch policy extensibility open; the locked implementation decision requires all M2 applications to be single-instance, so no policy enum or multi-instance path was added. +- The review recommended deciding keyboard move/resize and global focus cycling; the locked implementation explicitly excludes both from M2. +- The review proposed a broader application context as a possibility. The implementation uses only application/instance identity and a scoped auxiliary-window request because no other M2 capability is required. +- The planned separate viewport adapter was unnecessary. `WindowLayerView` translates browser resize measurements into `WindowManager.setWorkArea` commands while the manager remains the state authority. + +## Known Limitations + +- M2 provides one built-in diagnostic application only. +- Application registration is fixed at startup. +- Applications are single-instance and have one lifecycle-owning primary window. +- Window dragging and resizing use pointer input on floating desktop layouts only. +- Small-screen mode intentionally suppresses floating geometry and presents only the active window. +- Firefox, WebKit, and a formal assistive-technology matrix were not run locally; Chromium is the configured automated browser baseline. +- The canonical milestone checklist exists on `origin/documentation`, not this branch, so its formal completion record was not changed here. +- Remote CI and formal project-owner milestone approval remain pending; M2 is not yet declared complete. + +## Scope Review + +No virtual filesystem, file manager, text editor, terminal, process/task simulation, notifications, settings, persistence, accounts, networking, scenarios, backend, real machine access, dynamic application installation, multi-instance policy, global window-cycling shortcut, or keyboard move/resize behavior was introduced. + +No release, version tag, GitHub Release, PR, merge, or branch change was created. diff --git a/src/applications/built-in/system-diagnostics.ts b/src/applications/built-in/system-diagnostics.ts new file mode 100644 index 0000000..16eda73 --- /dev/null +++ b/src/applications/built-in/system-diagnostics.ts @@ -0,0 +1,120 @@ +import type { + ApplicationContext, + ApplicationDefinition, + ApplicationView, +} from "../framework/application"; +import { toApplicationId } from "../../core/identity/identifiers"; + +export const SYSTEM_DIAGNOSTICS_APPLICATION_ID = toApplicationId("system.diagnostics"); + +export function createSystemDiagnosticsDefinition(): ApplicationDefinition { + return { + manifest: { + id: SYSTEM_DIAGNOSTICS_APPLICATION_ID, + name: "System Diagnostics", + description: "Inspect application and window lifecycle behavior.", + window: { + title: "System Diagnostics", + preferredWidth: 680, + preferredHeight: 460, + constraints: { minWidth: 340, minHeight: 280 }, + }, + }, + create: (context) => ({ + primaryView: createPrimaryView(context), + dispose: () => undefined, + }), + }; +} + +function createPrimaryView(context: ApplicationContext): ApplicationView { + let detailCount = 0; + + return { + mount(host, document): () => void { + const content = element(document, "section", "diagnostics-app"); + const heading = element(document, "h2", "diagnostics-app__title", "System Diagnostics"); + const status = element(document, "p", "diagnostics-app__status", "APPLICATION ONLINE"); + status.setAttribute("role", "status"); + const facts = element(document, "dl", "diagnostics-app__facts"); + facts.append( + fact(document, "Application", context.applicationId), + fact(document, "Instance", context.instanceId), + fact(document, "Launch policy", "Single instance"), + ); + const detailButton = element( + document, + "button", + "diagnostics-app__action", + "Open lifecycle detail", + ); + detailButton.type = "button"; + const handleDetail = (): void => { + detailCount += 1; + context.openWindow({ + title: `Lifecycle Detail ${detailCount.toString().padStart(2, "0")}`, + preferredWidth: 440, + preferredHeight: 300, + constraints: { minWidth: 300, minHeight: 220 }, + view: createDetailView(context, detailCount), + }); + }; + detailButton.addEventListener("click", handleDetail); + content.append(heading, status, facts, detailButton); + host.replaceChildren(content); + + return () => { + detailButton.removeEventListener("click", handleDetail); + host.replaceChildren(); + }; + }, + }; +} + +function createDetailView(context: ApplicationContext, detailNumber: number): ApplicationView { + return { + mount(host, document): () => void { + const content = element(document, "section", "diagnostics-detail"); + content.append( + element(document, "p", "diagnostics-detail__eyebrow", "WINDOW LIFECYCLE TRACE"), + element( + document, + "h2", + "diagnostics-detail__title", + `Detail ${detailNumber.toString().padStart(2, "0")}`, + ), + element( + document, + "p", + "diagnostics-detail__copy", + `Owned by ${context.instanceId}. This auxiliary window proves one application instance can coordinate multiple windows.`, + ), + ); + host.replaceChildren(content); + return () => host.replaceChildren(); + }, + }; +} + +function fact(document: Document, term: string, value: string): HTMLElement { + const group = element(document, "div", "diagnostics-app__fact"); + group.append( + element(document, "dt", "diagnostics-app__term", term), + element(document, "dd", "diagnostics-app__value", value), + ); + return group; +} + +function element( + document: Document, + tagName: K, + className: string, + text?: string, +): HTMLElementTagNameMap[K] { + const node = document.createElement(tagName); + node.className = className; + if (text !== undefined) { + node.textContent = text; + } + return node; +} diff --git a/src/applications/framework/application-manager.ts b/src/applications/framework/application-manager.ts new file mode 100644 index 0000000..3e6cdf5 --- /dev/null +++ b/src/applications/framework/application-manager.ts @@ -0,0 +1,267 @@ +import type { Disposable } from "../../core/disposable"; +import { TypedEvent, type EventListener } from "../../core/events/typed-event"; +import { + toApplicationInstanceId, + type ApplicationId, + type ApplicationInstanceId, + type IdGenerator, + type WindowId, +} from "../../core/identity/identifiers"; +import type { WindowManager } from "../../shell/windows/window-manager"; +import type { + ApplicationContext, + ApplicationInstance, + ApplicationInstanceState, + ApplicationManagerSnapshot, + ApplicationStateChanged, + ApplicationTransitionReason, + ApplicationView, + ApplicationWindowOptions, +} from "./application"; +import type { ApplicationRegistry } from "./application-registry"; + +interface RunningApplication { + readonly instance: ApplicationInstance; + readonly views: Map; + state: ApplicationInstanceState; +} + +export class ApplicationManager { + readonly #registry: ApplicationRegistry; + readonly #windowManager: WindowManager; + readonly #idGenerator: IdGenerator; + readonly #stateChanged = new TypedEvent(); + readonly #running = new Map(); + #snapshot: ApplicationManagerSnapshot = freezeSnapshot([]); + + constructor( + registry: ApplicationRegistry, + windowManager: WindowManager, + idGenerator: IdGenerator, + ) { + this.#registry = registry; + this.#windowManager = windowManager; + this.#idGenerator = idGenerator; + } + + get snapshot(): ApplicationManagerSnapshot { + return this.#snapshot; + } + + onStateChanged(listener: EventListener): Disposable { + return this.#stateChanged.subscribe(listener); + } + + launch(applicationId: ApplicationId): ApplicationInstanceId { + const existing = [...this.#running.values()].find( + (running) => running.state.applicationId === applicationId, + ); + + if (existing) { + const primaryWindow = this.#windowManager.snapshot.windows.find( + (windowState) => windowState.id === existing.state.primaryWindowId, + ); + + if (primaryWindow?.mode === "minimized") { + this.#windowManager.restore(existing.state.primaryWindowId); + } else { + this.#windowManager.focus(existing.state.primaryWindowId); + } + + this.#emit("application-focused-existing", existing.state.id, existing.state.primaryWindowId); + return existing.state.id; + } + + const definition = this.#registry.get(applicationId); + const instanceId = toApplicationInstanceId(this.#idGenerator.next("application-instance")); + const context = this.#createContext(applicationId, instanceId); + const instance = definition.create(context); + let primaryWindowId: WindowId | null = null; + + try { + const windowOptions = definition.manifest.window; + primaryWindowId = this.#windowManager.open({ + ownerId: instanceId, + title: windowOptions.title, + ...(windowOptions.preferredWidth === undefined + ? {} + : { preferredWidth: windowOptions.preferredWidth }), + ...(windowOptions.preferredHeight === undefined + ? {} + : { preferredHeight: windowOptions.preferredHeight }), + ...(windowOptions.constraints === undefined + ? {} + : { constraints: windowOptions.constraints }), + }); + const state = freezeInstanceState({ + id: instanceId, + applicationId, + primaryWindowId, + windowIds: [primaryWindowId], + }); + this.#running.set(instanceId, { + instance, + views: new Map([[primaryWindowId, instance.primaryView]]), + state, + }); + this.#refreshSnapshot(); + this.#emit("application-launched", instanceId, primaryWindowId); + return instanceId; + } catch (error) { + if (primaryWindowId) { + this.#windowManager.close(primaryWindowId); + } + instance.dispose(); + throw error; + } + } + + getView(windowId: WindowId): ApplicationView | undefined { + for (const running of this.#running.values()) { + const view = running.views.get(windowId); + + if (view) { + return view; + } + } + + return undefined; + } + + closeWindow(windowId: WindowId): boolean { + const running = this.#findByWindow(windowId); + + if (!running) { + return false; + } + + if (running.state.primaryWindowId === windowId) { + return this.closeInstance(running.state.id); + } + + if (!this.#windowManager.close(windowId)) { + return false; + } + + running.views.delete(windowId); + running.state = freezeInstanceState({ + ...running.state, + windowIds: running.state.windowIds.filter((id) => id !== windowId), + }); + this.#refreshSnapshot(); + this.#emit("application-window-closed", running.state.id, windowId); + return true; + } + + closeInstance(instanceId: ApplicationInstanceId): boolean { + const running = this.#running.get(instanceId); + + if (!running) { + return false; + } + + for (const windowId of running.state.windowIds) { + this.#windowManager.close(windowId); + } + + this.#running.delete(instanceId); + running.instance.dispose(); + this.#refreshSnapshot(); + this.#emit("application-closed", instanceId, running.state.primaryWindowId); + return true; + } + + reset(): void { + if (this.#running.size === 0) { + this.#windowManager.reset(); + return; + } + + for (const running of this.#running.values()) { + running.instance.dispose(); + } + this.#running.clear(); + this.#windowManager.reset(); + this.#refreshSnapshot(); + this.#emit("applications-reset", null, null); + } + + dispose(): void { + this.reset(); + this.#stateChanged.clear(); + } + + #createContext( + applicationId: ApplicationId, + instanceId: ApplicationInstanceId, + ): ApplicationContext { + return Object.freeze({ + applicationId, + instanceId, + openWindow: (options: ApplicationWindowOptions): WindowId => + this.#openOwnedWindow(instanceId, options), + }); + } + + #openOwnedWindow(instanceId: ApplicationInstanceId, options: ApplicationWindowOptions): WindowId { + const running = this.#running.get(instanceId); + + if (!running) { + throw new Error(`Application instance is not running: ${instanceId}`); + } + + const windowId = this.#windowManager.open({ + ownerId: instanceId, + title: options.title, + ...(options.preferredWidth === undefined ? {} : { preferredWidth: options.preferredWidth }), + ...(options.preferredHeight === undefined + ? {} + : { preferredHeight: options.preferredHeight }), + ...(options.constraints === undefined ? {} : { constraints: options.constraints }), + }); + running.views.set(windowId, options.view); + running.state = freezeInstanceState({ + ...running.state, + windowIds: [...running.state.windowIds, windowId], + }); + this.#refreshSnapshot(); + this.#emit("application-window-opened", instanceId, windowId); + return windowId; + } + + #findByWindow(windowId: WindowId): RunningApplication | undefined { + return [...this.#running.values()].find((running) => + running.state.windowIds.includes(windowId), + ); + } + + #refreshSnapshot(): void { + this.#snapshot = freezeSnapshot([...this.#running.values()].map((running) => running.state)); + } + + #emit( + reason: ApplicationTransitionReason, + instanceId: ApplicationInstanceId | null, + windowId: WindowId | null, + ): void { + this.#stateChanged.emit( + Object.freeze({ + type: "application-state-changed", + reason, + instanceId, + windowId, + snapshot: this.#snapshot, + }), + ); + } +} + +function freezeInstanceState(state: ApplicationInstanceState): ApplicationInstanceState { + return Object.freeze({ ...state, windowIds: Object.freeze([...state.windowIds]) }); +} + +function freezeSnapshot( + instances: readonly ApplicationInstanceState[], +): ApplicationManagerSnapshot { + return Object.freeze({ instances: Object.freeze([...instances]) }); +} diff --git a/src/applications/framework/application-registry.ts b/src/applications/framework/application-registry.ts new file mode 100644 index 0000000..3caeff9 --- /dev/null +++ b/src/applications/framework/application-registry.ts @@ -0,0 +1,62 @@ +import type { ApplicationId } from "../../core/identity/identifiers"; +import type { ApplicationDefinition, ApplicationManifest } from "./application"; + +export class DuplicateApplicationError extends Error { + constructor(applicationId: ApplicationId) { + super(`Application is already registered: ${applicationId}`); + this.name = "DuplicateApplicationError"; + } +} + +export class UnknownApplicationError extends Error { + constructor(applicationId: ApplicationId) { + super(`Application is not registered: ${applicationId}`); + this.name = "UnknownApplicationError"; + } +} + +export class ApplicationRegistry { + readonly #definitions = new Map(); + + constructor(definitions: readonly ApplicationDefinition[]) { + for (const definition of definitions) { + const applicationId = definition.manifest.id; + + if (this.#definitions.has(applicationId)) { + throw new DuplicateApplicationError(applicationId); + } + + this.#definitions.set(applicationId, freezeDefinition(definition)); + } + } + + list(): readonly ApplicationManifest[] { + return Object.freeze([...this.#definitions.values()].map((definition) => definition.manifest)); + } + + get(applicationId: ApplicationId): ApplicationDefinition { + const definition = this.#definitions.get(applicationId); + + if (!definition) { + throw new UnknownApplicationError(applicationId); + } + + return definition; + } +} + +function freezeDefinition(definition: ApplicationDefinition): ApplicationDefinition { + const constraints = definition.manifest.window.constraints + ? Object.freeze({ ...definition.manifest.window.constraints }) + : undefined; + const window = Object.freeze({ + ...definition.manifest.window, + ...(constraints ? { constraints } : {}), + }); + const manifest = Object.freeze({ ...definition.manifest, window }); + + return Object.freeze({ + manifest, + create: (context: Parameters[0]) => definition.create(context), + }); +} diff --git a/src/applications/framework/application.ts b/src/applications/framework/application.ts new file mode 100644 index 0000000..42780b5 --- /dev/null +++ b/src/applications/framework/application.ts @@ -0,0 +1,74 @@ +import type { Disposable } from "../../core/disposable"; +import type { + ApplicationId, + ApplicationInstanceId, + WindowId, +} from "../../core/identity/identifiers"; +import type { WindowConstraints } from "../../shell/windows/window-state"; + +export interface ApplicationView { + mount(host: HTMLElement, document: Document): Disposable; +} + +export interface ApplicationWindowOptions { + readonly title: string; + readonly view: ApplicationView; + readonly preferredWidth?: number; + readonly preferredHeight?: number; + readonly constraints?: Partial; +} + +export interface ApplicationContext { + readonly applicationId: ApplicationId; + readonly instanceId: ApplicationInstanceId; + openWindow(options: ApplicationWindowOptions): WindowId; +} + +export interface ApplicationInstance { + readonly primaryView: ApplicationView; + dispose(): void; +} + +export interface ApplicationManifest { + readonly id: ApplicationId; + readonly name: string; + readonly description: string; + readonly window: Readonly<{ + title: string; + preferredWidth?: number; + preferredHeight?: number; + constraints?: Partial; + }>; +} + +export interface ApplicationDefinition { + readonly manifest: ApplicationManifest; + create(context: ApplicationContext): ApplicationInstance; +} + +export interface ApplicationInstanceState { + readonly id: ApplicationInstanceId; + readonly applicationId: ApplicationId; + readonly primaryWindowId: WindowId; + readonly windowIds: readonly WindowId[]; +} + +export interface ApplicationManagerSnapshot { + readonly instances: readonly ApplicationInstanceState[]; +} + +export type ApplicationTransitionReason = + | "application-launched" + | "application-focused-existing" + | "application-window-opened" + | "application-window-closed" + | "application-closed" + | "applications-reset"; + +export interface ApplicationStateChanged { + readonly type: "application-state-changed"; + readonly reason: ApplicationTransitionReason; + readonly instanceId: ApplicationInstanceId | null; + readonly windowId: WindowId | null; + readonly snapshot: ApplicationManagerSnapshot; +} diff --git a/src/bootstrap/start-afterboot.ts b/src/bootstrap/start-afterboot.ts index 9d094a8..3c6683d 100644 --- a/src/bootstrap/start-afterboot.ts +++ b/src/bootstrap/start-afterboot.ts @@ -1,7 +1,12 @@ import { ShadowRuntime, type BootStageDurations } from "../core/runtime/shadow-runtime"; +import { SequentialIdGenerator } from "../core/identity/identifiers"; +import { ApplicationRegistry } from "../applications/framework/application-registry"; +import { ApplicationManager } from "../applications/framework/application-manager"; +import { createSystemDiagnosticsDefinition } from "../applications/built-in/system-diagnostics"; import { BrowserClock } from "../platform/browser-clock"; import { prefersReducedMotion } from "../platform/motion-preference"; import { ShellView } from "../shell/shell-view"; +import { WindowManager } from "../shell/windows/window-manager"; const STANDARD_BOOT_STAGE_DURATIONS: BootStageDurations = { "power-on": 700, @@ -44,7 +49,26 @@ export function startAfterboot(document: Document, browserWindow: Window): After ? REDUCED_MOTION_BOOT_STAGE_DURATIONS : STANDARD_BOOT_STAGE_DURATIONS, }); - const shellView = new ShellView(root, document, runtime, clock, reducedMotion); + const ids = new SequentialIdGenerator(); + const windowManager = new WindowManager(ids, { x: 0, y: 0, width: 1, height: 1 }); + const registry = new ApplicationRegistry([createSystemDiagnosticsDefinition()]); + const applicationManager = new ApplicationManager(registry, windowManager, ids); + const disposeRuntimeServices = runtime.onStateChanged((event) => { + if (event.reason === "reset-requested" || event.reason === "runtime-failed") { + applicationManager.reset(); + } + }); + const shellView = new ShellView( + root, + document, + runtime, + clock, + reducedMotion, + browserWindow, + registry, + applicationManager, + windowManager, + ); const disposeShell = shellView.mount(); runtime.boot(); @@ -53,6 +77,9 @@ export function startAfterboot(document: Document, browserWindow: Window): After runtime, dispose(): void { disposeShell(); + disposeRuntimeServices(); + applicationManager.dispose(); + windowManager.dispose(); runtime.dispose(); }, }; diff --git a/src/core/identity/identifiers.ts b/src/core/identity/identifiers.ts new file mode 100644 index 0000000..3353771 --- /dev/null +++ b/src/core/identity/identifiers.ts @@ -0,0 +1,39 @@ +export type ApplicationId = string & { readonly __brand: "ApplicationId" }; +export type ApplicationInstanceId = string & { readonly __brand: "ApplicationInstanceId" }; +export type WindowId = string & { readonly __brand: "WindowId" }; + +export type IdScope = "application-instance" | "window"; + +export interface IdGenerator { + next(scope: IdScope): string; +} + +export class SequentialIdGenerator implements IdGenerator { + readonly #counts = new Map(); + + next(scope: IdScope): string { + const nextCount = (this.#counts.get(scope) ?? 0) + 1; + this.#counts.set(scope, nextCount); + return `${scope}-${nextCount}`; + } +} + +export function toApplicationId(value: string): ApplicationId { + return requireIdentifier(value, "ApplicationId") as ApplicationId; +} + +export function toApplicationInstanceId(value: string): ApplicationInstanceId { + return requireIdentifier(value, "ApplicationInstanceId") as ApplicationInstanceId; +} + +export function toWindowId(value: string): WindowId { + return requireIdentifier(value, "WindowId") as WindowId; +} + +function requireIdentifier(value: string, kind: string): string { + if (value.trim().length === 0) { + throw new TypeError(`${kind} must not be empty.`); + } + + return value; +} diff --git a/src/main.ts b/src/main.ts index 56d2b0c..c2bc956 100644 --- a/src/main.ts +++ b/src/main.ts @@ -1,4 +1,5 @@ import "./styles/main.css"; +import "./styles/windows.css"; import { renderStartupFailure, startAfterboot, diff --git a/src/shell/desktop/desktop-view.ts b/src/shell/desktop/desktop-view.ts new file mode 100644 index 0000000..663315a --- /dev/null +++ b/src/shell/desktop/desktop-view.ts @@ -0,0 +1,224 @@ +import type { ApplicationManager } from "../../applications/framework/application-manager"; +import type { ApplicationRegistry } from "../../applications/framework/application-registry"; +import type { Disposable } from "../../core/disposable"; +import { toApplicationId, toWindowId } from "../../core/identity/identifiers"; +import type { ShadowRuntime } from "../../core/runtime/shadow-runtime"; +import type { Clock } from "../../core/time/clock"; +import type { WindowManager } from "../windows/window-manager"; +import { WindowLayerView } from "../windows/window-layer-view"; +import { formatSystemTime } from "../system-time"; + +const CLOCK_UPDATE_INTERVAL_MS = 1_000; + +export class DesktopView { + readonly element: HTMLElement; + readonly #document: Document; + readonly #runtime: ShadowRuntime; + readonly #clock: Clock; + readonly #registry: ApplicationRegistry; + readonly #applicationManager: ApplicationManager; + readonly #windowManager: WindowManager; + readonly #windowLayer: WindowLayerView; + readonly #launcher: HTMLElement; + readonly #taskStrip: HTMLElement; + readonly #time: HTMLTimeElement; + readonly #date: HTMLElement; + readonly #resetButton: HTMLButtonElement; + #cancelClock: Disposable | null = null; + #unsubscribeWindows: Disposable | null = null; + + constructor( + document: Document, + browserWindow: Window, + runtime: ShadowRuntime, + clock: Clock, + registry: ApplicationRegistry, + applicationManager: ApplicationManager, + windowManager: WindowManager, + bootCycle: number, + ) { + this.#document = document; + this.#runtime = runtime; + this.#clock = clock; + this.#registry = registry; + this.#applicationManager = applicationManager; + this.#windowManager = windowManager; + + const main = element(document, "main", "desktop-shell"); + main.setAttribute("aria-labelledby", "desktop-title"); + const title = element(document, "h1", "desktop-shell__ready", "Desktop ready"); + title.id = "desktop-title"; + + const header = element(document, "header", "system-header desktop-shell__header"); + header.append( + element(document, "span", "system-header__brand", "SHADOW OS"), + title, + element(document, "span", "system-header__state", "SYSTEM / READY"), + ); + + const workspace = element(document, "section", "desktop-shell__workspace"); + workspace.setAttribute("aria-label", "SHADOW OS desktop work area"); + const desktopIdentity = element(document, "div", "desktop-shell__identity"); + desktopIdentity.setAttribute("aria-hidden", "true"); + desktopIdentity.append( + element( + document, + "p", + "desktop-shell__environment", + `ENVIRONMENT / CYCLE ${bootCycle.toString().padStart(2, "0")}`, + ), + element(document, "p", "desktop-shell__wordmark", "SHADOW"), + element(document, "p", "desktop-shell__description", "WINDOW SERVICES ONLINE"), + ); + const windowLayer = element(document, "div", "window-layer"); + windowLayer.setAttribute("aria-label", "Open application windows"); + workspace.append(desktopIdentity, windowLayer); + + const footer = element(document, "footer", "desktop-shell__footer"); + this.#launcher = element(document, "nav", "application-launcher"); + this.#launcher.setAttribute("aria-label", "Applications"); + this.#renderLauncher(); + this.#taskStrip = element(document, "nav", "window-task-strip"); + this.#taskStrip.setAttribute("aria-label", "Open windows"); + const clockPanel = element(document, "section", "system-clock"); + clockPanel.setAttribute("aria-label", "SHADOW OS system clock"); + this.#time = element(document, "time", "system-clock__time"); + this.#date = element(document, "span", "system-clock__date"); + clockPanel.append(this.#time, this.#date); + this.#resetButton = element(document, "button", "desktop-shell__reset", "Restart SHADOW OS"); + this.#resetButton.type = "button"; + footer.append(this.#launcher, this.#taskStrip, clockPanel, this.#resetButton); + main.append(header, workspace, footer); + + this.element = main; + this.#windowLayer = new WindowLayerView( + windowLayer, + document, + browserWindow, + windowManager, + applicationManager, + ); + } + + mount(): Disposable { + this.#launcher.addEventListener("click", this.#handleLauncherClick); + this.#taskStrip.addEventListener("click", this.#handleTaskClick); + this.#resetButton.addEventListener("click", this.#handleReset); + this.#unsubscribeWindows = this.#windowManager.onStateChanged((event) => { + this.#renderTasks(); + + if (event.reason === "window-minimized" && !event.snapshot.activeWindowId) { + this.#taskStrip + .querySelector(`[data-window-id="${event.windowId ?? ""}"]`) + ?.focus(); + } + + if (event.reason === "window-closed" && !event.snapshot.activeWindowId) { + this.#launcher.querySelector("[data-application-id]")?.focus(); + } + }); + const disposeWindowLayer = this.#windowLayer.mount(); + this.#renderTasks(); + this.#updateClock(); + + return () => { + this.#launcher.removeEventListener("click", this.#handleLauncherClick); + this.#taskStrip.removeEventListener("click", this.#handleTaskClick); + this.#resetButton.removeEventListener("click", this.#handleReset); + this.#unsubscribeWindows?.(); + this.#unsubscribeWindows = null; + this.#cancelClock?.(); + this.#cancelClock = null; + disposeWindowLayer(); + }; + } + + #renderLauncher(): void { + const label = element(this.#document, "span", "application-launcher__label", "APPS"); + const buttons = this.#registry.list().map((manifest) => { + const button = element( + this.#document, + "button", + "application-launcher__button", + manifest.name, + ); + button.type = "button"; + button.dataset.applicationId = manifest.id; + button.title = manifest.description; + return button; + }); + this.#launcher.replaceChildren(label, ...buttons); + } + + #renderTasks(): void { + const snapshot = this.#windowManager.snapshot; + const tasks = snapshot.windows.map((windowState) => { + const button = element( + this.#document, + "button", + "window-task-strip__button", + windowState.title, + ); + button.type = "button"; + button.dataset.windowId = windowState.id; + button.dataset.active = snapshot.activeWindowId === windowState.id ? "true" : "false"; + button.dataset.mode = windowState.mode; + button.setAttribute( + "aria-label", + `${windowState.mode === "minimized" ? "Restore" : "Focus"} ${windowState.title}`, + ); + return button; + }); + this.#taskStrip.replaceChildren(...tasks); + } + + #updateClock(): void { + const systemTime = formatSystemTime(this.#clock.now()); + this.#time.dateTime = systemTime.iso; + this.#time.textContent = systemTime.time; + this.#date.textContent = systemTime.date; + this.#cancelClock = this.#clock.schedule(() => this.#updateClock(), CLOCK_UPDATE_INTERVAL_MS); + } + + readonly #handleLauncherClick = (event: MouseEvent): void => { + const target = event.target instanceof Element ? event.target : null; + const applicationId = + target?.closest("[data-application-id]")?.dataset.applicationId; + if (applicationId) { + this.#applicationManager.launch(toApplicationId(applicationId)); + } + }; + + readonly #handleTaskClick = (event: MouseEvent): void => { + const target = event.target instanceof Element ? event.target : null; + const rawWindowId = target?.closest("[data-window-id]")?.dataset.windowId; + if (!rawWindowId) { + return; + } + const windowId = toWindowId(rawWindowId); + const windowState = this.#windowManager.snapshot.windows.find( + (candidate) => candidate.id === windowId, + ); + if (windowState?.mode === "minimized") { + this.#windowManager.restore(windowId); + } else { + this.#windowManager.focus(windowId); + } + }; + + readonly #handleReset = (): void => this.#runtime.reset(); +} + +function element( + document: Document, + tagName: K, + className: string, + text?: string, +): HTMLElementTagNameMap[K] { + const node = document.createElement(tagName); + node.className = className; + if (text !== undefined) { + node.textContent = text; + } + return node; +} diff --git a/src/shell/shell-view.ts b/src/shell/shell-view.ts index cec1c18..de6c844 100644 --- a/src/shell/shell-view.ts +++ b/src/shell/shell-view.ts @@ -6,9 +6,11 @@ import { type ShadowRuntime, } from "../core/runtime/shadow-runtime"; import type { Clock } from "../core/time/clock"; -import { formatSystemTime } from "./system-time"; +import type { ApplicationManager } from "../applications/framework/application-manager"; +import type { ApplicationRegistry } from "../applications/framework/application-registry"; +import { DesktopView } from "./desktop/desktop-view"; +import type { WindowManager } from "./windows/window-manager"; -const CLOCK_UPDATE_INTERVAL_MS = 1_000; const SKIP_BOOT_ACTION = "skip-boot"; interface BootService { @@ -29,8 +31,12 @@ export class ShellView { readonly #runtime: ShadowRuntime; readonly #clock: Clock; readonly #reducedMotion: boolean; + readonly #browserWindow: Window; + readonly #registry: ApplicationRegistry; + readonly #applicationManager: ApplicationManager; + readonly #windowManager: WindowManager; #unsubscribeRuntime: Disposable | null = null; - #cancelClockUpdate: Disposable | null = null; + #disposeDesktop: Disposable | null = null; constructor( root: HTMLElement, @@ -38,12 +44,20 @@ export class ShellView { runtime: ShadowRuntime, clock: Clock, reducedMotion: boolean, + browserWindow: Window, + registry: ApplicationRegistry, + applicationManager: ApplicationManager, + windowManager: WindowManager, ) { this.#root = root; this.#document = document; this.#runtime = runtime; this.#clock = clock; this.#reducedMotion = reducedMotion; + this.#browserWindow = browserWindow; + this.#registry = registry; + this.#applicationManager = applicationManager; + this.#windowManager = windowManager; } mount(): Disposable { @@ -57,12 +71,14 @@ export class ShellView { } render(snapshot: RuntimeSnapshot): void { - this.#cancelClock(); + this.#disposeDesktop?.(); + this.#disposeDesktop = null; this.#root.dataset.runtimePhase = snapshot.phase; const restoreSkipFocus = this.#document.activeElement instanceof HTMLElement && this.#document.activeElement.dataset.action === SKIP_BOOT_ACTION; let content: HTMLElement; + let desktopView: DesktopView | null = null; if (snapshot.bootStage) { this.#root.dataset.bootStage = snapshot.bootStage; @@ -79,7 +95,17 @@ export class ShellView { content = this.#renderBoot(snapshot); break; case "ready": - content = this.#renderDesktop(snapshot); + desktopView = new DesktopView( + this.#document, + this.#browserWindow, + this.#runtime, + this.#clock, + this.#registry, + this.#applicationManager, + this.#windowManager, + snapshot.bootCycle, + ); + content = desktopView.element; break; case "failed": content = this.#renderFailure(snapshot); @@ -87,6 +113,7 @@ export class ShellView { } this.#root.replaceChildren(content); + this.#disposeDesktop = desktopView?.mount() ?? null; if (restoreSkipFocus) { this.#root.querySelector(`[data-action="${SKIP_BOOT_ACTION}"]`)?.focus(); @@ -94,7 +121,8 @@ export class ShellView { } dispose(): void { - this.#cancelClock(); + this.#disposeDesktop?.(); + this.#disposeDesktop = null; this.#unsubscribeRuntime?.(); this.#unsubscribeRuntime = null; delete this.#document.documentElement.dataset.motion; @@ -203,54 +231,6 @@ export class ShellView { return main; } - #renderDesktop(snapshot: RuntimeSnapshot): HTMLElement { - const main = this.#element("main", "desktop-shell"); - main.setAttribute("aria-labelledby", "desktop-title"); - - const header = this.#element("header", "system-header desktop-shell__header"); - header.append( - this.#element("span", "system-header__brand", "SHADOW OS"), - this.#element("span", "system-header__state", "SYSTEM / READY"), - ); - - const workspace = this.#element("section", "desktop-shell__workspace"); - const identity = this.#element("div", "desktop-shell__identity"); - const environment = this.#element( - "p", - "desktop-shell__environment", - `ENVIRONMENT / CYCLE ${snapshot.bootCycle.toString().padStart(2, "0")}`, - ); - const title = this.#element("h1", "desktop-shell__title", "Desktop ready"); - title.id = "desktop-title"; - const description = this.#element( - "p", - "desktop-shell__description", - "Core runtime online. Workspace services awaiting installation.", - ); - identity.append(environment, title, description); - - const clockPanel = this.#element("section", "system-clock"); - clockPanel.setAttribute("aria-label", "SHADOW OS system clock"); - const clockLabel = this.#element("span", "system-clock__label", "LOCAL SYSTEM TIME"); - const time = this.#element("time", "system-clock__time"); - const date = this.#element("span", "system-clock__date"); - clockPanel.append(clockLabel, time, date); - this.#startClock(time, date); - - workspace.append(identity, clockPanel); - - const footer = this.#element("footer", "desktop-shell__footer"); - const runtimeState = this.#element("span", "desktop-shell__runtime", "RUNTIME STABLE"); - const resetButton = this.#element("button", "desktop-shell__reset", "Restart SHADOW OS"); - resetButton.type = "button"; - resetButton.title = "Restart SHADOW OS"; - resetButton.addEventListener("click", () => this.#runtime.reset()); - footer.append(runtimeState, resetButton); - - main.append(header, workspace, footer); - return main; - } - #renderFailure(snapshot: RuntimeSnapshot): HTMLElement { const main = this.#element("main", "runtime-failure"); main.setAttribute("aria-labelledby", "failure-title"); @@ -319,23 +299,6 @@ export class ShellView { return button; } - #startClock(timeElement: HTMLTimeElement, dateElement: HTMLElement): void { - const update = (): void => { - const systemTime = formatSystemTime(this.#clock.now()); - timeElement.dateTime = systemTime.iso; - timeElement.textContent = systemTime.time; - dateElement.textContent = systemTime.date; - this.#cancelClockUpdate = this.#clock.schedule(update, CLOCK_UPDATE_INTERVAL_MS); - }; - - update(); - } - - #cancelClock(): void { - this.#cancelClockUpdate?.(); - this.#cancelClockUpdate = null; - } - #element( tagName: K, className: string, diff --git a/src/shell/windows/window-layer-view.ts b/src/shell/windows/window-layer-view.ts new file mode 100644 index 0000000..05884dc --- /dev/null +++ b/src/shell/windows/window-layer-view.ts @@ -0,0 +1,311 @@ +import type { ApplicationManager } from "../../applications/framework/application-manager"; +import type { Disposable } from "../../core/disposable"; +import { toWindowId, type WindowId } from "../../core/identity/identifiers"; +import type { WindowManager } from "./window-manager"; +import type { WindowBounds, WindowState } from "./window-state"; + +interface WindowElementRecord { + readonly element: HTMLElement; + readonly title: HTMLElement; + readonly maximizeButton: HTMLButtonElement; + readonly content: HTMLElement; + readonly disposeView: Disposable; +} + +interface PointerInteraction { + readonly pointerId: number; + readonly windowId: WindowId; + readonly operation: "move" | "resize"; + readonly originX: number; + readonly originY: number; + readonly initialBounds: WindowBounds; +} + +export class WindowLayerView { + readonly #container: HTMLElement; + readonly #document: Document; + readonly #browserWindow: Window; + readonly #windowManager: WindowManager; + readonly #applicationManager: ApplicationManager; + readonly #records = new Map(); + #pointerInteraction: PointerInteraction | null = null; + #unsubscribeWindows: Disposable | null = null; + #unsubscribeApplications: Disposable | null = null; + #previousActiveWindowId: WindowId | null = null; + + constructor( + container: HTMLElement, + document: Document, + browserWindow: Window, + windowManager: WindowManager, + applicationManager: ApplicationManager, + ) { + this.#container = container; + this.#document = document; + this.#browserWindow = browserWindow; + this.#windowManager = windowManager; + this.#applicationManager = applicationManager; + } + + mount(): Disposable { + this.#unsubscribeWindows = this.#windowManager.onStateChanged(() => this.render()); + this.#unsubscribeApplications = this.#applicationManager.onStateChanged(() => this.render()); + this.#container.addEventListener("pointerdown", this.#handlePointerDown); + this.#container.addEventListener("pointermove", this.#handlePointerMove); + this.#container.addEventListener("pointerup", this.#handlePointerEnd); + this.#container.addEventListener("pointercancel", this.#handlePointerEnd); + this.#container.addEventListener("click", this.#handleClick); + this.#container.addEventListener("focusin", this.#handleFocusIn); + this.#browserWindow.addEventListener("resize", this.#syncWorkArea); + this.#syncWorkArea(); + this.render(); + return () => this.dispose(); + } + + render(): void { + const snapshot = this.#windowManager.snapshot; + const currentIds = new Set(snapshot.windows.map((windowState) => windowState.id)); + + for (const [windowId, record] of this.#records) { + if (!currentIds.has(windowId)) { + record.disposeView(); + record.element.remove(); + this.#records.delete(windowId); + } + } + + for (const windowState of snapshot.windows) { + const record = this.#records.get(windowState.id) ?? this.#createWindow(windowState); + if (!record) { + continue; + } + this.#updateWindow(record, windowState, snapshot.activeWindowId === windowState.id); + } + + if (snapshot.activeWindowId !== this.#previousActiveWindowId && snapshot.activeWindowId) { + const activeRecord = this.#records.get(snapshot.activeWindowId); + if ( + activeRecord && + !activeRecord.element.hidden && + !activeRecord.element.contains(this.#document.activeElement) + ) { + activeRecord.element.focus({ preventScroll: true }); + } + if (activeRecord) { + this.#previousActiveWindowId = snapshot.activeWindowId; + } + } else { + this.#previousActiveWindowId = snapshot.activeWindowId; + } + } + + dispose(): void { + this.#unsubscribeWindows?.(); + this.#unsubscribeApplications?.(); + this.#unsubscribeWindows = null; + this.#unsubscribeApplications = null; + this.#browserWindow.removeEventListener("resize", this.#syncWorkArea); + this.#container.removeEventListener("pointerdown", this.#handlePointerDown); + this.#container.removeEventListener("pointermove", this.#handlePointerMove); + this.#container.removeEventListener("pointerup", this.#handlePointerEnd); + this.#container.removeEventListener("pointercancel", this.#handlePointerEnd); + this.#container.removeEventListener("click", this.#handleClick); + this.#container.removeEventListener("focusin", this.#handleFocusIn); + for (const record of this.#records.values()) { + record.disposeView(); + } + this.#records.clear(); + this.#pointerInteraction = null; + this.#container.replaceChildren(); + } + + #createWindow(windowState: WindowState): WindowElementRecord | null { + const view = this.#applicationManager.getView(windowState.id); + if (!view) { + return null; + } + + const windowElement = this.#document.createElement("section"); + windowElement.className = "os-window"; + windowElement.dataset.windowId = windowState.id; + windowElement.tabIndex = -1; + windowElement.setAttribute("role", "dialog"); + + const titleBar = this.#document.createElement("header"); + titleBar.className = "os-window__titlebar"; + titleBar.dataset.windowDrag = "true"; + const title = this.#document.createElement("h2"); + title.className = "os-window__title"; + const controls = this.#document.createElement("div"); + controls.className = "os-window__controls"; + const minimizeButton = control(this.#document, "minimize", "Minimize window", "_"); + const maximizeButton = control(this.#document, "maximize", "Maximize window", "□"); + const closeButton = control(this.#document, "close", "Close window", "×"); + controls.append(minimizeButton, maximizeButton, closeButton); + titleBar.append(title, controls); + + const content = this.#document.createElement("div"); + content.className = "os-window__content"; + const resizeHandle = this.#document.createElement("div"); + resizeHandle.className = "os-window__resize-handle"; + resizeHandle.dataset.windowResize = "true"; + resizeHandle.setAttribute("aria-hidden", "true"); + windowElement.append(titleBar, content, resizeHandle); + this.#container.append(windowElement); + + const record = { + element: windowElement, + title, + maximizeButton, + content, + disposeView: view.mount(content, this.#document), + }; + this.#records.set(windowState.id, record); + return record; + } + + #updateWindow(record: WindowElementRecord, windowState: WindowState, active: boolean): void { + record.title.textContent = windowState.title; + record.element.setAttribute("aria-label", windowState.title); + record.element.dataset.mode = windowState.mode; + record.element.dataset.active = active ? "true" : "false"; + record.element.hidden = windowState.mode === "minimized"; + record.element.style.left = `${windowState.bounds.x}px`; + record.element.style.top = `${windowState.bounds.y}px`; + record.element.style.width = `${windowState.bounds.width}px`; + record.element.style.height = `${windowState.bounds.height}px`; + record.element.style.zIndex = String(10 + windowState.focusOrder); + const maximized = windowState.mode === "maximized"; + record.maximizeButton.dataset.windowAction = maximized ? "restore" : "maximize"; + record.maximizeButton.setAttribute( + "aria-label", + maximized ? "Restore window" : "Maximize window", + ); + record.maximizeButton.title = maximized ? "Restore window" : "Maximize window"; + record.maximizeButton.textContent = maximized ? "◇" : "□"; + } + + readonly #syncWorkArea = (): void => { + this.#windowManager.setWorkArea({ + x: 0, + y: 0, + width: Math.max(1, this.#container.clientWidth), + height: Math.max(1, this.#container.clientHeight), + }); + }; + + readonly #handleClick = (event: MouseEvent): void => { + const target = event.target instanceof Element ? event.target : null; + const actionElement = target?.closest("[data-window-action]"); + const windowElement = target?.closest("[data-window-id]"); + if (!actionElement || !windowElement?.dataset.windowId) { + return; + } + + const windowId = toWindowId(windowElement.dataset.windowId); + switch (actionElement.dataset.windowAction) { + case "minimize": + this.#windowManager.minimize(windowId); + break; + case "maximize": + this.#windowManager.maximize(windowId); + break; + case "restore": + this.#windowManager.restore(windowId); + break; + case "close": + this.#applicationManager.closeWindow(windowId); + break; + } + }; + + readonly #handleFocusIn = (event: FocusEvent): void => { + const target = event.target instanceof Element ? event.target : null; + const windowId = target?.closest("[data-window-id]")?.dataset.windowId; + if (windowId) { + this.#windowManager.focus(toWindowId(windowId)); + } + }; + + readonly #handlePointerDown = (event: PointerEvent): void => { + if (event.button !== 0) { + return; + } + + const target = event.target instanceof Element ? event.target : null; + const windowElement = target?.closest("[data-window-id]"); + const rawWindowId = windowElement?.dataset.windowId; + if (!windowElement || !rawWindowId) { + return; + } + + const windowId = toWindowId(rawWindowId); + this.#windowManager.focus(windowId); + const windowState = this.#windowManager.snapshot.windows.find( + (candidate) => candidate.id === windowId, + ); + const operation = target?.closest("[data-window-resize]") + ? "resize" + : target?.closest("[data-window-drag]") && !target.closest("button") + ? "move" + : null; + if (!windowState || windowState.mode !== "normal" || !operation) { + return; + } + + event.preventDefault(); + windowElement.setPointerCapture(event.pointerId); + this.#pointerInteraction = { + pointerId: event.pointerId, + windowId, + operation, + originX: event.clientX, + originY: event.clientY, + initialBounds: windowState.bounds, + }; + }; + + readonly #handlePointerMove = (event: PointerEvent): void => { + const interaction = this.#pointerInteraction; + if (!interaction || interaction.pointerId !== event.pointerId) { + return; + } + + const deltaX = event.clientX - interaction.originX; + const deltaY = event.clientY - interaction.originY; + if (interaction.operation === "move") { + this.#windowManager.move(interaction.windowId, { + x: interaction.initialBounds.x + deltaX, + y: interaction.initialBounds.y + deltaY, + }); + } else { + this.#windowManager.resize(interaction.windowId, { + ...interaction.initialBounds, + width: interaction.initialBounds.width + deltaX, + height: interaction.initialBounds.height + deltaY, + }); + } + }; + + readonly #handlePointerEnd = (event: PointerEvent): void => { + if (this.#pointerInteraction?.pointerId === event.pointerId) { + this.#pointerInteraction = null; + } + }; +} + +function control( + document: Document, + action: string, + label: string, + symbol: string, +): HTMLButtonElement { + const button = document.createElement("button"); + button.className = `os-window__control os-window__control--${action}`; + button.type = "button"; + button.dataset.windowAction = action; + button.setAttribute("aria-label", label); + button.title = label; + button.textContent = symbol; + return button; +} diff --git a/src/shell/windows/window-manager.ts b/src/shell/windows/window-manager.ts new file mode 100644 index 0000000..c13ee4f --- /dev/null +++ b/src/shell/windows/window-manager.ts @@ -0,0 +1,405 @@ +import type { Disposable } from "../../core/disposable"; +import { TypedEvent, type EventListener } from "../../core/events/typed-event"; +import { toWindowId, type IdGenerator, type WindowId } from "../../core/identity/identifiers"; +import type { + OpenWindowRequest, + RestorableWindowMode, + WindowBounds, + WindowConstraints, + WindowManagerSnapshot, + WindowState, + WindowStateChanged, + WindowTransitionReason, +} from "./window-state"; + +export const DEFAULT_WINDOW_WIDTH = 640; +export const DEFAULT_WINDOW_HEIGHT = 420; +export const DEFAULT_MIN_WINDOW_WIDTH = 320; +export const DEFAULT_MIN_WINDOW_HEIGHT = 220; +export const WINDOW_CASCADE_OFFSET = 32; + +export class WindowManager { + readonly #idGenerator: IdGenerator; + readonly #stateChanged = new TypedEvent(); + #snapshot: WindowManagerSnapshot; + #focusOrder = 0; + + constructor(idGenerator: IdGenerator, workArea: WindowBounds) { + this.#idGenerator = idGenerator; + this.#snapshot = freezeSnapshot([], null, validateWorkArea(workArea)); + } + + get snapshot(): WindowManagerSnapshot { + return this.#snapshot; + } + + onStateChanged(listener: EventListener): Disposable { + return this.#stateChanged.subscribe(listener); + } + + open(request: OpenWindowRequest): WindowId { + const id = toWindowId(this.#idGenerator.next("window")); + const constraints = normalizeConstraints(request.constraints); + const bounds = this.#initialBounds( + request.preferredWidth ?? DEFAULT_WINDOW_WIDTH, + request.preferredHeight ?? DEFAULT_WINDOW_HEIGHT, + constraints, + ); + const windowState = freezeWindow({ + id, + ownerId: request.ownerId, + title: request.title, + bounds, + normalBounds: bounds, + constraints, + mode: "normal", + restoreMode: "normal", + focusOrder: this.#nextFocusOrder(), + }); + + this.#replace([...this.#snapshot.windows, windowState], id, "window-opened", id); + return id; + } + + focus(windowId: WindowId): boolean { + const target = this.#find(windowId); + + if (!target || target.mode === "minimized") { + return false; + } + + if (this.#snapshot.activeWindowId === windowId) { + return true; + } + + return this.#update( + windowId, + (windowState) => ({ ...windowState, focusOrder: this.#nextFocusOrder() }), + "window-focused", + windowId, + ); + } + + move(windowId: WindowId, position: Pick): boolean { + return this.#updateNormalBounds( + windowId, + (windowState) => ({ ...windowState.normalBounds, ...position }), + "window-moved", + ); + } + + resize(windowId: WindowId, bounds: Pick): boolean { + return this.#updateNormalBounds(windowId, () => bounds, "window-resized"); + } + + minimize(windowId: WindowId): boolean { + const target = this.#find(windowId); + + if (!target || target.mode === "minimized") { + return false; + } + + const restoreMode: RestorableWindowMode = target.mode; + const windows = this.#snapshot.windows.map((windowState) => + windowState.id === windowId + ? freezeWindow({ ...windowState, mode: "minimized", restoreMode }) + : windowState, + ); + const activeWindowId = this.#topVisibleWindowId(windows, windowId); + this.#replace(windows, activeWindowId, "window-minimized", windowId); + return true; + } + + maximize(windowId: WindowId): boolean { + const target = this.#find(windowId); + + if (!target || target.mode !== "normal") { + return false; + } + + return this.#update( + windowId, + (windowState) => ({ + ...windowState, + mode: "maximized", + restoreMode: "maximized", + bounds: this.#snapshot.workArea, + focusOrder: this.#nextFocusOrder(), + }), + "window-maximized", + windowId, + ); + } + + restore(windowId: WindowId): boolean { + const target = this.#find(windowId); + + if (!target || target.mode === "normal") { + return false; + } + + const restoredMode: RestorableWindowMode = + target.mode === "minimized" ? target.restoreMode : "normal"; + const bounds = restoredMode === "maximized" ? this.#snapshot.workArea : target.normalBounds; + + return this.#update( + windowId, + (windowState) => ({ + ...windowState, + mode: restoredMode, + restoreMode: restoredMode, + bounds, + focusOrder: this.#nextFocusOrder(), + }), + "window-restored", + windowId, + ); + } + + close(windowId: WindowId): boolean { + if (!this.#find(windowId)) { + return false; + } + + const windows = this.#snapshot.windows.filter((windowState) => windowState.id !== windowId); + const activeWindowId = + this.#snapshot.activeWindowId === windowId + ? this.#topVisibleWindowId(windows) + : this.#snapshot.activeWindowId; + this.#replace(windows, activeWindowId, "window-closed", windowId); + return true; + } + + setWorkArea(workArea: WindowBounds): void { + const validated = validateWorkArea(workArea); + const windows = this.#snapshot.windows.map((windowState) => { + const normalBounds = constrainBounds( + windowState.normalBounds, + windowState.constraints, + validated, + ); + const bounds = windowState.mode === "maximized" ? validated : normalBounds; + return freezeWindow({ ...windowState, bounds, normalBounds }); + }); + this.#snapshot = freezeSnapshot(windows, this.#snapshot.activeWindowId, validated); + this.#emit("work-area-changed", null); + } + + reset(): void { + if (this.#snapshot.windows.length === 0) { + return; + } + + this.#focusOrder = 0; + this.#replace([], null, "windows-reset", null); + } + + dispose(): void { + this.reset(); + this.#stateChanged.clear(); + } + + #initialBounds( + preferredWidth: number, + preferredHeight: number, + constraints: WindowConstraints, + ): WindowBounds { + const workArea = this.#snapshot.workArea; + const baseBounds = constrainBounds( + { + x: workArea.x + (workArea.width - preferredWidth) / 2, + y: workArea.y + (workArea.height - preferredHeight) / 2, + width: preferredWidth, + height: preferredHeight, + }, + constraints, + workArea, + ); + const cascadeIndex = this.#snapshot.windows.length; + + return constrainBounds( + { + ...baseBounds, + x: baseBounds.x + cascadeIndex * WINDOW_CASCADE_OFFSET, + y: baseBounds.y + cascadeIndex * WINDOW_CASCADE_OFFSET, + }, + constraints, + workArea, + ); + } + + #updateNormalBounds( + windowId: WindowId, + update: (windowState: WindowState) => WindowBounds, + reason: WindowTransitionReason, + ): boolean { + const target = this.#find(windowId); + + if (!target || target.mode !== "normal") { + return false; + } + + return this.#update( + windowId, + (windowState) => { + const bounds = constrainBounds( + update(windowState), + windowState.constraints, + this.#snapshot.workArea, + ); + return { ...windowState, bounds, normalBounds: bounds }; + }, + reason, + this.#snapshot.activeWindowId, + ); + } + + #update( + windowId: WindowId, + update: (windowState: WindowState) => WindowState, + reason: WindowTransitionReason, + activeWindowId: WindowId | null, + ): boolean { + if (!this.#find(windowId)) { + return false; + } + + const windows = this.#snapshot.windows.map((windowState) => + windowState.id === windowId ? freezeWindow(update(windowState)) : windowState, + ); + this.#replace(windows, activeWindowId, reason, windowId); + return true; + } + + #replace( + windows: readonly WindowState[], + activeWindowId: WindowId | null, + reason: WindowTransitionReason, + windowId: WindowId | null, + ): void { + this.#snapshot = freezeSnapshot(windows, activeWindowId, this.#snapshot.workArea); + this.#emit(reason, windowId); + } + + #emit(reason: WindowTransitionReason, windowId: WindowId | null): void { + this.#stateChanged.emit( + Object.freeze({ + type: "window-state-changed", + reason, + windowId, + snapshot: this.#snapshot, + }), + ); + } + + #find(windowId: WindowId): WindowState | undefined { + return this.#snapshot.windows.find((windowState) => windowState.id === windowId); + } + + #topVisibleWindowId( + windows: readonly WindowState[], + excludedWindowId?: WindowId, + ): WindowId | null { + return ( + windows + .filter( + (windowState) => windowState.mode !== "minimized" && windowState.id !== excludedWindowId, + ) + .sort((left, right) => right.focusOrder - left.focusOrder)[0]?.id ?? null + ); + } + + #nextFocusOrder(): number { + this.#focusOrder += 1; + return this.#focusOrder; + } +} + +function normalizeConstraints( + constraints: Partial | undefined, +): WindowConstraints { + const normalized: WindowConstraints = { + minWidth: constraints?.minWidth ?? DEFAULT_MIN_WINDOW_WIDTH, + minHeight: constraints?.minHeight ?? DEFAULT_MIN_WINDOW_HEIGHT, + maxWidth: constraints?.maxWidth ?? null, + maxHeight: constraints?.maxHeight ?? null, + }; + + for (const value of [normalized.minWidth, normalized.minHeight]) { + if (!Number.isFinite(value) || value <= 0) { + throw new RangeError("Minimum window dimensions must be finite and positive."); + } + } + + if (normalized.maxWidth !== null && normalized.maxWidth < normalized.minWidth) { + throw new RangeError("Maximum window width must not be smaller than its minimum."); + } + + if (normalized.maxHeight !== null && normalized.maxHeight < normalized.minHeight) { + throw new RangeError("Maximum window height must not be smaller than its minimum."); + } + + return Object.freeze(normalized); +} + +function constrainBounds( + bounds: WindowBounds, + constraints: WindowConstraints, + workArea: WindowBounds, +): WindowBounds { + for (const value of [bounds.x, bounds.y, bounds.width, bounds.height]) { + if (!Number.isFinite(value)) { + throw new RangeError("Window bounds must contain only finite values."); + } + } + + const maximumWidth = Math.min(constraints.maxWidth ?? workArea.width, workArea.width); + const maximumHeight = Math.min(constraints.maxHeight ?? workArea.height, workArea.height); + const minimumWidth = Math.min(constraints.minWidth, maximumWidth); + const minimumHeight = Math.min(constraints.minHeight, maximumHeight); + const width = clamp(bounds.width, minimumWidth, maximumWidth); + const height = clamp(bounds.height, minimumHeight, maximumHeight); + const x = clamp(bounds.x, workArea.x, workArea.x + workArea.width - width); + const y = clamp(bounds.y, workArea.y, workArea.y + workArea.height - height); + + return Object.freeze({ x, y, width, height }); +} + +function validateWorkArea(workArea: WindowBounds): WindowBounds { + for (const value of [workArea.x, workArea.y, workArea.width, workArea.height]) { + if (!Number.isFinite(value)) { + throw new RangeError("Work area bounds must contain only finite values."); + } + } + + if (workArea.width <= 0 || workArea.height <= 0) { + throw new RangeError("Work area dimensions must be positive."); + } + + return Object.freeze({ ...workArea }); +} + +function freezeWindow(windowState: WindowState): WindowState { + return Object.freeze({ + ...windowState, + bounds: Object.freeze({ ...windowState.bounds }), + normalBounds: Object.freeze({ ...windowState.normalBounds }), + constraints: Object.freeze({ ...windowState.constraints }), + }); +} + +function freezeSnapshot( + windows: readonly WindowState[], + activeWindowId: WindowId | null, + workArea: WindowBounds, +): WindowManagerSnapshot { + return Object.freeze({ + windows: Object.freeze([...windows]), + activeWindowId, + workArea: Object.freeze({ ...workArea }), + }); +} + +function clamp(value: number, minimum: number, maximum: number): number { + return Math.min(Math.max(value, minimum), maximum); +} diff --git a/src/shell/windows/window-state.ts b/src/shell/windows/window-state.ts new file mode 100644 index 0000000..07f27cd --- /dev/null +++ b/src/shell/windows/window-state.ts @@ -0,0 +1,63 @@ +import type { ApplicationInstanceId, WindowId } from "../../core/identity/identifiers"; + +export type WindowMode = "normal" | "minimized" | "maximized"; +export type RestorableWindowMode = Exclude; + +export interface WindowBounds { + readonly x: number; + readonly y: number; + readonly width: number; + readonly height: number; +} + +export interface WindowConstraints { + readonly minWidth: number; + readonly minHeight: number; + readonly maxWidth: number | null; + readonly maxHeight: number | null; +} + +export interface WindowState { + readonly id: WindowId; + readonly ownerId: ApplicationInstanceId; + readonly title: string; + readonly bounds: WindowBounds; + readonly normalBounds: WindowBounds; + readonly constraints: WindowConstraints; + readonly mode: WindowMode; + readonly restoreMode: RestorableWindowMode; + readonly focusOrder: number; +} + +export interface WindowManagerSnapshot { + readonly windows: readonly WindowState[]; + readonly activeWindowId: WindowId | null; + readonly workArea: WindowBounds; +} + +export interface OpenWindowRequest { + readonly ownerId: ApplicationInstanceId; + readonly title: string; + readonly preferredWidth?: number; + readonly preferredHeight?: number; + readonly constraints?: Partial; +} + +export type WindowTransitionReason = + | "window-opened" + | "window-focused" + | "window-moved" + | "window-resized" + | "window-minimized" + | "window-maximized" + | "window-restored" + | "window-closed" + | "work-area-changed" + | "windows-reset"; + +export interface WindowStateChanged { + readonly type: "window-state-changed"; + readonly reason: WindowTransitionReason; + readonly windowId: WindowId | null; + readonly snapshot: WindowManagerSnapshot; +} diff --git a/src/styles/windows.css b/src/styles/windows.css new file mode 100644 index 0000000..dce7677 --- /dev/null +++ b/src/styles/windows.css @@ -0,0 +1,358 @@ +.desktop-shell { + height: 100vh; + min-height: 32rem; + padding: 1rem 1rem 0; + overflow: hidden; + background: + linear-gradient(115deg, transparent 64%, rgb(255 107 85 / 7%) 64%), + radial-gradient(circle at 18% 76%, rgb(143 240 189 / 8%), transparent 28%); +} + +.desktop-shell__header { + min-height: 2rem; +} + +.desktop-shell__ready { + margin: 0; + color: var(--color-muted); + font-size: 0.7rem; + font-weight: 400; + text-transform: uppercase; +} + +.desktop-shell__workspace { + position: relative; + display: block; + width: 100%; + min-height: 0; + padding: 0; + overflow: hidden; + border-inline: 1px solid var(--color-rule); + animation: desktop-enter 350ms ease-out both; +} + +.desktop-shell__identity { + position: absolute; + z-index: 0; + top: 2rem; + left: 2rem; + pointer-events: none; +} + +.desktop-shell__environment, +.desktop-shell__description { + margin: 0; +} + +.desktop-shell__wordmark { + margin: 0.35rem 0; + color: rgb(237 247 241 / 12%); + font-family: Impact, Haettenschweiler, "Arial Narrow Bold", sans-serif; + font-size: clamp(4rem, 12vw, 10rem); + line-height: 0.85; +} + +.desktop-shell__description { + color: var(--color-muted); + font-size: 0.7rem; + letter-spacing: 0; +} + +.window-layer { + position: absolute; + z-index: 1; + inset: 0; + overflow: hidden; +} + +.os-window { + position: absolute; + display: grid; + grid-template-rows: 2.75rem minmax(0, 1fr); + min-width: 0; + min-height: 0; + overflow: hidden; + border: 1px solid var(--color-rule-strong); + border-radius: 3px; + color: var(--color-ink); + background: #0c1214; + box-shadow: 0 1.25rem 3rem rgb(0 0 0 / 45%); +} + +.os-window[hidden] { + display: none; +} + +.os-window[data-active="true"] { + border-color: var(--color-signal); + box-shadow: + 0 0 0 1px rgb(143 240 189 / 18%), + 0 1.5rem 3.5rem rgb(0 0 0 / 55%); +} + +.os-window__titlebar { + display: grid; + grid-template-columns: minmax(0, 1fr) auto; + align-items: center; + min-width: 0; + border-bottom: 1px solid var(--color-rule); + background: var(--color-panel-raised); + cursor: move; + user-select: none; + touch-action: none; +} + +.os-window__title { + min-width: 0; + margin: 0; + padding-inline: 0.85rem; + overflow: hidden; + font-size: 0.75rem; + line-height: 1; + text-overflow: ellipsis; + text-transform: uppercase; + white-space: nowrap; +} + +.os-window__controls { + display: flex; + align-self: stretch; +} + +.os-window__control { + display: grid; + width: 2.75rem; + min-width: 2.75rem; + padding: 0; + place-items: center; + border: 0; + border-left: 1px solid var(--color-rule); + border-radius: 0; + color: var(--color-muted); + background: transparent; + cursor: pointer; +} + +.os-window__control--close:hover { + color: #fff; + background: var(--color-alert); +} + +.os-window__content { + min-width: 0; + min-height: 0; + overflow: auto; +} + +.os-window__resize-handle { + position: absolute; + right: 0; + bottom: 0; + width: 1.25rem; + height: 1.25rem; + cursor: nwse-resize; + touch-action: none; +} + +.os-window__resize-handle::after { + position: absolute; + right: 0.25rem; + bottom: 0.25rem; + width: 0.5rem; + height: 0.5rem; + border-right: 1px solid var(--color-signal); + border-bottom: 1px solid var(--color-signal); + content: ""; +} + +.os-window[data-mode="maximized"] .os-window__titlebar { + cursor: default; +} + +.os-window[data-mode="maximized"] .os-window__resize-handle { + display: none; +} + +.desktop-shell__footer { + display: grid; + grid-template-columns: auto minmax(0, 1fr) auto auto; + gap: 0.75rem; + min-height: 4rem; + padding: 0.6rem 0; +} + +.application-launcher, +.window-task-strip { + display: flex; + align-items: center; + gap: 0.4rem; + min-width: 0; +} + +.window-task-strip { + overflow-x: auto; +} + +.application-launcher__label { + color: var(--color-signal); + font-size: 0.65rem; +} + +.application-launcher__button, +.window-task-strip__button, +.diagnostics-app__action { + min-height: 2.5rem; + padding-inline: 0.85rem; + border: 1px solid var(--color-rule-strong); + border-radius: 2px; + color: var(--color-ink); + background: var(--color-panel); + cursor: pointer; +} + +.window-task-strip__button { + max-width: 13rem; + overflow: hidden; + color: var(--color-muted); + font-size: 0.7rem; + text-overflow: ellipsis; + white-space: nowrap; +} + +.window-task-strip__button[data-active="true"] { + border-color: var(--color-signal); + color: var(--color-ink); +} + +.window-task-strip__button[data-mode="minimized"] { + border-style: dashed; +} + +.desktop-shell .system-clock { + display: grid; + min-width: 7rem; + padding: 0 0.75rem; + border: 0; + border-inline: 1px solid var(--color-rule); + justify-items: end; +} + +.desktop-shell .system-clock__time { + margin: 0; + font-family: inherit; + font-size: 1rem; +} + +.desktop-shell .system-clock__date { + margin: 0; + font-size: 0.65rem; +} + +.diagnostics-app, +.diagnostics-detail { + min-height: 100%; + padding: 1.5rem; + background: linear-gradient(90deg, rgb(143 240 189 / 4%) 1px, transparent 1px), #0c1214; + background-size: 2rem 2rem; +} + +.diagnostics-app__title, +.diagnostics-detail__title { + margin: 0; + font-family: Impact, Haettenschweiler, "Arial Narrow Bold", sans-serif; + font-size: 2.25rem; + font-weight: 400; + letter-spacing: 0; + text-transform: uppercase; +} + +.diagnostics-app__status, +.diagnostics-detail__eyebrow { + margin: 0 0 0.75rem; + color: var(--color-signal); + font-size: 0.7rem; +} + +.diagnostics-app__facts { + margin: 1.5rem 0; + border-top: 1px solid var(--color-rule); +} + +.diagnostics-app__fact { + display: grid; + grid-template-columns: minmax(7rem, 0.7fr) minmax(0, 1fr); + gap: 1rem; + padding: 0.8rem 0; + border-bottom: 1px solid var(--color-rule); +} + +.diagnostics-app__term, +.diagnostics-app__value { + margin: 0; + overflow-wrap: anywhere; + font-size: 0.75rem; +} + +.diagnostics-app__term { + color: var(--color-muted); +} + +.diagnostics-detail__copy { + max-width: 34rem; + color: var(--color-muted); + line-height: 1.7; +} + +@media (max-width: 44rem) { + .desktop-shell { + min-height: 28rem; + padding: 0.75rem 0.75rem 0; + } + + .desktop-shell__identity { + display: none; + } + + .os-window { + inset: 0 !important; + width: 100% !important; + height: 100% !important; + border: 0; + border-radius: 0; + } + + .os-window[data-active="false"] { + display: none; + } + + .os-window__titlebar { + cursor: default; + } + + .os-window__resize-handle { + display: none; + } + + .desktop-shell__footer { + grid-template-columns: minmax(0, 1fr) auto; + grid-template-rows: auto auto; + } + + .application-launcher { + grid-column: 1; + } + + .window-task-strip { + grid-column: 1 / -1; + grid-row: 2; + } + + .desktop-shell .system-clock { + display: none; + } + + .desktop-shell__reset { + grid-column: 2; + grid-row: 1; + } +} diff --git a/tests/e2e/windows-applications.spec.ts b/tests/e2e/windows-applications.spec.ts new file mode 100644 index 0000000..b8037ed --- /dev/null +++ b/tests/e2e/windows-applications.spec.ts @@ -0,0 +1,168 @@ +import { expect, test, type Page } from "@playwright/test"; + +function monitorPageFailures(page: Page): string[] { + const failures: string[] = []; + + page.on("console", (message) => { + if (message.type() === "error") { + failures.push(`console: ${message.text()}`); + } + }); + page.on("pageerror", (error) => failures.push(`page: ${error.message}`)); + page.on("requestfailed", (request) => { + failures.push(`request: ${request.url()} ${request.failure()?.errorText ?? "unknown failure"}`); + }); + return failures; +} + +async function openDesktop(page: Page): Promise { + const failures = monitorPageFailures(page); + await page.goto("/"); + await page.getByRole("button", { name: "Skip boot sequence" }).click(); + await expect(page.getByRole("heading", { name: "Desktop ready" })).toBeVisible(); + return failures; +} + +async function launchDiagnostics(page: Page): Promise { + await page.getByRole("button", { name: "System Diagnostics" }).click(); + await expect(page.getByRole("dialog", { name: "System Diagnostics" })).toBeVisible(); +} + +test("launches one application instance and coordinates multiple owned windows", async ({ + page, +}) => { + const failures = await openDesktop(page); + const launcher = page.getByRole("button", { name: "System Diagnostics", exact: true }); + + await launcher.click(); + const primary = page.getByRole("dialog", { name: "System Diagnostics" }); + await expect(primary).toBeVisible(); + await expect(primary).toContainText("application-instance-1"); + + await launcher.click(); + await expect(page.getByRole("dialog")).toHaveCount(1); + await expect(primary).toHaveAttribute("data-active", "true"); + + await primary.getByRole("button", { name: "Open lifecycle detail" }).click(); + const detail = page.getByRole("dialog", { name: "Lifecycle Detail 01" }); + await expect(detail).toBeVisible(); + await expect(page.getByRole("dialog")).toHaveCount(2); + await expect(detail).toHaveAttribute("data-active", "true"); + + await page.getByRole("button", { name: "Focus System Diagnostics" }).click(); + await expect(primary).toHaveAttribute("data-active", "true"); + await expect(detail).toHaveAttribute("data-active", "false"); + expect(failures).toEqual([]); +}); + +test("moves and resizes a floating window with pointer input", async ({ page }) => { + const failures = await openDesktop(page); + await launchDiagnostics(page); + const dialog = page.getByRole("dialog", { name: "System Diagnostics" }); + const initial = await dialog.boundingBox(); + expect(initial).not.toBeNull(); + + const titleBar = dialog.locator(".os-window__titlebar"); + const titleBounds = await titleBar.boundingBox(); + expect(titleBounds).not.toBeNull(); + await page.mouse.move(titleBounds!.x + 80, titleBounds!.y + 20); + await page.mouse.down(); + await page.mouse.move(titleBounds!.x + 150, titleBounds!.y + 70, { steps: 4 }); + await page.mouse.up(); + const moved = await dialog.boundingBox(); + expect(moved!.x).toBeGreaterThan(initial!.x + 50); + expect(moved!.y).toBeGreaterThan(initial!.y + 30); + + const resizeHandle = dialog.locator(".os-window__resize-handle"); + const handleBounds = await resizeHandle.boundingBox(); + expect(handleBounds).not.toBeNull(); + await page.mouse.move(handleBounds!.x + 8, handleBounds!.y + 8); + await page.mouse.down(); + await page.mouse.move(handleBounds!.x + 88, handleBounds!.y + 58, { steps: 4 }); + await page.mouse.up(); + const resized = await dialog.boundingBox(); + expect(resized!.width).toBeGreaterThan(moved!.width + 60); + expect(resized!.height).toBeGreaterThan(moved!.height + 35); + expect(failures).toEqual([]); +}); + +test("minimizes, restores, maximizes, restores, and closes a window", async ({ page }) => { + const failures = await openDesktop(page); + await launchDiagnostics(page); + const dialog = page.getByRole("dialog", { name: "System Diagnostics" }); + + await dialog.getByRole("button", { name: "Minimize window" }).click(); + await expect(dialog).toBeHidden(); + const restoreTask = page.getByRole("button", { name: "Restore System Diagnostics" }); + await expect(restoreTask).toBeFocused(); + await restoreTask.press("Enter"); + await expect(dialog).toBeVisible(); + + await dialog.getByRole("button", { name: "Maximize window" }).click(); + await expect(dialog).toHaveAttribute("data-mode", "maximized"); + await dialog.getByRole("button", { name: "Restore window" }).click(); + await expect(dialog).toHaveAttribute("data-mode", "normal"); + + await dialog.getByRole("button", { name: "Close window" }).click(); + await expect(dialog).toHaveCount(0); + await expect(page.getByRole("button", { name: "System Diagnostics" })).toBeFocused(); + expect(failures).toEqual([]); +}); + +test("supports keyboard launch and window controls without global shortcuts", async ({ page }) => { + const failures = await openDesktop(page); + const launcher = page.getByRole("button", { name: "System Diagnostics" }); + await launcher.focus(); + await page.keyboard.press("Enter"); + + const dialog = page.getByRole("dialog", { name: "System Diagnostics" }); + await expect(dialog).toBeFocused(); + await page.keyboard.press("Tab"); + await expect(dialog.getByRole("button", { name: "Minimize window" })).toBeFocused(); + await page.keyboard.press("Enter"); + await expect(page.getByRole("button", { name: "Restore System Diagnostics" })).toBeFocused(); + expect(failures).toEqual([]); +}); + +test("fills the mobile work area with only the active window", async ({ page }) => { + const failures = monitorPageFailures(page); + await page.setViewportSize({ width: 360, height: 740 }); + await page.goto("/"); + await page.getByRole("button", { name: "Skip boot sequence" }).click(); + await launchDiagnostics(page); + const primary = page.getByRole("dialog", { name: "System Diagnostics" }); + await primary.getByRole("button", { name: "Open lifecycle detail" }).click(); + const detail = page.getByRole("dialog", { name: "Lifecycle Detail 01" }); + const workArea = await page.getByLabel("Open application windows").boundingBox(); + const detailBounds = await detail.boundingBox(); + + expect(detailBounds).toEqual(workArea); + await expect(primary).toBeHidden(); + await page.getByRole("button", { name: "Focus System Diagnostics" }).click(); + await expect(primary).toBeVisible(); + await expect(detail).toBeHidden(); + const pageSize = await page.locator("body").evaluate((body) => ({ + scrollWidth: body.scrollWidth, + viewportWidth: document.documentElement.clientWidth, + })); + expect(pageSize.scrollWidth).toBeLessThanOrEqual(pageSize.viewportWidth); + expect(failures).toEqual([]); +}); + +test("restart disposes open applications and returns to a clean desktop", async ({ page }) => { + const failures = await openDesktop(page); + await launchDiagnostics(page); + await page + .getByRole("dialog", { name: "System Diagnostics" }) + .getByRole("button", { name: "Open lifecycle detail" }) + .click(); + + await page.getByRole("button", { name: "Restart SHADOW OS" }).click(); + await page.getByRole("button", { name: "Skip boot sequence" }).click(); + + await expect(page.getByText("ENVIRONMENT / CYCLE 02")).toBeVisible(); + await expect(page.getByRole("dialog")).toHaveCount(0); + await launchDiagnostics(page); + await expect(page.getByText("application-instance-2")).toBeVisible(); + expect(failures).toEqual([]); +}); diff --git a/tests/helpers/fake-id-generator.ts b/tests/helpers/fake-id-generator.ts new file mode 100644 index 0000000..ce8577a --- /dev/null +++ b/tests/helpers/fake-id-generator.ts @@ -0,0 +1,11 @@ +import type { IdGenerator, IdScope } from "../../src/core/identity/identifiers"; + +export class FakeIdGenerator implements IdGenerator { + readonly #counts = new Map(); + + next(scope: IdScope): string { + const nextCount = (this.#counts.get(scope) ?? 0) + 1; + this.#counts.set(scope, nextCount); + return `${scope}-${nextCount}`; + } +} diff --git a/tests/integration/application-window-lifecycle.test.ts b/tests/integration/application-window-lifecycle.test.ts new file mode 100644 index 0000000..3e95e1f --- /dev/null +++ b/tests/integration/application-window-lifecycle.test.ts @@ -0,0 +1,53 @@ +import { describe, expect, it, vi } from "vitest"; + +import type { ApplicationContext } from "../../src/applications/framework/application"; +import { ApplicationManager } from "../../src/applications/framework/application-manager"; +import { ApplicationRegistry } from "../../src/applications/framework/application-registry"; +import { toApplicationId } from "../../src/core/identity/identifiers"; +import { WindowManager } from "../../src/shell/windows/window-manager"; +import { FakeIdGenerator } from "../helpers/fake-id-generator"; + +describe("application and window lifecycle", () => { + it("coordinates startup registration, launch, multiple windows, relaunch, and close", () => { + const applicationId = toApplicationId("system.diagnostics"); + const dispose = vi.fn(); + let context: ApplicationContext | undefined; + const registry = new ApplicationRegistry([ + { + manifest: { + id: applicationId, + name: "System Diagnostics", + description: "Inspect the M2 application contract.", + window: { title: "System Diagnostics" }, + }, + create: (createdContext) => { + context = createdContext; + return { + primaryView: { mount: () => () => undefined }, + dispose, + }; + }, + }, + ]); + const ids = new FakeIdGenerator(); + const windows = new WindowManager(ids, { x: 0, y: 0, width: 1000, height: 700 }); + const applications = new ApplicationManager(registry, windows, ids); + + const instanceId = applications.launch(applicationId); + const detailWindowId = context!.openWindow({ + title: "Lifecycle Detail", + view: { mount: () => () => undefined }, + }); + windows.focus(applications.snapshot.instances[0]!.primaryWindowId); + + expect(applications.launch(applicationId)).toBe(instanceId); + expect(applications.snapshot.instances).toHaveLength(1); + expect(windows.snapshot.windows).toHaveLength(2); + expect(applications.closeWindow(detailWindowId)).toBe(true); + expect(windows.snapshot.windows).toHaveLength(1); + expect(applications.closeInstance(instanceId)).toBe(true); + expect(dispose).toHaveBeenCalledTimes(1); + expect(applications.snapshot.instances).toEqual([]); + expect(windows.snapshot.windows).toEqual([]); + }); +}); diff --git a/tests/unit/application-manager.test.ts b/tests/unit/application-manager.test.ts new file mode 100644 index 0000000..b208337 --- /dev/null +++ b/tests/unit/application-manager.test.ts @@ -0,0 +1,134 @@ +import { describe, expect, it, vi } from "vitest"; + +import type { + ApplicationContext, + ApplicationDefinition, + ApplicationView, +} from "../../src/applications/framework/application"; +import { ApplicationManager } from "../../src/applications/framework/application-manager"; +import { ApplicationRegistry } from "../../src/applications/framework/application-registry"; +import { toApplicationId, toWindowId } from "../../src/core/identity/identifiers"; +import { WindowManager } from "../../src/shell/windows/window-manager"; +import { FakeIdGenerator } from "../helpers/fake-id-generator"; + +const APPLICATION_ID = toApplicationId("system.diagnostics"); +const EMPTY_VIEW: ApplicationView = { mount: () => () => undefined }; + +function createDefinition(dispose = vi.fn()): { + definition: ApplicationDefinition; + contexts: ApplicationContext[]; + dispose: ReturnType; +} { + const contexts: ApplicationContext[] = []; + return { + contexts, + dispose, + definition: { + manifest: { + id: APPLICATION_ID, + name: "System Diagnostics", + description: "Inspect the M2 application contract.", + window: { title: "System Diagnostics", preferredWidth: 700, preferredHeight: 480 }, + }, + create: (context) => { + contexts.push(context); + return { primaryView: EMPTY_VIEW, dispose }; + }, + }, + }; +} + +function createSystem(definition: ApplicationDefinition): { + applications: ApplicationManager; + windows: WindowManager; +} { + const ids = new FakeIdGenerator(); + const windows = new WindowManager(ids, { x: 0, y: 0, width: 1200, height: 800 }); + const applications = new ApplicationManager(new ApplicationRegistry([definition]), windows, ids); + return { applications, windows }; +} + +describe("ApplicationManager", () => { + it("launches a registered application with a primary window and view", () => { + const fixture = createDefinition(); + const { applications, windows } = createSystem(fixture.definition); + + const instanceId = applications.launch(APPLICATION_ID); + const state = applications.snapshot.instances[0]; + + expect(instanceId).toBe("application-instance-1"); + expect(state).toMatchObject({ id: instanceId, applicationId: APPLICATION_ID }); + expect(windows.snapshot.windows[0]).toMatchObject({ + id: state?.primaryWindowId, + ownerId: instanceId, + title: "System Diagnostics", + }); + expect(applications.getView(state!.primaryWindowId)).toBe(EMPTY_VIEW); + }); + + it("enforces single-instance launch and restores/focuses the existing primary window", () => { + const fixture = createDefinition(); + const { applications, windows } = createSystem(fixture.definition); + const instanceId = applications.launch(APPLICATION_ID); + const primaryWindowId = applications.snapshot.instances[0]!.primaryWindowId; + windows.minimize(primaryWindowId); + + expect(applications.launch(APPLICATION_ID)).toBe(instanceId); + expect(applications.snapshot.instances).toHaveLength(1); + expect(windows.snapshot.windows[0]?.mode).toBe("normal"); + expect(windows.snapshot.activeWindowId).toBe(primaryWindowId); + expect(fixture.contexts).toHaveLength(1); + }); + + it("opens and closes an auxiliary window through the scoped application context", () => { + const fixture = createDefinition(); + const { applications, windows } = createSystem(fixture.definition); + applications.launch(APPLICATION_ID); + + const auxiliaryId = fixture.contexts[0]!.openWindow({ + title: "Diagnostic Detail", + view: EMPTY_VIEW, + }); + + expect(applications.snapshot.instances[0]?.windowIds).toHaveLength(2); + expect(windows.snapshot.windows).toHaveLength(2); + expect(applications.getView(auxiliaryId)).toBe(EMPTY_VIEW); + expect(applications.closeWindow(auxiliaryId)).toBe(true); + expect(applications.snapshot.instances[0]?.windowIds).toHaveLength(1); + expect(windows.snapshot.windows).toHaveLength(1); + }); + + it("closes all owned windows and disposes exactly once when the primary closes", () => { + const fixture = createDefinition(); + const { applications, windows } = createSystem(fixture.definition); + const instanceId = applications.launch(APPLICATION_ID); + const primaryWindowId = applications.snapshot.instances[0]!.primaryWindowId; + fixture.contexts[0]!.openWindow({ title: "Diagnostic Detail", view: EMPTY_VIEW }); + + expect(applications.closeWindow(primaryWindowId)).toBe(true); + expect(applications.snapshot.instances).toEqual([]); + expect(windows.snapshot.windows).toEqual([]); + expect(fixture.dispose).toHaveBeenCalledTimes(1); + expect(applications.closeInstance(instanceId)).toBe(false); + }); + + it("resets all application and window state and disposes instances", () => { + const fixture = createDefinition(); + const { applications, windows } = createSystem(fixture.definition); + applications.launch(APPLICATION_ID); + fixture.contexts[0]!.openWindow({ title: "Diagnostic Detail", view: EMPTY_VIEW }); + + applications.reset(); + + expect(applications.snapshot.instances).toEqual([]); + expect(windows.snapshot.windows).toEqual([]); + expect(fixture.dispose).toHaveBeenCalledTimes(1); + }); + + it("returns false for windows and instances it does not own", () => { + const fixture = createDefinition(); + const { applications } = createSystem(fixture.definition); + + expect(applications.closeWindow(toWindowId("missing"))).toBe(false); + }); +}); diff --git a/tests/unit/application-registry.test.ts b/tests/unit/application-registry.test.ts new file mode 100644 index 0000000..c4eca3b --- /dev/null +++ b/tests/unit/application-registry.test.ts @@ -0,0 +1,47 @@ +import { describe, expect, it } from "vitest"; + +import type { ApplicationDefinition } from "../../src/applications/framework/application"; +import { + ApplicationRegistry, + DuplicateApplicationError, + UnknownApplicationError, +} from "../../src/applications/framework/application-registry"; +import { toApplicationId } from "../../src/core/identity/identifiers"; + +const APPLICATION_ID = toApplicationId("system.diagnostics"); + +function definition(name = "System Diagnostics"): ApplicationDefinition { + return { + manifest: { + id: APPLICATION_ID, + name, + description: "Inspect the M2 application contract.", + window: { title: "System Diagnostics" }, + }, + create: () => ({ primaryView: { mount: () => () => undefined }, dispose: () => undefined }), + }; +} + +describe("ApplicationRegistry", () => { + it("lists and resolves immutable startup definitions", () => { + const source = definition(); + const registry = new ApplicationRegistry([source]); + + expect(registry.list()).toEqual([source.manifest]); + expect(registry.get(APPLICATION_ID).manifest.name).toBe("System Diagnostics"); + expect(Object.isFrozen(registry.list())).toBe(true); + expect(Object.isFrozen(registry.get(APPLICATION_ID).manifest)).toBe(true); + }); + + it("rejects duplicate application identifiers", () => { + expect(() => new ApplicationRegistry([definition(), definition("Duplicate")])).toThrow( + DuplicateApplicationError, + ); + }); + + it("rejects unknown application identifiers", () => { + const registry = new ApplicationRegistry([definition()]); + + expect(() => registry.get(toApplicationId("missing"))).toThrow(UnknownApplicationError); + }); +}); diff --git a/tests/unit/window-manager.test.ts b/tests/unit/window-manager.test.ts new file mode 100644 index 0000000..7838dd0 --- /dev/null +++ b/tests/unit/window-manager.test.ts @@ -0,0 +1,166 @@ +import { describe, expect, it } from "vitest"; + +import { toApplicationInstanceId, toWindowId } from "../../src/core/identity/identifiers"; +import { WINDOW_CASCADE_OFFSET, WindowManager } from "../../src/shell/windows/window-manager"; +import { FakeIdGenerator } from "../helpers/fake-id-generator"; + +const WORK_AREA = { x: 0, y: 0, width: 1200, height: 800 } as const; +const OWNER_ID = toApplicationInstanceId("application-instance-1"); + +function createManager(): WindowManager { + return new WindowManager(new FakeIdGenerator(), WORK_AREA); +} + +describe("WindowManager", () => { + it("centers the first window and cascades subsequent windows deterministically", () => { + const manager = createManager(); + + const firstId = manager.open({ ownerId: OWNER_ID, title: "Primary" }); + const secondId = manager.open({ ownerId: OWNER_ID, title: "Secondary" }); + + expect(firstId).toBe("window-1"); + expect(manager.snapshot.windows[0]?.bounds).toEqual({ + x: 280, + y: 190, + width: 640, + height: 420, + }); + expect(manager.snapshot.windows[1]?.bounds).toEqual({ + x: 280 + WINDOW_CASCADE_OFFSET, + y: 190 + WINDOW_CASCADE_OFFSET, + width: 640, + height: 420, + }); + expect(manager.snapshot.activeWindowId).toBe(secondId); + }); + + it("focuses visible windows with deterministic z-order", () => { + const manager = createManager(); + const firstId = manager.open({ ownerId: OWNER_ID, title: "Primary" }); + const secondId = manager.open({ ownerId: OWNER_ID, title: "Secondary" }); + + expect(manager.focus(firstId)).toBe(true); + expect(manager.snapshot.activeWindowId).toBe(firstId); + expect( + manager.snapshot.windows.find((windowState) => windowState.id === firstId)?.focusOrder, + ).toBeGreaterThan( + manager.snapshot.windows.find((windowState) => windowState.id === secondId)?.focusOrder ?? 0, + ); + }); + + it("moves and resizes normal windows within work-area constraints", () => { + const manager = createManager(); + const windowId = manager.open({ ownerId: OWNER_ID, title: "Primary" }); + + expect(manager.move(windowId, { x: 900, y: -100 })).toBe(true); + expect(manager.snapshot.windows[0]?.bounds).toEqual({ x: 560, y: 0, width: 640, height: 420 }); + + expect(manager.resize(windowId, { x: 1_000, y: 700, width: 100, height: 100 })).toBe(true); + expect(manager.snapshot.windows[0]?.bounds).toEqual({ + x: 880, + y: 580, + width: 320, + height: 220, + }); + }); + + it("minimizes the active window and focuses the next visible window", () => { + const manager = createManager(); + const firstId = manager.open({ ownerId: OWNER_ID, title: "Primary" }); + const secondId = manager.open({ ownerId: OWNER_ID, title: "Secondary" }); + + expect(manager.minimize(secondId)).toBe(true); + expect(manager.snapshot.activeWindowId).toBe(firstId); + expect(manager.snapshot.windows[1]?.mode).toBe("minimized"); + expect(manager.focus(secondId)).toBe(false); + }); + + it("maximizes and restores the previous normal geometry", () => { + const manager = createManager(); + const windowId = manager.open({ ownerId: OWNER_ID, title: "Primary" }); + manager.move(windowId, { x: 80, y: 90 }); + const normalBounds = manager.snapshot.windows[0]?.bounds; + + expect(manager.maximize(windowId)).toBe(true); + expect(manager.snapshot.windows[0]).toMatchObject({ mode: "maximized", bounds: WORK_AREA }); + expect(manager.move(windowId, { x: 10, y: 10 })).toBe(false); + + expect(manager.restore(windowId)).toBe(true); + expect(manager.snapshot.windows[0]).toMatchObject({ mode: "normal", bounds: normalBounds }); + }); + + it("restores a window minimized from maximized back to maximized", () => { + const manager = createManager(); + const windowId = manager.open({ ownerId: OWNER_ID, title: "Primary" }); + manager.maximize(windowId); + manager.minimize(windowId); + + expect(manager.restore(windowId)).toBe(true); + expect(manager.snapshot.windows[0]).toMatchObject({ mode: "maximized", bounds: WORK_AREA }); + }); + + it("removes closed windows and selects the top remaining window", () => { + const manager = createManager(); + const firstId = manager.open({ ownerId: OWNER_ID, title: "Primary" }); + const secondId = manager.open({ ownerId: OWNER_ID, title: "Secondary" }); + + expect(manager.close(secondId)).toBe(true); + expect(manager.snapshot.windows.map((windowState) => windowState.id)).toEqual([firstId]); + expect(manager.snapshot.activeWindowId).toBe(firstId); + expect(manager.close(toWindowId("missing"))).toBe(false); + }); + + it("reconstrains windows when the work area changes", () => { + const manager = createManager(); + const normalId = manager.open({ ownerId: OWNER_ID, title: "Normal" }); + const maximizedId = manager.open({ ownerId: OWNER_ID, title: "Maximized" }); + manager.move(normalId, { x: 500, y: 300 }); + manager.maximize(maximizedId); + + manager.setWorkArea({ x: 0, y: 0, width: 500, height: 400 }); + + expect(manager.snapshot.windows[0]?.bounds).toEqual({ x: 0, y: 0, width: 500, height: 400 }); + expect(manager.snapshot.windows[1]?.bounds).toEqual({ x: 0, y: 0, width: 500, height: 400 }); + }); + + it("emits immutable facts and resets without stale windows", () => { + const manager = createManager(); + const reasons: string[] = []; + manager.onStateChanged((event) => reasons.push(event.reason)); + const windowId = manager.open({ ownerId: OWNER_ID, title: "Primary" }); + manager.minimize(windowId); + manager.restore(windowId); + manager.close(windowId); + manager.open({ ownerId: OWNER_ID, title: "Fresh" }); + manager.reset(); + + expect(reasons).toEqual([ + "window-opened", + "window-minimized", + "window-restored", + "window-closed", + "window-opened", + "windows-reset", + ]); + expect(manager.snapshot.windows).toEqual([]); + expect(Object.isFrozen(manager.snapshot)).toBe(true); + }); + + it("rejects invalid work areas, dimensions, and impossible constraints", () => { + expect( + () => new WindowManager(new FakeIdGenerator(), { x: 0, y: 0, width: 0, height: 1 }), + ).toThrow("Work area dimensions must be positive."); + const manager = createManager(); + expect(() => + manager.open({ + ownerId: OWNER_ID, + title: "Invalid", + constraints: { minWidth: 500, maxWidth: 400 }, + }), + ).toThrow("Maximum window width must not be smaller than its minimum."); + const windowId = manager.open({ ownerId: OWNER_ID, title: "Primary" }); + expect(() => manager.move(windowId, { x: Number.NaN, y: 0 })).toThrow( + "Window bounds must contain only finite values.", + ); + }); +}); From 0051e5dfcada111677928841cc23d06570fc2de0 Mon Sep 17 00:00:00 2001 From: Suvankar Das <137081476+ShadowSD10@users.noreply.github.com> Date: Sun, 27 Sep 2026 13:48:47 -0700 Subject: [PATCH 3/3] Feature/m3 applications os experience (#4) * docs: record M3 architecture planning * feat: add M3 application launcher and context menu * style: refine M3 launcher and context menu * docs: record M3 Phase 1 completion * feat: add M3 notepad application * refactor: rename notepad to notes * style: refine notes application icon * feat: add M3 calculator application * style: clarify calculator operation state * style: clarify calculator operation state * feat: add M3 clock application --- docs/SESSION_RESULTS.md | 611 ++++++++++++++++++ src/applications/built-in/calculator-model.ts | 222 +++++++ src/applications/built-in/calculator.ts | 266 ++++++++ src/applications/built-in/clock-model.ts | 77 +++ src/applications/built-in/clock.ts | 74 +++ src/applications/built-in/notepad-model.ts | 15 + src/applications/built-in/notepad.ts | 55 ++ src/bootstrap/start-afterboot.ts | 10 +- src/shell/desktop/application-drawer-view.ts | 302 +++++++++ src/shell/desktop/context-menu-model.ts | 32 + src/shell/desktop/context-menu-view.ts | 171 +++++ src/shell/desktop/desktop-view.ts | 128 ++-- src/styles/windows.css | 480 +++++++++++++- tests/e2e/calculator.spec.ts | 226 +++++++ tests/e2e/clock.spec.ts | 190 ++++++ tests/e2e/notepad.spec.ts | 153 +++++ tests/e2e/shell-foundation.spec.ts | 143 ++++ tests/e2e/windows-applications.spec.ts | 27 +- .../application-window-lifecycle.test.ts | 126 ++++ tests/unit/calculator-model.test.ts | 201 ++++++ tests/unit/clock-model.test.ts | 108 ++++ tests/unit/context-menu-model.test.ts | 42 ++ tests/unit/notepad-model.test.ts | 26 + 23 files changed, 3634 insertions(+), 51 deletions(-) create mode 100644 src/applications/built-in/calculator-model.ts create mode 100644 src/applications/built-in/calculator.ts create mode 100644 src/applications/built-in/clock-model.ts create mode 100644 src/applications/built-in/clock.ts create mode 100644 src/applications/built-in/notepad-model.ts create mode 100644 src/applications/built-in/notepad.ts create mode 100644 src/shell/desktop/application-drawer-view.ts create mode 100644 src/shell/desktop/context-menu-model.ts create mode 100644 src/shell/desktop/context-menu-view.ts create mode 100644 tests/e2e/calculator.spec.ts create mode 100644 tests/e2e/clock.spec.ts create mode 100644 tests/e2e/notepad.spec.ts create mode 100644 tests/e2e/shell-foundation.spec.ts create mode 100644 tests/unit/calculator-model.test.ts create mode 100644 tests/unit/clock-model.test.ts create mode 100644 tests/unit/context-menu-model.test.ts create mode 100644 tests/unit/notepad-model.test.ts diff --git a/docs/SESSION_RESULTS.md b/docs/SESSION_RESULTS.md index 58de7ad..3c8c482 100644 --- a/docs/SESSION_RESULTS.md +++ b/docs/SESSION_RESULTS.md @@ -680,3 +680,614 @@ Existing M1 unit, integration, and Playwright tests remain unchanged and pass as No virtual filesystem, file manager, text editor, terminal, process/task simulation, notifications, settings, persistence, accounts, networking, scenarios, backend, real machine access, dynamic application installation, multi-instance policy, global window-cycling shortcut, or keyboard move/resize behavior was introduced. No release, version tag, GitHub Release, PR, merge, or branch change was created. + +--- + +# Milestone 3 Architecture Planning Session + +- **Date:** 2026-09-27 +- **Branch:** `feature/m3-applications-os-experience` +- **Starting `develop` commit:** `0135404d61219ac1e3071123179d45911c04e44a` +- **Authoritative roadmap ref:** `origin/documentation` at `a719f3fe598ea523cdb783059677a026173f6c84` +- **Task type:** Architecture review and implementation planning only +- **Implementation status:** Not started + +## Planning Context and Scope + +The post-M2 roadmap was intentionally revised before this planning session. The authoritative documentation now defines M3 as **Applications + OS Experience**, moves the shared Virtual Filesystem to M4, and leaves M5 as Scenario Foundation. Earlier entries in this file preserve the former filesystem-first M3 plan as historical context; this entry supersedes that prospective plan without rewriting it. + +M3 is limited to: + +- a temporary in-memory Notepad; +- a basic Calculator; +- a small digital Clock; +- the existing System Diagnostics application; +- a registry-backed, keyboard-accessible Application Drawer; +- the existing task strip as a projection of open windows only; +- a SHADOW OS desktop context menu; and +- a projection-only Refresh Desktop command that does not reload or reboot the application. + +M3 explicitly excludes the Virtual Filesystem, File Manager, file saving/loading, persistent application data, Browser, Email, Image Viewer, Settings application, themes, Calendar, Tasks, Terminal, networking, accounts, backend/cloud persistence, and scenario runtime/gameplay. M4 owns the shared Virtual Filesystem and coherent filesystem-backed sandbox. + +## Documentation and Implementation Reviewed + +Documentation reviewed: + +- `README.md` +- `CHANGELOG.md` +- `docs/AFTERBOOT_PROJECT.md` +- `docs/SESSION_RESULTS.md` +- canonical `docs/AFTERBOOT_MILESTONES.md` from `origin/documentation` +- the post-M2 roadmap revisions on `origin/documentation` + +Implementation and tests reviewed: + +- composition in `src/bootstrap/start-afterboot.ts`; +- runtime/reset behavior in `src/core/runtime/shadow-runtime.ts`; +- typed events, disposables, identifiers, and the clock boundary; +- application contracts, registry, and manager; +- `WindowManager` and `WindowLayerView`; +- `ShellView`, `DesktopView`, launcher, task strip, system clock, and responsive styles; +- the existing System Diagnostics application; and +- M0-M2 unit, integration, and Playwright coverage. + +## Existing Architecture Assessment + +The M2 architecture is sufficient for M3 without a framework rewrite or a second catalog: + +- `ApplicationRegistry` already owns the immutable startup catalog and exposes ordered manifests through `list()`. +- `ApplicationManager` already owns single-instance launch, focus/restore-on-relaunch, application instances, primary and auxiliary windows, reset, and disposal. +- `WindowManager` remains the only authority for window geometry, modes, z-order, focus, and work-area constraints. +- `WindowLayerView` already mounts application views by stable window identity and translates DOM interaction into manager commands. +- `DesktopView` is the correct owner for shell composition, task-strip projection, transient launcher/context-menu presentation, and focus handoff. +- `ShadowRuntime` should remain limited to boot/reset/failure lifecycle and should not absorb M3 overlay or application state. +- The existing `Clock` and `formatSystemTime` boundaries are deterministic and reusable by the Clock application. +- Reset and failure already dispose applications and windows through the composition root; M3 additions must join those existing disposal paths. + +The current `ApplicationContext` is intentionally narrow and remains sufficient. M3 does not justify exposing the runtime, registry, managers, clock, or broad system services to every application. The Clock definition can receive the existing `Clock` explicitly from the composition root through its factory. + +Application definitions must remain construction-only: `create()` returns an instance and must not call `context.openWindow()` synchronously before the manager has registered that instance. M3 applications require only a primary window, so no manager contract change is needed for this ordering constraint. + +## A. Application Architecture + +- Register Notepad, Calculator, Clock, and the existing System Diagnostics definition together at startup in the composition root. +- Continue using registry manifests as the sole installed-application metadata source. The current ID, name, description, and window metadata are enough for M3; icon, grouping, search, sort-key, and launch-policy fields are not required. +- Preserve registration order as deterministic drawer order unless later usability evidence requires explicit sorting metadata. +- Continue routing all launches through `ApplicationManager.launch()`. Relaunching an existing M3 application restores or focuses its primary window and does not create another instance. +- Keep each application's mutable state inside its application instance/model, not in the DOM, shell, registry, or application manager. +- Keep application views on the existing `mount(host, document): Disposable` contract. +- Closing a primary window, runtime reset/failure, and application disposal release application-local resources exactly once. Reopening after close creates a fresh instance. +- Do not add multi-instance launch policies during M3; no planned M3 application requires one. + +## B. Application Drawer + +`ApplicationRegistry` owns discovery, and `ApplicationManager` owns launch. A new domain-level `AppLauncher` service would duplicate those authorities and is not justified. + +The drawer should be a disposable shell view/controller owned by `DesktopView`: + +1. Read immutable manifests from `ApplicationRegistry.list()`. +2. Render one entry per registered application, including System Diagnostics. +3. Dispatch the selected application ID to `ApplicationManager.launch()`. +4. Close after a successful launch and allow the existing window layer to focus the launched or restored window. + +The bottom bar should expose one clearly labeled drawer trigger rather than one permanent button per installed application. The trigger uses `aria-expanded`, `aria-controls`, and an appropriate popup relationship. Opening by pointer or keyboard moves focus to the first available application. Arrow keys move among entries; Home and End move to the bounds; Enter or Space launches; Escape closes and restores focus to the trigger. Pointer interaction outside the drawer dismisses it and restores focus when appropriate. + +The drawer remains viewport-contained and scrollable. It may appear as an anchored panel on desktop and a constrained sheet/panel on small screens, but both layouts use the same catalog and launch commands. Reduced-motion mode must not depend on an animated transition to make the drawer usable. + +## C. Task Strip and Bottom Bar + +M3 should refine, not replace, the current footer composition: + +- the application area becomes one App Drawer trigger; +- the task strip continues to show open windows only and continues to focus or restore them; +- the status area retains the existing clock and restart control; and +- responsive layouts may rearrange these zones without changing their ownership or data sources. + +The task strip must not become an installed-application catalog and must not duplicate drawer entries. Existing focus recovery after window minimize/close remains part of the contract, with the drawer trigger replacing the first permanent application button as the shell fallback target. + +## D. Context Menu + +The initial context menu is transient shell presentation state owned by `DesktopView`, not a new OS domain service. Its model should use typed surface and action identifiers plus immutable item data; DOM elements and executable callbacks do not belong in the menu model. + +The first registered surface is the desktop workspace/background. The browser's native `contextmenu` is suppressed only when a SHADOW OS surface has explicitly claimed that interaction. Window/application content and editable controls, especially the Notepad editing surface, are not suppressed by the desktop provider. Future window, application, and file providers can supply their own typed item definitions without changing the initial action-dispatch path. + +The initial desktop menu contains only: + +- **Refresh Desktop**; and +- **Open App Drawer**. + +No Settings placeholder is needed because M3 has no settings capability. + +Menu behavior requirements: + +- pointer invocation anchors at the pointer location; +- keyboard invocation through the Context Menu key or Shift+F10 anchors to the focused desktop surface; +- placement clamps to the visible workspace/viewport and handles all edges; +- focus moves to the first enabled item; +- Arrow Up/Down and Home/End navigate enabled items; +- Enter or Space invokes the focused item; +- Escape, outside pointer interaction, a second invocation, or successful action dismisses the menu; +- dismissal restores focus to the invoker when it remains available; and +- disposal removes document-level listeners and any active menu DOM. + +The initial implementation may use a focused context-menu view/controller plus typed desktop definitions. A global provider registry or context-menu service should be deferred until a second context-specific consumer proves that abstraction necessary. + +## E. Refresh Desktop + +Refresh Desktop is a shell command, not a runtime reset. It must: + +- close transient drawer/context-menu overlays; +- re-read the immutable registry and current application/window snapshots; +- reconcile launcher, task-strip, window-layer, clock, and work-area presentation from those authoritative sources; and +- preserve running application instances, application-local state, open windows, window modes, geometry, z-order, and the current runtime boot cycle. + +It must not call `location.reload()`, navigate, invoke `ShadowRuntime.reset()`, recreate the composition root, dispose applications, close windows, or mutate unrelated OS state. The smallest implementation is an explicit `DesktopView` refresh command that invokes existing projection/reconciliation methods. No new persistent desktop model or event is required because refresh does not change domain state. + +## F. Notepad + +- Create one instance-local text model whose value is independent from its rendered control. +- Use a native multiline text control for editing, selection, copy, paste, undo, and standard keyboard behavior rather than reimplementing browser text editing. +- Synchronize input into the instance model so a shell projection refresh or view remount does not lose text while the application instance remains alive. +- Start each new instance blank. +- Preserve text while the same single instance is minimized, restored, focused again, or retained through Refresh Desktop. +- Discard text when the primary window closes, the application is disposed, or SHADOW OS resets/fails. +- Do not expose save/open commands, filenames, fake paths, storage adapters, local storage, IndexedDB, import/export, or any placeholder filesystem API. + +## G. Calculator + +Use a small pure deterministic state machine rather than evaluating strings with `eval()` or introducing a parser/library. + +The locked M3 operation set is addition, subtraction, multiplication, and division with integer and decimal input. The model tracks the current entry, accumulator, pending operator, entry-replacement state, and an error state. Operations evaluate in immediate pocket-calculator order; expression precedence, history, memory registers, percentages, scientific operations, and programmable expressions are out of scope. + +Required controls are digits, decimal point, the four operators, equals, clear, and backspace. Keyboard input maps to the same commands; Enter invokes equals, Escape clears, and Backspace removes the current entry. Division by zero and non-finite results enter a visible `Error` state. Clear or the next numeric entry recovers deterministically. Display formatting and maximum practical input length should be finalized during implementation without changing this operation model. + +## H. Clock + +- Inject the existing `Clock` into the Clock application definition factory from the composition root; do not call `Date.now()` directly and do not add a second clock source. +- Reuse `formatSystemTime` for browser-local date/time presentation unless a separate pure formatter is proven necessary. +- Render a small digital time/date view and schedule one update at a time through `Clock.schedule()`. +- Cancel the pending scheduled update when the view unmounts or the application instance is disposed. +- Use the existing fake clock strategy for deterministic tests. +- Do not broaden `ApplicationContext` solely for Clock. Reconsider a read-only time capability only when another application needs application-context clock access. + +The current clock abstraction requires no architectural change for M3. + +## I. Accessibility, Focus, and Responsive Behavior + +- Preserve semantic headings, labels, native buttons, visible focus, and logical source/tab order. +- The App Drawer and context menu must be completely operable without a pointer and must restore focus on dismissal. +- The context menu uses menu/menuitem semantics; the drawer uses a labeled panel/dialog or navigation region with ordinary application buttons rather than falsely presenting application launch as a command menu. +- The desktop surface must provide a discoverable focus target for keyboard context-menu invocation. +- Notepad retains native text-selection and clipboard shortcuts and must have an accessible label. +- Calculator controls need unambiguous accessible names, a readable result/status, and no color-only error state. +- Clock uses semantic time output and must not announce every one-second update through an intrusive live region. +- Existing window focus behavior and task-strip restore behavior remain intact when drawer entries replace permanent launcher buttons. +- Desktop and current small-screen active-window layouts must contain drawer, menus, and application content without horizontal overflow or inaccessible controls. +- New transitions must honor the existing reduced-motion setting; no essential state change may depend on animation. + +## J. Testing Strategy + +### Domain and Unit Tests + +- Notepad model: initial blank value, text replacement/edit synchronization, retention while the instance lives, and fresh state after a new instance. +- Calculator model: each operation, decimals, chained immediate operations, operator replacement, equals, clear, backspace, division by zero, non-finite/error recovery, and immutable/read-only snapshots if snapshots are exposed. +- Clock: initial formatting, scheduled updates, one active scheduled callback, and cancellation on disposal using a fake clock. +- Any extracted drawer/context-menu reducer: deterministic open, navigation, selection, dismissal, and edge-position calculations independent from DOM nodes. + +### Service Integration Tests + +- Registry lists all four definitions exactly once in deterministic order. +- Application Manager launches each M3 application through the existing contract. +- Relaunch restores/focuses the existing primary window and does not create a second instance. +- Closing and reset dispose application models/timers and leave no windows or running instances. +- Refresh Desktop preserves application/window snapshots and application-local Notepad state. +- Context-menu actions dispatch only approved shell commands and do not invoke runtime reset or navigation. + +### View and Browser Tests + +The repository has no DOM component-test environment and M3 does not justify adding one solely for these views. Keep models and positioning logic unit-testable, service workflows in Vitest, and semantic DOM/focus interaction in Playwright. + +Playwright should verify: + +- pointer and keyboard drawer open, navigation, launch, dismissal, and focus restoration; +- deterministic catalog contents including System Diagnostics; +- task strip contains only running windows; +- Notepad typing, selection/clipboard-compatible behavior, relaunch retention, close/reopen discard, and reset cleanup; +- Calculator pointer and keyboard arithmetic, clear/backspace, decimal, and division-by-zero recovery; +- Clock date/time rendering and cleanup behavior without direct wall-clock flakiness; +- desktop pointer and keyboard context-menu invocation, edge clamping, menu navigation, outside/Escape dismissal, and focus restoration; +- native context-menu suppression on owned desktop surfaces but not on editable Notepad content; +- Refresh Desktop causes no navigation/reload, boot-cycle change, app disposal, window loss, or Notepad text loss; +- existing System Diagnostics, window interactions, restart, focus recovery, and M0-M2 workflows remain operational; +- desktop and current 360 x 740 small-screen behavior have no horizontal overflow or blocked critical controls; and +- no unexpected console errors, page errors, failed requests, or external runtime dependencies occur. + +All checks should prefer roles, accessible names, stable domain markers, injected time, and observable manager results over arbitrary delays or implementation-specific selectors. + +## Locked Architectural Decisions + +1. **Use the M2 application framework unchanged for M3 application ownership.** + +- **Reason:** Registry discovery, single-instance launch, primary-window ownership, reset, and disposal already satisfy M3. +- **Alternative considered:** A new application runtime or launcher service. +- **Consequence:** All M3 apps register at startup and launch only through `ApplicationManager`. + +2. **Keep the registry as the only installed-application catalog.** + +- **Reason:** A second drawer catalog would introduce conflicting truth. +- **Alternative considered:** Drawer-owned application configuration. +- **Consequence:** Drawer order and metadata come directly from immutable manifests. + +3. **Keep drawer and context-menu state in disposable shell views.** + +- **Reason:** Open/position/focus state is transient presentation state, not OS domain state. +- **Alternative considered:** New global services or runtime state. +- **Consequence:** `DesktopView` owns and disposes both overlays; domain managers remain unchanged. + +4. **Keep the task strip limited to open windows.** + +- **Reason:** Installed applications and running windows are different concepts with existing owners. +- **Alternative considered:** Keep permanent application launch buttons mixed with running-window controls. +- **Consequence:** One drawer trigger replaces permanent per-application launcher buttons. + +5. **Define Refresh Desktop as projection reconciliation only.** + +- **Reason:** A refresh should correct/rebuild presentation from authoritative state without becoming restart. +- **Alternatives considered:** Browser reload, runtime reset, or composition-root reconstruction. +- **Consequence:** Apps, windows, local app state, geometry, and boot cycle survive refresh. + +6. **Keep Notepad text instance-local and ephemeral.** + +- **Reason:** M3 needs useful editing but M4 owns shared storage. +- **Alternative considered:** Local storage or a temporary filesystem. +- **Consequence:** Text survives view reconciliation while the instance lives and is discarded on close/reset. + +7. **Use an explicit calculator state machine with four arithmetic operations.** + +- **Reason:** It is deterministic, testable, and avoids unsafe evaluation or unnecessary parsing. +- **Alternatives considered:** Evaluate expression strings or add a general expression parser. +- **Consequence:** History, precedence parsing, memory, percentage, and scientific behavior remain excluded. + +8. **Inject the existing Clock into the Clock definition factory.** + +- **Reason:** This reuses deterministic time without broadening every application's context. +- **Alternative considered:** Direct browser time or adding Clock to `ApplicationContext`. +- **Consequence:** The composition root wires Clock explicitly and disposal cancels scheduled ticks. + +9. **Claim native context-menu behavior only for registered SHADOW OS surfaces.** + +- **Reason:** Application/editable content may need native browser behavior until it has its own provider. +- **Alternatives considered:** Suppress the native menu across the entire shell or introduce a global provider service before a second provider exists. +- **Consequence:** M3 begins with the desktop background and leaves future typed providers incremental. + +10. **Add no new external dependency or DOM test environment for M3.** + +- **Reason:** Existing TypeScript, browser APIs, Vitest service tests, and Playwright cover the planned behavior. +- **Alternative considered:** Add a browser-like DOM unit-test dependency solely for M3 views. +- **Consequence:** Pure logic stays DOM-independent and browser semantics are verified end to end. + +## Open Questions + +- What exact visual composition gives the App Drawer a distinct SHADOW OS identity while preserving the behavioral contract above? +- What practical Calculator input-length and floating-point display policy avoids misleading output without expanding into arbitrary precision? +- Should a second context-specific consumer in M3 appear, or should the generalized provider registry wait until M4 file contexts exist? +- Which formal browser and assistive-technology matrix will gate M3 beyond the current Chromium baseline and manual keyboard review? + +These questions may be resolved during implementation without changing subsystem ownership or the M3/M4 boundary. + +## Deferred Decisions + +- Virtual Filesystem contracts, paths, metadata, events, seed data, and storage adapters. +- File Manager and Notepad save/open workflows. +- Browser persistence, import/export, and shared application data. +- Image Viewer and file associations. +- Settings application, themes, Calendar, Tasks, Terminal, Browser, Email, networking, accounts, and backend services. +- Process/task-service semantics. +- Scenario packages, setup/reset, objectives, progression, and gameplay. +- Multi-instance launch policies and dynamic application installation. +- Global context-provider registration until more than one concrete provider exists. + +## Future Ideas + +- Drawer search, grouping, favorites, and optional manifest icon metadata after the base catalog proves a need. +- A command palette sharing typed action IDs with context menus. +- Application/window grouping in the task strip. +- Capability-filtered context providers for windows, applications, and M4 file surfaces. + +None of these ideas is an M3 requirement. + +## Proposed M3 Definition of Done + +### Applications + +- Notepad, Calculator, Clock, and System Diagnostics are registered once in the startup registry and launch through `ApplicationManager`. +- Repeated launch restores/focuses the existing single instance. +- Notepad provides labeled native multiline editing with temporary instance-local text, retains it while that instance lives, and discards it on close/reset without any save, load, path, storage, or persistence API. +- Calculator provides deterministic pointer and keyboard use for addition, subtraction, multiplication, division, decimals, equals, clear, and backspace, including recoverable division-by-zero/non-finite errors. +- Clock presents local digital date/time from the injected existing `Clock`, updates predictably, and cancels scheduled work on close/reset/disposal. +- System Diagnostics remains launchable and functionally unchanged except for normal drawer integration. + +### Shell and Interaction + +- One keyboard-accessible App Drawer trigger replaces permanent per-application bottom-bar entries. +- The drawer lists registry manifests in deterministic order and launches only through `ApplicationManager`. +- The task strip lists only open windows and preserves focus/restore behavior. +- Desktop pointer and keyboard invocation opens a viewport-clamped SHADOW OS context menu with Refresh Desktop and Open App Drawer. +- Native context-menu suppression is limited to the registered desktop surface; editable Notepad behavior remains native. +- Escape, outside interaction, launch/action completion, and disposal dismiss overlays with deterministic focus restoration. +- Refresh Desktop causes no browser navigation, runtime reset, boot-cycle change, application disposal, window loss, geometry reset, or Notepad text loss. + +### Quality and Lifecycle + +- Drawer, context menu, all applications, and critical shell paths are accessible by keyboard with semantic labels, visible focus, and reduced-motion-safe behavior. +- Desktop and the current supported small-screen presentation remain coherent without horizontal overflow or blocked critical controls. +- Closing applications, restart/reset, runtime failure, and top-level disposal leave no stale instances, windows, overlays, event listeners, or scheduled clock work. +- Focus recovery remains predictable after overlay dismissal, application launch, window minimize/close, and reset. +- Focused unit and integration tests cover application models, registry/manager workflows, refresh invariants, commands, and disposal. +- Playwright covers the critical pointer, keyboard, responsive, lifecycle, focus, context-menu, drawer, and application workflows with no console/page/network failures. +- Prettier, strict TypeScript, ESLint, all Vitest tests, production build, and all Playwright tests pass. +- Manual desktop, current small-screen, keyboard-only, focus, and reduced-motion review passes. +- A final scope audit confirms no Virtual Filesystem, file workflow, persistent data, deferred application/service, backend, or scenario behavior entered M3. + +## Recommended Implementation Order + +1. Add pure Notepad and Calculator models with focused unit tests. +2. Add the three application definitions/views and inject the existing Clock through composition. +3. Replace permanent application buttons with the registry-backed App Drawer while preserving task-strip behavior. +4. Add the typed desktop context-menu model/view and shell command dispatch. +5. Add projection-only Refresh Desktop and lock its state-preservation tests. +6. Complete responsive/accessibility styling and Playwright workflows incrementally. +7. Run all quality gates, manual verification, and strict M3/M4 scope review before declaring implementation ready. + +## Planning Outcome + +The existing M2 ownership model is sufficient for M3. No new global state store, application catalog, launcher service, context-menu domain service, clock source, persistence mechanism, filesystem substitute, or external dependency is justified. M3 implementation should extend the composition root with three definitions, add instance-local application models/views, and add disposable shell projections for the drawer and desktop context menu. + +No M3 source code, tests, styles, package files, workflows, configuration, application implementations, release, tag, PR, merge, or deployment was created during this planning session. + +--- + +# M3 Phase 1 — Shell Foundation Implementation + Visual Refinement + +- **Date:** 2026-09-28 +- **Branch:** `feature/m3-applications-os-experience` +- **Implementation commit:** `ad088e41dd6c99faf5ae764036b5167271e0e219` +- **Visual refinement commit:** `41113dd9a618c1eeddb025621c7ffb894b411ce9` +- **Checkpoint status:** M3 Phase 1 implemented and manually verified; Milestone 3 remains in progress + +## Scope Implemented + +- Added a registry-backed floating Application Drawer/Launcher. +- Kept the task strip limited to running windows. +- Added a scoped SHADOW OS desktop context menu. +- Added projection-only Refresh Desktop behavior. +- Preserved accessible keyboard interaction, focus recovery, and overlay dismissal. +- Added responsive launcher and context-menu behavior. +- Refined the launcher into a compact floating SHADOW OS surface. +- Refined the context menu into a minimal two-action command surface. + +## Architecture + +- `ApplicationRegistry` remains the sole installed-application catalog. +- `ApplicationManager` remains responsible for application launch and lifecycle. +- `WindowManager` remains responsible for windows, focus, geometry, and z-order. +- The drawer and context menu remain disposable shell views/overlays owned by `DesktopView`. +- The task strip represents running windows rather than installed applications. +- Context-menu interception remains scoped to registered desktop surfaces; application content retains native browser context-menu behavior. +- Refresh Desktop performs projection/reconciliation only. It does not reload the page, reset the runtime, or mutate application/window manager state. +- No new global service, dependency, persistence mechanism, filesystem behavior, or application architecture was introduced. + +## Visual Refinement + +Manual review of the initial Phase 1 presentation led to a focused visual pass: + +- The App Drawer became a compact floating launcher above the task strip. +- Its single-application state was deliberately composed as a bounded application tile rather than an empty large panel. +- The context menu became a compact two-action SHADOW OS command surface containing Refresh Desktop and Applications. +- The refinement was CSS-led, with typed presentation symbols rendered separately from accessible action names. +- Existing behavior, ownership boundaries, and application/window architecture were preserved. + +## Verification + +- Prettier: PASS +- Strict TypeScript: PASS +- ESLint: PASS +- Vitest: 38 tests PASS across 9 files +- Production build: PASS +- Playwright Chromium: 16 tests PASS + +Manual viewport inspection passed at 1440px, 1024px, 768px, and 360 × 740. The launcher and context menu remained contained without clipping or horizontal page overflow. Launcher opening and launching, context-menu edge clamping, keyboard/focus behavior, and the existing window interactions remained functional. Refresh Desktop did not reload the browser or disturb open application/window state. Right-click inside application content retained the native browser context menu, and restart returned SHADOW OS to a clean desktop. + +Reduced-motion behavior passed the existing automated Playwright coverage. Manual reduced-motion verification was not performed for this checkpoint. + +## Remaining M3 Work + +Milestone 3 is not complete. Remaining work includes: + +- Notepad. +- Calculator. +- Clock. +- Broader M3 integration. +- Final accessibility and manual acceptance. +- Final M3 quality-gate audit. +- M3 documentation and milestone closure. + +## Commit References + +- `ad088e41dd6c99faf5ae764036b5167271e0e219` — `feat: add M3 application launcher and context menu` +- `41113dd9a618c1eeddb025621c7ffb894b411ce9` — `style: refine M3 launcher and context menu` + +## Scope Review + +This checkpoint introduced no Notepad, Calculator, Clock, Settings, virtual filesystem, persistence, scenarios, networking, backend, account, release, or version changes. It records the timeline from M3 planning through Phase 1 implementation and visual refinement while leaving the remaining M3 application work explicit. + +--- + +# M3 Phase 2A — Notepad Implementation + +- **Date:** 2026-09-28 +- **Branch:** `feature/m3-applications-os-experience` +- **Checkpoint status:** Notepad implemented and manually verified; Milestone 3 remains in progress + +## Scope Implemented + +- Added Notepad as a startup-registered application discovered through the existing App Drawer. +- Added a pure instance-local text model with blank initial state and explicit disposal cleanup. +- Added a native multiline textarea with browser-provided editing, selection, cursor movement, clipboard, and undo/redo behavior. +- Added a restrained SHADOW OS editor surface with visible focus and responsive sizing. +- Preserved text while the single running instance is focused, moved, resized, minimized, restored, maximized, or reconciled through Refresh Desktop. +- Discarded text when Notepad closes or SHADOW OS restarts; reopening creates a fresh blank instance. + +## Architecture + +- `ApplicationRegistry` remains the sole application catalog, and `ApplicationManager` remains the launch/lifecycle authority. +- Notepad uses the existing `ApplicationView.mount(host, document)` contract and the existing single-instance application policy. +- `WindowManager` remains the sole owner of Notepad window geometry, mode, focus, and z-order. +- Mutable text is owned only by the running Notepad instance and is synchronized from the native editor into its model. +- No framework contract, application context, global service, dependency, filesystem abstraction, or persistence mechanism was added. + +## Tests Added + +- Unit tests cover blank initial state, multiline edits, replacement, and disposal cleanup. +- Service integration covers registration, manager-backed launch, single-instance relaunch, close/reopen identity, and reset cleanup. +- Playwright covers drawer discovery, launch, initial focus, multiline editing and selection, Escape behavior, task-strip projection, single-instance relaunch, move/resize, minimize/restore, maximize/restore, Refresh Desktop retention, native editor context menus, close/fresh reopen, restart cleanup, and mobile containment. + +## Verification + +- Prettier: PASS +- Strict TypeScript: PASS +- ESLint: PASS +- Vitest: 41 tests PASS across 10 files +- Production build: PASS +- Playwright Chromium: 18 tests PASS + +Manual verification passed at 1280px desktop and 360 × 740 mobile. The App Drawer listed both System Diagnostics and Notepad. Typing, multiline text, selection, native editing, keyboard focus, move/resize, minimize/restore, maximize/restore, Refresh Desktop, close/reopen, restart, task-strip behavior, and responsive active-window presentation worked without clipping or horizontal overflow. Right-click inside the editor retained the native browser context menu. Existing M3 Phase 1 and System Diagnostics workflows remained functional. + +Reduced-motion behavior remained covered by the existing automated Playwright workflow; manual reduced-motion verification was not performed for this checkpoint. + +## M3/M4 Leakage Audit + +Notepad introduces no Save, Save As, Open, file picker, file path, file/folder model, virtual filesystem, local or browser storage, cookies, URL state, backend call, shared file state, or other persistence behavior. Text exists only for the running application instance. + +## Remaining M3 Work + +Milestone 3 is not complete. Calculator and Clock remain unimplemented. Broader M3 integration, final accessibility/manual acceptance, the final M3 quality-gate audit, and M3 documentation/milestone closure also remain outstanding. + +--- + +# M3 Phase 2B — Calculator Implementation + +- **Date:** 2026-09-28 +- **Branch:** `feature/m3-applications-os-experience` +- **Checkpoint status:** Calculator implemented and manually verified; Milestone 3 remains in progress + +## Scope Implemented + +- Added Calculator as a startup-registered application discovered through the existing App Drawer. +- Added a compact four-operation SHADOW OS interface with semantic digit, decimal, operator, clear, backspace, and equals buttons. +- Added direct keyboard input for digits, decimal, `+`, `-`, `*`, `/`, `Enter`, `=`, `Escape`, `C`, `Backspace`, and `Delete` while preserving native Tab navigation. +- Added accessible button names, a live labeled display, visible keyboard focus, and a concise visible `ERROR` state. +- Preserved state while the single running instance is focused, moved, resized, minimized, restored, maximized, or reconciled through Refresh Desktop. +- Discarded calculations when Calculator closes or SHADOW OS restarts; reopening creates a fresh instance displaying zero. + +## Architecture + +- `ApplicationRegistry` remains the sole application catalog, and `ApplicationManager` remains the launch/lifecycle authority. +- Calculator uses the existing `ApplicationView.mount(host, document)` contract and single-instance application policy. +- `WindowManager` remains the sole owner of Calculator window geometry, mode, focus, and z-order. +- Arithmetic state is owned by a pure DOM-independent `CalculatorModel` created for each running application instance. +- The existing Clock abstraction, framework contracts, application context, global services, shell projections, and dependency graph remain unchanged. + +## State-Machine Decisions + +- Operations execute immediately from left to right, matching a conventional pocket calculator rather than expression precedence. For example, `12 + 5 × 2` produces `34`. +- Choosing another operator before entering the right operand replaces the pending operator. +- Repeated equals reapplies the last completed operator and right operand. +- Division by zero and non-finite arithmetic enter `ERROR`; Clear or a new numeric entry recovers deterministically. +- Direct entry is limited to 12 characters. Results are normalized to 12 significant digits and use compact scientific notation when needed to stay within a 16-character display budget. +- No evaluated expression string, parser, calculation history, memory, percentage, or scientific operation was introduced. + +## Tests Added + +- Sixteen pure-model tests cover initial state, digit and multi-digit entry, decimals, all four operations, immediate chained evaluation, equals, clear, backspace, negative results, division by zero, operator replacement, repeated equals, malformed decimal prevention, bounded large-number formatting, recovery, and disposal. +- Service integration covers Calculator registration, manager-backed launch, window title, single-instance relaunch, close/fresh reopen identity, and reset cleanup. +- Playwright covers drawer discovery, launch, initial focus, task-strip projection, pointer addition/subtraction/multiplication/division, decimal arithmetic, clear, backspace, visible error and recovery, keyboard input, Escape handling, single-instance restore, close/fresh reopen, restart cleanup, and mobile containment. + +## Verification + +- Prettier: PASS +- Strict TypeScript: PASS +- ESLint: PASS +- Vitest: 58 tests PASS across 11 files +- Production build: PASS +- Playwright Chromium: 20 tests PASS + +Manual verification passed at 1280 × 800 desktop and 360 × 740 mobile. App Drawer launch, pointer and keyboard arithmetic, decimals, division by zero, clear, backspace, initial focus, task-strip behavior, move/resize, minimize/restore, maximize/restore, existing-instance focus, Refresh Desktop retention, close/fresh reopen, restart cleanup, and responsive containment worked without clipping or horizontal overflow. Existing Notes editing, System Diagnostics, the desktop context menu, and Refresh Desktop remained functional with no console errors, page errors, or failed requests. + +Reduced-motion behavior remains covered by the existing automated Playwright workflow; manual reduced-motion verification was not performed for this checkpoint. + +## M3/M4 Leakage Audit + +Calculator introduces no filesystem or file model, persistence, `localStorage`, IndexedDB, cookies, backend or network call, shared file state, new global service, external dependency, advanced expression parser, history, memory, Settings, Browser, Clock implementation, or M4 process behavior. Calculator state exists only for the running application instance. + +## Remaining M3 Work + +Milestone 3 is not complete. Clock remains unimplemented. Broader M3 integration, final accessibility/manual acceptance, the final M3 quality-gate audit, and M3 documentation/milestone closure also remain outstanding. + +--- + +# M3 Phase 2C — Clock Implementation + +- **Date:** 2026-09-28 +- **Branch:** `feature/m3-applications-os-experience` +- **Checkpoint status:** Clock implemented and manually verified; Milestone 3 remains in progress + +## Scope Implemented + +- Added Clock as a startup-registered application discovered through the existing App Drawer. +- Added a compact SHADOW OS digital clock view with dominant 24-hour time including seconds and a secondary local date. +- Added semantic time/date elements with explicit accessible names and machine-readable values. +- Preserved the live display while the single running instance is focused, moved, resized, minimized, restored, maximized, or reconciled through Refresh Desktop. +- Stopped application-owned updates on close/reset and created one fresh update lifecycle when Clock reopened. + +## Existing Clock Integration + +- The composition root injects the existing M1 `Clock` into `createClockDefinition(clock)`; `ApplicationContext` and global runtime contracts remain unchanged. +- An instance-local `ClockModel` reads only `Clock.now()`, schedules only through `Clock.schedule()`, and reuses the existing pure `formatSystemTime` presentation convention. +- Clock uses the existing `ApplicationView.mount(host, document)` contract, registry catalog, manager single-instance policy, and WindowManager geometry/focus lifecycle. +- The application contains no direct `Date.now()`, `new Date()`, browser timer source, or second clock service. + +## Update and Disposal Behavior + +- The model aligns each update to the next whole-second boundary and keeps at most one scheduled callback while subscribed. +- Multiple subscribers share that single scheduled callback. +- Final unsubscribe and instance disposal both cancel the pending callback idempotently. +- Closing Clock returns browser timer activity to its pre-launch baseline; relaunch adds exactly one fresh Clock timer rather than accumulating callbacks. +- Restart/reset disposes the running instance and leaves no Clock window, task entry, subscription, or scheduled application update. + +## Tests Added + +- Six deterministic model tests cover fixed injected formatting, second-boundary alignment, repeated ticking, local midnight rollover, one-task sharing, final-unsubscribe cancellation, disposal, rejected post-disposal subscriptions, and reopen without timer accumulation. +- Service integration covers Clock registration, manager-backed launch, window title, single-instance relaunch, close/fresh reopen identity, and reset cleanup. +- Playwright covers drawer discovery, launch, accessible time/date values, live updates without fixed wall-clock assumptions, task-strip projection, single-instance relaunch, minimize/restore, close/reopen, browser timer-count cleanup, restart disposal, mobile active-window containment, and horizontal-overflow prevention. + +## Verification + +- Prettier: PASS +- Strict TypeScript: PASS +- ESLint: PASS +- Vitest: 71 tests PASS across 12 files +- Production build: PASS +- Playwright Chromium: 23 tests PASS + +Manual verification passed at 1280 × 800, 1024 × 768, 768 × 720, and 360 × 740. App Drawer launch, synchronized application/system time, local date, visible ticking, initial focus, task-strip behavior, move/resize, minimize/restore, maximize/restore, existing-instance focus, Refresh Desktop retention, close/fresh reopen, restart cleanup, and responsive containment worked without clipping or horizontal overflow. Existing Notes editing, Calculator pointer/keyboard arithmetic, System Diagnostics, the desktop context menu, Refresh Desktop, and window controls remained functional with no observed browser errors. + +Reduced-motion behavior remains covered by the existing automated Playwright workflow; manual reduced-motion verification was not performed for this checkpoint. + +## M3/M4 Leakage Audit + +Clock introduces no filesystem or file model, persistence, `localStorage`, IndexedDB, cookies, backend or network call, shared state service, global ticking service, external dependency, Calendar behavior, timezone configuration, user setting, alarm, timer, stopwatch, world clock, weather, or M4 process behavior. Its only time source is the existing injected OS `Clock`. + +## Remaining M3 Work + +Milestone 3 is not complete. Broader M3 integration, final accessibility/manual acceptance, the final M3 quality-gate audit, and M3 documentation/milestone closure remain outstanding. No final integration or closure work was started in this phase. diff --git a/src/applications/built-in/calculator-model.ts b/src/applications/built-in/calculator-model.ts new file mode 100644 index 0000000..db69e76 --- /dev/null +++ b/src/applications/built-in/calculator-model.ts @@ -0,0 +1,222 @@ +export type CalculatorOperator = "add" | "subtract" | "multiply" | "divide"; + +export interface CalculatorPendingOperation { + readonly operand: string; + readonly operator: CalculatorOperator; +} + +const ERROR_DISPLAY = "ERROR"; +const MAX_ENTRY_LENGTH = 12; +const MAX_DISPLAY_LENGTH = 16; +const MAX_SIGNIFICANT_DIGITS = 12; + +export class CalculatorModel { + #display = "0"; + #accumulator: number | null = null; + #pendingOperator: CalculatorOperator | null = null; + #replaceDisplay = false; + #lastOperator: CalculatorOperator | null = null; + #lastOperand: number | null = null; + #hasError = false; + + get display(): string { + return this.#display; + } + + get hasError(): boolean { + return this.#hasError; + } + + get pendingOperation(): CalculatorPendingOperation | null { + if (this.#accumulator === null || this.#pendingOperator === null || this.#hasError) { + return null; + } + + return Object.freeze({ + operand: formatResult(this.#accumulator), + operator: this.#pendingOperator, + }); + } + + inputDigit(digit: string): void { + if (!/^\d$/.test(digit)) { + throw new RangeError(`Calculator digit must be between 0 and 9: ${digit}`); + } + + this.#recoverForNumericInput(); + this.#clearRepeatedOperation(); + + if (this.#replaceDisplay || this.#display === "0") { + this.#display = digit; + this.#replaceDisplay = false; + return; + } + + if (this.#display.length < MAX_ENTRY_LENGTH) { + this.#display += digit; + } + } + + inputDecimal(): void { + this.#recoverForNumericInput(); + this.#clearRepeatedOperation(); + + if (this.#replaceDisplay) { + this.#display = "0."; + this.#replaceDisplay = false; + return; + } + + if (!this.#display.includes(".") && this.#display.length < MAX_ENTRY_LENGTH) { + this.#display += "."; + } + } + + chooseOperator(operator: CalculatorOperator): void { + if (this.#hasError) { + return; + } + + const currentValue = Number(this.#display); + + if (this.#pendingOperator !== null && !this.#replaceDisplay) { + const result = this.#calculate(this.#accumulator ?? currentValue, currentValue); + if (result === null) { + return; + } + this.#accumulator = result; + } else if (this.#pendingOperator === null) { + this.#accumulator = currentValue; + } + + this.#pendingOperator = operator; + this.#replaceDisplay = true; + this.#clearRepeatedOperation(); + } + + equals(): void { + if (this.#hasError) { + return; + } + + const currentValue = Number(this.#display); + + if (this.#pendingOperator !== null) { + const operator = this.#pendingOperator; + const result = this.#calculate(this.#accumulator ?? currentValue, currentValue); + if (result === null) { + return; + } + this.#pendingOperator = null; + this.#accumulator = null; + this.#lastOperator = operator; + this.#lastOperand = currentValue; + this.#replaceDisplay = true; + return; + } + + if (this.#lastOperator !== null && this.#lastOperand !== null) { + this.#calculate(currentValue, this.#lastOperand); + this.#replaceDisplay = true; + return; + } + + this.#replaceDisplay = true; + } + + backspace(): void { + if (this.#hasError || this.#replaceDisplay) { + return; + } + + if ( + this.#display.length === 1 || + (this.#display.startsWith("-") && this.#display.length === 2) + ) { + this.#display = "0"; + return; + } + + this.#display = this.#display.slice(0, -1); + } + + clear(): void { + this.#display = "0"; + this.#accumulator = null; + this.#pendingOperator = null; + this.#replaceDisplay = false; + this.#clearRepeatedOperation(); + this.#hasError = false; + } + + dispose(): void { + this.clear(); + } + + #recoverForNumericInput(): void { + if (this.#hasError) { + this.clear(); + } + } + + #clearRepeatedOperation(): void { + this.#lastOperator = null; + this.#lastOperand = null; + } + + #calculate(left: number, right: number): number | null { + let result: number; + + switch (this.#pendingOperator ?? this.#lastOperator) { + case "add": + result = left + right; + break; + case "subtract": + result = left - right; + break; + case "multiply": + result = left * right; + break; + case "divide": + if (right === 0) { + this.#enterError(); + return null; + } + result = left / right; + break; + default: + return null; + } + + if (!Number.isFinite(result)) { + this.#enterError(); + return null; + } + + this.#display = formatResult(result); + return result; + } + + #enterError(): void { + this.#display = ERROR_DISPLAY; + this.#accumulator = null; + this.#pendingOperator = null; + this.#replaceDisplay = true; + this.#clearRepeatedOperation(); + this.#hasError = true; + } +} + +function formatResult(value: number): string { + const normalized = Number.parseFloat(value.toPrecision(MAX_SIGNIFICANT_DIGITS)); + const plain = normalized.toString(); + + if (plain.length <= MAX_DISPLAY_LENGTH) { + return plain; + } + + return normalized + .toExponential(8) + .replace(/\.0+e/, "e") + .replace(/(\.\d*?)0+e/, "$1e"); +} diff --git a/src/applications/built-in/calculator.ts b/src/applications/built-in/calculator.ts new file mode 100644 index 0000000..308a275 --- /dev/null +++ b/src/applications/built-in/calculator.ts @@ -0,0 +1,266 @@ +import { toApplicationId } from "../../core/identity/identifiers"; +import type { ApplicationDefinition, ApplicationView } from "../framework/application"; +import { CalculatorModel, type CalculatorOperator } from "./calculator-model"; + +export const CALCULATOR_APPLICATION_ID = toApplicationId("system.calculator"); + +interface CalculatorKey { + readonly label: string; + readonly name: string; + readonly command: string; + readonly kind: "digit" | "operator" | "utility" | "equals"; + readonly shortcuts?: string; +} + +const CALCULATOR_KEYS: readonly CalculatorKey[] = [ + { label: "C", name: "Clear", command: "clear", kind: "utility", shortcuts: "Escape C" }, + { + label: "DEL", + name: "Backspace", + command: "backspace", + kind: "utility", + shortcuts: "Backspace Delete", + }, + { label: "÷", name: "Divide", command: "operator:divide", kind: "operator", shortcuts: "/" }, + { + label: "×", + name: "Multiply", + command: "operator:multiply", + kind: "operator", + shortcuts: "*", + }, + { label: "7", name: "7", command: "digit:7", kind: "digit" }, + { label: "8", name: "8", command: "digit:8", kind: "digit" }, + { label: "9", name: "9", command: "digit:9", kind: "digit" }, + { + label: "−", + name: "Subtract", + command: "operator:subtract", + kind: "operator", + shortcuts: "-", + }, + { label: "4", name: "4", command: "digit:4", kind: "digit" }, + { label: "5", name: "5", command: "digit:5", kind: "digit" }, + { label: "6", name: "6", command: "digit:6", kind: "digit" }, + { label: "+", name: "Add", command: "operator:add", kind: "operator", shortcuts: "+" }, + { label: "1", name: "1", command: "digit:1", kind: "digit" }, + { label: "2", name: "2", command: "digit:2", kind: "digit" }, + { label: "3", name: "3", command: "digit:3", kind: "digit" }, + { label: "=", name: "Equals", command: "equals", kind: "equals", shortcuts: "Enter =" }, + { label: "0", name: "0", command: "digit:0", kind: "digit" }, + { label: ".", name: "Decimal point", command: "decimal", kind: "digit", shortcuts: "." }, +]; + +const OPERATOR_PRESENTATION: Readonly< + Record +> = { + add: { symbol: "+", name: "plus" }, + subtract: { symbol: "−", name: "minus" }, + multiply: { symbol: "×", name: "times" }, + divide: { symbol: "÷", name: "divided by" }, +}; + +export function createCalculatorDefinition(): ApplicationDefinition { + return { + manifest: { + id: CALCULATOR_APPLICATION_ID, + name: "Calculator", + description: "Perform basic four-operation arithmetic.", + window: { + title: "Calculator", + preferredWidth: 350, + preferredHeight: 480, + constraints: { minWidth: 300, minHeight: 390 }, + }, + }, + create: () => { + const model = new CalculatorModel(); + + return { + primaryView: createCalculatorView(model), + dispose: () => model.dispose(), + }; + }, + }; +} + +function createCalculatorView(model: CalculatorModel): ApplicationView { + return { + mount(host, document): () => void { + const content = document.createElement("section"); + content.className = "calculator-app"; + content.tabIndex = 0; + content.setAttribute("aria-label", "Calculator keyboard input"); + + const displayPanel = document.createElement("div"); + displayPanel.className = "calculator-app__display-panel"; + + const pendingDisplay = document.createElement("output"); + pendingDisplay.className = "calculator-app__pending"; + pendingDisplay.setAttribute("aria-live", "polite"); + pendingDisplay.setAttribute("aria-atomic", "true"); + + const display = document.createElement("output"); + display.className = "calculator-app__display"; + display.setAttribute("aria-label", "Calculator display"); + display.setAttribute("aria-live", "polite"); + display.setAttribute("aria-atomic", "true"); + displayPanel.append(pendingDisplay, display); + + const keypad = document.createElement("div"); + keypad.className = "calculator-app__keypad"; + keypad.setAttribute("aria-label", "Calculator keypad"); + keypad.append(...CALCULATOR_KEYS.map((key) => createKey(document, key))); + const operatorButtons = [ + ...keypad.querySelectorAll(".calculator-app__key--operator"), + ]; + + const render = (): void => { + const state = model.hasError ? "error" : "ready"; + const pendingOperation = model.pendingOperation; + const presentation = pendingOperation + ? OPERATOR_PRESENTATION[pendingOperation.operator] + : null; + const pendingText = + pendingOperation && presentation + ? `${pendingOperation.operand} ${presentation.symbol}` + : ""; + + if (display.textContent !== model.display) { + display.textContent = model.display; + } + display.dataset.state = state; + displayPanel.dataset.state = state; + + if (pendingDisplay.textContent !== pendingText) { + pendingDisplay.textContent = pendingText; + } + if (pendingOperation && presentation) { + pendingDisplay.setAttribute( + "aria-label", + `Pending operation: ${pendingOperation.operand} ${presentation.name}`, + ); + } else { + pendingDisplay.removeAttribute("aria-label"); + } + + for (const button of operatorButtons) { + button.setAttribute( + "aria-pressed", + String(button.dataset.calculatorCommand === `operator:${pendingOperation?.operator}`), + ); + } + }; + const runCommand = (command: string): void => { + applyCommand(model, command); + render(); + }; + const handleClick = (event: MouseEvent): void => { + const target = event.target instanceof Element ? event.target : null; + const button = target?.closest("[data-calculator-command]"); + if (button && keypad.contains(button)) { + runCommand(button.dataset.calculatorCommand ?? ""); + } + }; + const handleKeyDown = (event: KeyboardEvent): void => { + const command = keyboardCommand(event); + if (command === null) { + return; + } + + event.preventDefault(); + event.stopPropagation(); + runCommand(command); + }; + + keypad.addEventListener("click", handleClick); + content.addEventListener("keydown", handleKeyDown); + content.append(displayPanel, keypad); + host.replaceChildren(content); + render(); + content.focus({ preventScroll: true }); + + return () => { + keypad.removeEventListener("click", handleClick); + content.removeEventListener("keydown", handleKeyDown); + host.replaceChildren(); + }; + }, + }; +} + +function createKey(document: Document, key: CalculatorKey): HTMLButtonElement { + const button = document.createElement("button"); + button.className = `calculator-app__key calculator-app__key--${key.kind}`; + button.type = "button"; + button.textContent = key.label; + button.dataset.calculatorCommand = key.command; + button.setAttribute("aria-label", key.name); + if (key.kind === "operator") { + button.setAttribute("aria-pressed", "false"); + } + if (key.shortcuts !== undefined) { + button.setAttribute("aria-keyshortcuts", key.shortcuts); + } + return button; +} + +function keyboardCommand(event: KeyboardEvent): string | null { + if (event.key === "Enter" && event.target instanceof HTMLButtonElement) { + return null; + } + if (/^\d$/.test(event.key)) { + return `digit:${event.key}`; + } + + switch (event.key) { + case ".": + return "decimal"; + case "+": + return "operator:add"; + case "-": + return "operator:subtract"; + case "*": + return "operator:multiply"; + case "/": + return "operator:divide"; + case "Enter": + case "=": + return "equals"; + case "Escape": + case "c": + case "C": + return "clear"; + case "Backspace": + case "Delete": + return "backspace"; + default: + return null; + } +} + +function applyCommand(model: CalculatorModel, command: string): void { + if (command.startsWith("digit:")) { + model.inputDigit(command.slice(-1)); + return; + } + if (command.startsWith("operator:")) { + model.chooseOperator(command.slice("operator:".length) as CalculatorOperator); + return; + } + + switch (command) { + case "decimal": + model.inputDecimal(); + break; + case "equals": + model.equals(); + break; + case "clear": + model.clear(); + break; + case "backspace": + model.backspace(); + break; + } +} diff --git a/src/applications/built-in/clock-model.ts b/src/applications/built-in/clock-model.ts new file mode 100644 index 0000000..ce3d260 --- /dev/null +++ b/src/applications/built-in/clock-model.ts @@ -0,0 +1,77 @@ +import type { Disposable } from "../../core/disposable"; +import type { Clock } from "../../core/time/clock"; +import { formatSystemTime, type SystemTime } from "../../shell/system-time"; + +export type ClockListener = (snapshot: SystemTime) => void; + +export class ClockModel { + readonly #clock: Clock; + readonly #listeners = new Set(); + #snapshot: SystemTime; + #cancelTick: Disposable | null = null; + #disposed = false; + + constructor(clock: Clock) { + this.#clock = clock; + this.#snapshot = formatSystemTime(clock.now()); + } + + get snapshot(): SystemTime { + return this.#snapshot; + } + + subscribe(listener: ClockListener): Disposable { + if (this.#disposed) { + throw new Error("Cannot subscribe to a disposed Clock model."); + } + + this.#listeners.add(listener); + if (this.#listeners.size === 1) { + this.#scheduleNextTick(); + } + + let subscribed = true; + return () => { + if (!subscribed) { + return; + } + subscribed = false; + this.#listeners.delete(listener); + if (this.#listeners.size === 0) { + this.#cancelScheduledTick(); + } + }; + } + + dispose(): void { + if (this.#disposed) { + return; + } + + this.#disposed = true; + this.#cancelScheduledTick(); + this.#listeners.clear(); + } + + #scheduleNextTick(): void { + const now = this.#clock.now(); + const elapsedInSecond = ((now % 1_000) + 1_000) % 1_000; + const delayMs = elapsedInSecond === 0 ? 1_000 : 1_000 - elapsedInSecond; + + this.#cancelTick = this.#clock.schedule(() => { + this.#cancelTick = null; + this.#snapshot = formatSystemTime(this.#clock.now()); + for (const listener of [...this.#listeners]) { + listener(this.#snapshot); + } + if (!this.#disposed && this.#listeners.size > 0) { + this.#scheduleNextTick(); + } + }, delayMs); + } + + #cancelScheduledTick(): void { + this.#cancelTick?.(); + this.#cancelTick = null; + } +} diff --git a/src/applications/built-in/clock.ts b/src/applications/built-in/clock.ts new file mode 100644 index 0000000..d4a676f --- /dev/null +++ b/src/applications/built-in/clock.ts @@ -0,0 +1,74 @@ +import type { Clock } from "../../core/time/clock"; +import { toApplicationId } from "../../core/identity/identifiers"; +import type { SystemTime } from "../../shell/system-time"; +import type { ApplicationDefinition, ApplicationView } from "../framework/application"; +import { ClockModel } from "./clock-model"; + +export const CLOCK_APPLICATION_ID = toApplicationId("system.clock"); + +export function createClockDefinition(clock: Clock): ApplicationDefinition { + return { + manifest: { + id: CLOCK_APPLICATION_ID, + name: "Clock", + description: "View the current local time and date.", + window: { + title: "Clock", + preferredWidth: 440, + preferredHeight: 300, + constraints: { minWidth: 300, minHeight: 240 }, + }, + }, + create: () => { + const model = new ClockModel(clock); + + return { + primaryView: createClockView(model), + dispose: () => model.dispose(), + }; + }, + }; +} + +function createClockView(model: ClockModel): ApplicationView { + return { + mount(host, document): () => void { + const content = document.createElement("section"); + content.className = "clock-app"; + + const face = document.createElement("div"); + face.className = "clock-app__face"; + + const time = document.createElement("time"); + time.className = "clock-app__time"; + + const date = document.createElement("time"); + date.className = "clock-app__date"; + + const render = (snapshot: SystemTime): void => { + if (time.textContent !== snapshot.time) { + time.textContent = snapshot.time; + } + time.dateTime = snapshot.iso; + time.setAttribute("aria-label", `Current time: ${snapshot.time}`); + + if (date.textContent !== snapshot.date) { + date.textContent = snapshot.date; + } + date.dateTime = snapshot.date.replaceAll(".", "-"); + date.setAttribute("aria-label", `Current date: ${snapshot.date}`); + }; + + face.append(time, date); + content.append(face); + host.replaceChildren(content); + render(model.snapshot); + const unsubscribe = model.subscribe(render); + + return () => { + unsubscribe(); + host.replaceChildren(); + }; + }, + }; +} diff --git a/src/applications/built-in/notepad-model.ts b/src/applications/built-in/notepad-model.ts new file mode 100644 index 0000000..267e50c --- /dev/null +++ b/src/applications/built-in/notepad-model.ts @@ -0,0 +1,15 @@ +export class NotepadModel { + #text = ""; + + get text(): string { + return this.#text; + } + + setText(text: string): void { + this.#text = text; + } + + dispose(): void { + this.#text = ""; + } +} diff --git a/src/applications/built-in/notepad.ts b/src/applications/built-in/notepad.ts new file mode 100644 index 0000000..2ca8327 --- /dev/null +++ b/src/applications/built-in/notepad.ts @@ -0,0 +1,55 @@ +import { toApplicationId } from "../../core/identity/identifiers"; +import type { ApplicationDefinition, ApplicationView } from "../framework/application"; +import { NotepadModel } from "./notepad-model"; + +export const NOTEPAD_APPLICATION_ID = toApplicationId("system.notepad"); + +export function createNotepadDefinition(): ApplicationDefinition { + return { + manifest: { + id: NOTEPAD_APPLICATION_ID, + name: "Notes", + description: "Write and edit temporary session text.", + window: { + title: "Notes", + preferredWidth: 620, + preferredHeight: 440, + constraints: { minWidth: 320, minHeight: 240 }, + }, + }, + create: () => { + const model = new NotepadModel(); + + return { + primaryView: createNotepadView(model), + dispose: () => model.dispose(), + }; + }, + }; +} + +function createNotepadView(model: NotepadModel): ApplicationView { + return { + mount(host, document): () => void { + const content = document.createElement("section"); + content.className = "notepad-app"; + + const editor = document.createElement("textarea"); + editor.className = "notepad-app__editor"; + editor.value = model.text; + editor.placeholder = "Start typing..."; + editor.setAttribute("aria-label", "Notes editor"); + + const handleInput = (): void => model.setText(editor.value); + editor.addEventListener("input", handleInput); + content.append(editor); + host.replaceChildren(content); + editor.focus({ preventScroll: true }); + + return () => { + editor.removeEventListener("input", handleInput); + host.replaceChildren(); + }; + }, + }; +} diff --git a/src/bootstrap/start-afterboot.ts b/src/bootstrap/start-afterboot.ts index 3c6683d..6386630 100644 --- a/src/bootstrap/start-afterboot.ts +++ b/src/bootstrap/start-afterboot.ts @@ -2,6 +2,9 @@ import { ShadowRuntime, type BootStageDurations } from "../core/runtime/shadow-r import { SequentialIdGenerator } from "../core/identity/identifiers"; import { ApplicationRegistry } from "../applications/framework/application-registry"; import { ApplicationManager } from "../applications/framework/application-manager"; +import { createCalculatorDefinition } from "../applications/built-in/calculator"; +import { createClockDefinition } from "../applications/built-in/clock"; +import { createNotepadDefinition } from "../applications/built-in/notepad"; import { createSystemDiagnosticsDefinition } from "../applications/built-in/system-diagnostics"; import { BrowserClock } from "../platform/browser-clock"; import { prefersReducedMotion } from "../platform/motion-preference"; @@ -51,7 +54,12 @@ export function startAfterboot(document: Document, browserWindow: Window): After }); const ids = new SequentialIdGenerator(); const windowManager = new WindowManager(ids, { x: 0, y: 0, width: 1, height: 1 }); - const registry = new ApplicationRegistry([createSystemDiagnosticsDefinition()]); + const registry = new ApplicationRegistry([ + createSystemDiagnosticsDefinition(), + createNotepadDefinition(), + createCalculatorDefinition(), + createClockDefinition(clock), + ]); const applicationManager = new ApplicationManager(registry, windowManager, ids); const disposeRuntimeServices = runtime.onStateChanged((event) => { if (event.reason === "reset-requested" || event.reason === "runtime-failed") { diff --git a/src/shell/desktop/application-drawer-view.ts b/src/shell/desktop/application-drawer-view.ts new file mode 100644 index 0000000..9ba9604 --- /dev/null +++ b/src/shell/desktop/application-drawer-view.ts @@ -0,0 +1,302 @@ +import type { ApplicationManager } from "../../applications/framework/application-manager"; +import type { ApplicationRegistry } from "../../applications/framework/application-registry"; +import type { ApplicationManifest } from "../../applications/framework/application"; +import type { Disposable } from "../../core/disposable"; +import { toApplicationId } from "../../core/identity/identifiers"; + +const DRAWER_ID = "application-drawer"; +const DRAWER_TITLE_ID = "application-drawer-title"; +const SVG_NAMESPACE = "http://www.w3.org/2000/svg"; + +export class ApplicationDrawerView { + readonly trigger: HTMLButtonElement; + readonly element: HTMLElement; + readonly #document: Document; + readonly #registry: ApplicationRegistry; + readonly #applicationManager: ApplicationManager; + readonly #list: HTMLElement; + + constructor( + document: Document, + registry: ApplicationRegistry, + applicationManager: ApplicationManager, + ) { + this.#document = document; + this.#registry = registry; + this.#applicationManager = applicationManager; + + this.trigger = document.createElement("button"); + this.trigger.className = "application-drawer__trigger"; + this.trigger.type = "button"; + this.trigger.textContent = "Applications"; + this.trigger.setAttribute("aria-controls", DRAWER_ID); + this.trigger.setAttribute("aria-expanded", "false"); + this.trigger.setAttribute("aria-haspopup", "dialog"); + + this.element = document.createElement("section"); + this.element.id = DRAWER_ID; + this.element.className = "application-drawer"; + this.element.hidden = true; + this.element.setAttribute("role", "dialog"); + this.element.setAttribute("aria-labelledby", DRAWER_TITLE_ID); + + const header = document.createElement("header"); + header.className = "application-drawer__header"; + const eyebrow = document.createElement("span"); + eyebrow.className = "application-drawer__eyebrow"; + eyebrow.textContent = "SHADOW OS /"; + const title = document.createElement("h2"); + title.id = DRAWER_TITLE_ID; + title.className = "application-drawer__title"; + title.textContent = "Applications"; + header.append(eyebrow, title); + + this.#list = document.createElement("div"); + this.#list.className = "application-drawer__list"; + this.#list.setAttribute("aria-label", "Installed applications"); + this.element.append(header, this.#list); + this.refresh(); + } + + get isOpen(): boolean { + return !this.element.hidden; + } + + mount(): Disposable { + this.trigger.addEventListener("click", this.#handleTriggerClick); + this.trigger.addEventListener("keydown", this.#handleTriggerKeyDown); + this.element.addEventListener("click", this.#handleDrawerClick); + this.element.addEventListener("keydown", this.#handleDrawerKeyDown); + this.#document.addEventListener("pointerdown", this.#handleDocumentPointerDown); + this.#document.addEventListener("focusin", this.#handleDocumentFocusIn); + + return () => { + this.trigger.removeEventListener("click", this.#handleTriggerClick); + this.trigger.removeEventListener("keydown", this.#handleTriggerKeyDown); + this.element.removeEventListener("click", this.#handleDrawerClick); + this.element.removeEventListener("keydown", this.#handleDrawerKeyDown); + this.#document.removeEventListener("pointerdown", this.#handleDocumentPointerDown); + this.#document.removeEventListener("focusin", this.#handleDocumentFocusIn); + this.close(false); + }; + } + + refresh(): void { + this.#list.replaceChildren(...this.#registry.list().map((manifest) => this.#entry(manifest))); + } + + open(focusFirst = true): void { + if (this.isOpen) { + if (focusFirst) { + this.#entryButtons()[0]?.focus(); + } + return; + } + + this.element.hidden = false; + this.trigger.setAttribute("aria-expanded", "true"); + if (focusFirst) { + this.#entryButtons()[0]?.focus(); + } + } + + close(restoreFocus = true): void { + if (!this.isOpen) { + return; + } + + this.element.hidden = true; + this.trigger.setAttribute("aria-expanded", "false"); + if (restoreFocus && this.trigger.isConnected) { + this.trigger.focus({ preventScroll: true }); + } + } + + #entry(manifest: ApplicationManifest): HTMLButtonElement { + const button = this.#document.createElement("button"); + button.className = "application-drawer__entry"; + button.type = "button"; + button.dataset.applicationId = manifest.id; + + const marker = this.#document.createElement("span"); + marker.className = "application-drawer__marker"; + marker.setAttribute("aria-hidden", "true"); + if (manifest.name === "Notes") { + marker.append(createNotesIcon(this.#document)); + } else if (manifest.name === "Calculator") { + marker.append(createCalculatorIcon(this.#document)); + } else { + marker.textContent = markerFor(manifest.name); + } + const copy = this.#document.createElement("span"); + copy.className = "application-drawer__copy"; + const name = this.#document.createElement("span"); + name.className = "application-drawer__name"; + name.textContent = manifest.name; + const description = this.#document.createElement("span"); + description.className = "application-drawer__description"; + description.textContent = manifest.description; + copy.append(name, description); + button.append(marker, copy); + return button; + } + + #entryButtons(): HTMLButtonElement[] { + return [...this.#list.querySelectorAll("[data-application-id]")]; + } + + readonly #handleTriggerClick = (): void => { + if (this.isOpen) { + this.close(); + } else { + this.open(); + } + }; + + readonly #handleTriggerKeyDown = (event: KeyboardEvent): void => { + if (event.key === "ArrowDown") { + event.preventDefault(); + this.open(); + } else if (event.key === "Escape" && this.isOpen) { + event.preventDefault(); + this.close(); + } + }; + + readonly #handleDrawerClick = (event: MouseEvent): void => { + const target = event.target instanceof Element ? event.target : null; + const applicationId = + target?.closest("[data-application-id]")?.dataset.applicationId; + if (!applicationId) { + return; + } + + this.#applicationManager.launch(toApplicationId(applicationId)); + this.close(false); + }; + + readonly #handleDrawerKeyDown = (event: KeyboardEvent): void => { + if (event.key === "Escape") { + event.preventDefault(); + this.close(); + return; + } + + const entries = this.#entryButtons(); + const currentIndex = entries.indexOf(this.#document.activeElement as HTMLButtonElement); + let nextIndex: number | null = null; + + switch (event.key) { + case "ArrowDown": + case "ArrowRight": + nextIndex = currentIndex < 0 ? 0 : (currentIndex + 1) % entries.length; + break; + case "ArrowUp": + case "ArrowLeft": + nextIndex = + currentIndex < 0 + ? entries.length - 1 + : (currentIndex - 1 + entries.length) % entries.length; + break; + case "Home": + nextIndex = 0; + break; + case "End": + nextIndex = entries.length - 1; + break; + } + + const nextEntry = nextIndex === null ? undefined : entries[nextIndex]; + if (nextEntry) { + event.preventDefault(); + nextEntry.focus(); + } + }; + + readonly #handleDocumentPointerDown = (event: PointerEvent): void => { + const target = event.target; + if ( + this.isOpen && + target instanceof Node && + !this.element.contains(target) && + !this.trigger.contains(target) + ) { + this.close(false); + } + }; + + readonly #handleDocumentFocusIn = (event: FocusEvent): void => { + const target = event.target; + if ( + this.isOpen && + target instanceof Node && + !this.element.contains(target) && + !this.trigger.contains(target) + ) { + this.close(false); + } + }; +} + +function markerFor(name: string): string { + const marker = name + .trim() + .split(/\s+/) + .slice(0, 2) + .map((part) => part[0]?.toUpperCase() ?? "") + .join(""); + return marker || "APP"; +} + +function createNotesIcon(document: Document): SVGSVGElement { + const icon = document.createElementNS(SVG_NAMESPACE, "svg"); + icon.classList.add("application-drawer__notes-icon"); + icon.setAttribute("viewBox", "0 0 32 32"); + icon.setAttribute("fill", "none"); + icon.setAttribute("aria-hidden", "true"); + icon.setAttribute("focusable", "false"); + + const page = document.createElementNS(SVG_NAMESPACE, "path"); + page.classList.add("application-drawer__notes-page"); + page.setAttribute("d", "M7 4.5h12l6 6v17H7z M19 4.5v6h6 M11 15h10 M11 19h8 M11 23h4"); + + const pencil = document.createElementNS(SVG_NAMESPACE, "path"); + pencil.classList.add("application-drawer__notes-pencil"); + pencil.setAttribute("d", "m16 26.5 1-4 8-8 3.5 3.5-8 8z M24 15.5l3.5 3.5 M17 22.5l3.5 3.5"); + + icon.append(page, pencil); + return icon; +} + +function createCalculatorIcon(document: Document): SVGSVGElement { + const icon = document.createElementNS(SVG_NAMESPACE, "svg"); + icon.classList.add("application-drawer__calculator-icon"); + icon.setAttribute("viewBox", "0 0 32 32"); + icon.setAttribute("fill", "none"); + icon.setAttribute("aria-hidden", "true"); + icon.setAttribute("focusable", "false"); + + const body = document.createElementNS(SVG_NAMESPACE, "rect"); + body.classList.add("application-drawer__calculator-body"); + body.setAttribute("x", "6"); + body.setAttribute("y", "3.5"); + body.setAttribute("width", "20"); + body.setAttribute("height", "25"); + + const display = document.createElementNS(SVG_NAMESPACE, "rect"); + display.classList.add("application-drawer__calculator-display"); + display.setAttribute("x", "9"); + display.setAttribute("y", "7"); + display.setAttribute("width", "14"); + display.setAttribute("height", "5.5"); + + const keys = document.createElementNS(SVG_NAMESPACE, "path"); + keys.classList.add("application-drawer__calculator-keys"); + keys.setAttribute( + "d", + "M9 16h3v3H9z M14.5 16h3v3h-3z M20 16h3v3h-3z M9 21.5h3v3H9z M14.5 21.5h3v3h-3z M20 21.5h3v3h-3z", + ); + + icon.append(body, display, keys); + return icon; +} diff --git a/src/shell/desktop/context-menu-model.ts b/src/shell/desktop/context-menu-model.ts new file mode 100644 index 0000000..e4687ff --- /dev/null +++ b/src/shell/desktop/context-menu-model.ts @@ -0,0 +1,32 @@ +export type DesktopContextMenuActionId = "refresh-desktop" | "open-application-drawer"; + +export interface ContextMenuItem { + readonly id: DesktopContextMenuActionId; + readonly label: string; + readonly symbol: string; +} + +export interface OverlayPoint { + readonly x: number; + readonly y: number; +} + +export interface OverlaySize { + readonly width: number; + readonly height: number; +} + +export function clampOverlayPosition( + anchor: OverlayPoint, + overlay: OverlaySize, + viewport: OverlaySize, + margin = 8, +): OverlayPoint { + const maximumX = Math.max(margin, viewport.width - overlay.width - margin); + const maximumY = Math.max(margin, viewport.height - overlay.height - margin); + + return Object.freeze({ + x: Math.min(Math.max(margin, anchor.x), maximumX), + y: Math.min(Math.max(margin, anchor.y), maximumY), + }); +} diff --git a/src/shell/desktop/context-menu-view.ts b/src/shell/desktop/context-menu-view.ts new file mode 100644 index 0000000..74f3a40 --- /dev/null +++ b/src/shell/desktop/context-menu-view.ts @@ -0,0 +1,171 @@ +import type { Disposable } from "../../core/disposable"; +import { + clampOverlayPosition, + type ContextMenuItem, + type DesktopContextMenuActionId, +} from "./context-menu-model"; + +export type ContextMenuActionHandler = ( + actionId: DesktopContextMenuActionId, + invoker: HTMLElement | null, +) => void; + +export class ContextMenuView { + readonly element: HTMLElement; + readonly #document: Document; + readonly #browserWindow: Window; + readonly #onAction: ContextMenuActionHandler; + #invoker: HTMLElement | null = null; + + constructor( + document: Document, + browserWindow: Window, + items: readonly ContextMenuItem[], + onAction: ContextMenuActionHandler, + ) { + this.#document = document; + this.#browserWindow = browserWindow; + this.#onAction = onAction; + + this.element = document.createElement("div"); + this.element.className = "desktop-context-menu"; + this.element.hidden = true; + this.element.setAttribute("role", "menu"); + this.element.setAttribute("aria-label", "Desktop actions"); + this.element.append(...items.map((item) => this.#item(item))); + } + + get isOpen(): boolean { + return !this.element.hidden; + } + + mount(): Disposable { + this.element.addEventListener("click", this.#handleClick); + this.element.addEventListener("keydown", this.#handleKeyDown); + this.#document.addEventListener("pointerdown", this.#handleDocumentPointerDown); + + return () => { + this.element.removeEventListener("click", this.#handleClick); + this.element.removeEventListener("keydown", this.#handleKeyDown); + this.#document.removeEventListener("pointerdown", this.#handleDocumentPointerDown); + this.close(false); + }; + } + + open(anchorX: number, anchorY: number, invoker: HTMLElement | null): void { + this.#invoker = invoker; + this.element.hidden = false; + this.element.style.left = `${anchorX}px`; + this.element.style.top = `${anchorY}px`; + + const bounds = this.element.getBoundingClientRect(); + const position = clampOverlayPosition( + { x: anchorX, y: anchorY }, + { width: bounds.width, height: bounds.height }, + { width: this.#browserWindow.innerWidth, height: this.#browserWindow.innerHeight }, + ); + this.element.style.left = `${position.x}px`; + this.element.style.top = `${position.y}px`; + this.#focusItem(0); + } + + close(restoreFocus = true): void { + if (!this.isOpen) { + return; + } + + const invoker = this.#invoker; + this.element.hidden = true; + this.#invoker = null; + if (restoreFocus && invoker?.isConnected) { + invoker.focus({ preventScroll: true }); + } + } + + #item(item: ContextMenuItem): HTMLButtonElement { + const button = this.#document.createElement("button"); + button.className = "desktop-context-menu__item"; + button.type = "button"; + button.tabIndex = -1; + button.dataset.contextAction = item.id; + button.setAttribute("role", "menuitem"); + const label = this.#document.createElement("span"); + label.textContent = item.label; + const symbol = this.#document.createElement("span"); + symbol.className = "desktop-context-menu__symbol"; + symbol.textContent = item.symbol; + symbol.setAttribute("aria-hidden", "true"); + button.append(label, symbol); + return button; + } + + #items(): HTMLButtonElement[] { + return [...this.element.querySelectorAll("[role='menuitem']")]; + } + + #focusItem(index: number): void { + const items = this.#items(); + const item = items[index]; + if (!item) { + return; + } + + for (const candidate of items) { + candidate.tabIndex = candidate === item ? 0 : -1; + } + item.focus({ preventScroll: true }); + } + + readonly #handleClick = (event: MouseEvent): void => { + const target = event.target instanceof Element ? event.target : null; + const actionId = target?.closest("[data-context-action]")?.dataset + .contextAction as DesktopContextMenuActionId | undefined; + if (!actionId) { + return; + } + + const invoker = this.#invoker; + this.close(false); + this.#onAction(actionId, invoker); + }; + + readonly #handleKeyDown = (event: KeyboardEvent): void => { + if (event.key === "Escape" || event.key === "Tab") { + event.preventDefault(); + this.close(); + return; + } + + const items = this.#items(); + const currentIndex = items.indexOf(this.#document.activeElement as HTMLButtonElement); + let nextIndex: number | null = null; + + switch (event.key) { + case "ArrowDown": + nextIndex = currentIndex < 0 ? 0 : (currentIndex + 1) % items.length; + break; + case "ArrowUp": + nextIndex = + currentIndex < 0 ? items.length - 1 : (currentIndex - 1 + items.length) % items.length; + break; + case "Home": + nextIndex = 0; + break; + case "End": + nextIndex = items.length - 1; + break; + } + + if (nextIndex !== null && items[nextIndex]) { + event.preventDefault(); + this.#focusItem(nextIndex); + } + }; + + readonly #handleDocumentPointerDown = (event: PointerEvent): void => { + const target = event.target; + if (this.isOpen && target instanceof Node && !this.element.contains(target)) { + this.close(false); + } + }; +} diff --git a/src/shell/desktop/desktop-view.ts b/src/shell/desktop/desktop-view.ts index 663315a..a8c7ae5 100644 --- a/src/shell/desktop/desktop-view.ts +++ b/src/shell/desktop/desktop-view.ts @@ -1,12 +1,15 @@ import type { ApplicationManager } from "../../applications/framework/application-manager"; import type { ApplicationRegistry } from "../../applications/framework/application-registry"; import type { Disposable } from "../../core/disposable"; -import { toApplicationId, toWindowId } from "../../core/identity/identifiers"; +import { toWindowId } from "../../core/identity/identifiers"; import type { ShadowRuntime } from "../../core/runtime/shadow-runtime"; import type { Clock } from "../../core/time/clock"; import type { WindowManager } from "../windows/window-manager"; import { WindowLayerView } from "../windows/window-layer-view"; import { formatSystemTime } from "../system-time"; +import { ApplicationDrawerView } from "./application-drawer-view"; +import type { DesktopContextMenuActionId } from "./context-menu-model"; +import { ContextMenuView } from "./context-menu-view"; const CLOCK_UPDATE_INTERVAL_MS = 1_000; @@ -15,17 +18,19 @@ export class DesktopView { readonly #document: Document; readonly #runtime: ShadowRuntime; readonly #clock: Clock; - readonly #registry: ApplicationRegistry; - readonly #applicationManager: ApplicationManager; readonly #windowManager: WindowManager; readonly #windowLayer: WindowLayerView; - readonly #launcher: HTMLElement; + readonly #workspace: HTMLElement; + readonly #drawer: ApplicationDrawerView; + readonly #contextMenu: ContextMenuView; readonly #taskStrip: HTMLElement; readonly #time: HTMLTimeElement; readonly #date: HTMLElement; + readonly #status: HTMLElement; readonly #resetButton: HTMLButtonElement; #cancelClock: Disposable | null = null; #unsubscribeWindows: Disposable | null = null; + #refreshCount = 0; constructor( document: Document, @@ -40,8 +45,6 @@ export class DesktopView { this.#document = document; this.#runtime = runtime; this.#clock = clock; - this.#registry = registry; - this.#applicationManager = applicationManager; this.#windowManager = windowManager; const main = element(document, "main", "desktop-shell"); @@ -58,6 +61,8 @@ export class DesktopView { const workspace = element(document, "section", "desktop-shell__workspace"); workspace.setAttribute("aria-label", "SHADOW OS desktop work area"); + workspace.dataset.contextSurface = "desktop"; + workspace.tabIndex = 0; const desktopIdentity = element(document, "div", "desktop-shell__identity"); desktopIdentity.setAttribute("aria-hidden", "true"); desktopIdentity.append( @@ -74,10 +79,21 @@ export class DesktopView { windowLayer.setAttribute("aria-label", "Open application windows"); workspace.append(desktopIdentity, windowLayer); + this.#workspace = workspace; + this.#drawer = new ApplicationDrawerView(document, registry, applicationManager); + this.#contextMenu = new ContextMenuView( + document, + browserWindow, + [ + { id: "refresh-desktop", label: "Refresh Desktop", symbol: "↻" }, + { id: "open-application-drawer", label: "Applications", symbol: "◇" }, + ], + this.#handleContextAction, + ); + const footer = element(document, "footer", "desktop-shell__footer"); - this.#launcher = element(document, "nav", "application-launcher"); - this.#launcher.setAttribute("aria-label", "Applications"); - this.#renderLauncher(); + const launcher = element(document, "div", "application-launcher"); + launcher.append(this.#drawer.trigger); this.#taskStrip = element(document, "nav", "window-task-strip"); this.#taskStrip.setAttribute("aria-label", "Open windows"); const clockPanel = element(document, "section", "system-clock"); @@ -87,8 +103,18 @@ export class DesktopView { clockPanel.append(this.#time, this.#date); this.#resetButton = element(document, "button", "desktop-shell__reset", "Restart SHADOW OS"); this.#resetButton.type = "button"; - footer.append(this.#launcher, this.#taskStrip, clockPanel, this.#resetButton); - main.append(header, workspace, footer); + this.#status = element(document, "p", "visually-hidden"); + this.#status.setAttribute("role", "status"); + this.#status.setAttribute("aria-live", "polite"); + footer.append(launcher, this.#taskStrip, clockPanel, this.#resetButton); + main.append( + header, + workspace, + this.#drawer.element, + this.#contextMenu.element, + footer, + this.#status, + ); this.element = main; this.#windowLayer = new WindowLayerView( @@ -101,7 +127,9 @@ export class DesktopView { } mount(): Disposable { - this.#launcher.addEventListener("click", this.#handleLauncherClick); + const disposeDrawer = this.#drawer.mount(); + const disposeContextMenu = this.#contextMenu.mount(); + this.#workspace.addEventListener("contextmenu", this.#handleDesktopContextMenu); this.#taskStrip.addEventListener("click", this.#handleTaskClick); this.#resetButton.addEventListener("click", this.#handleReset); this.#unsubscribeWindows = this.#windowManager.onStateChanged((event) => { @@ -114,7 +142,7 @@ export class DesktopView { } if (event.reason === "window-closed" && !event.snapshot.activeWindowId) { - this.#launcher.querySelector("[data-application-id]")?.focus(); + this.#drawer.trigger.focus(); } }); const disposeWindowLayer = this.#windowLayer.mount(); @@ -122,34 +150,19 @@ export class DesktopView { this.#updateClock(); return () => { - this.#launcher.removeEventListener("click", this.#handleLauncherClick); + this.#workspace.removeEventListener("contextmenu", this.#handleDesktopContextMenu); this.#taskStrip.removeEventListener("click", this.#handleTaskClick); this.#resetButton.removeEventListener("click", this.#handleReset); this.#unsubscribeWindows?.(); this.#unsubscribeWindows = null; this.#cancelClock?.(); this.#cancelClock = null; + disposeContextMenu(); + disposeDrawer(); disposeWindowLayer(); }; } - #renderLauncher(): void { - const label = element(this.#document, "span", "application-launcher__label", "APPS"); - const buttons = this.#registry.list().map((manifest) => { - const button = element( - this.#document, - "button", - "application-launcher__button", - manifest.name, - ); - button.type = "button"; - button.dataset.applicationId = manifest.id; - button.title = manifest.description; - return button; - }); - this.#launcher.replaceChildren(label, ...buttons); - } - #renderTasks(): void { const snapshot = this.#windowManager.snapshot; const tasks = snapshot.windows.map((windowState) => { @@ -173,19 +186,60 @@ export class DesktopView { } #updateClock(): void { + this.#renderClock(); + this.#cancelClock = this.#clock.schedule(() => this.#updateClock(), CLOCK_UPDATE_INTERVAL_MS); + } + + #renderClock(): void { const systemTime = formatSystemTime(this.#clock.now()); this.#time.dateTime = systemTime.iso; this.#time.textContent = systemTime.time; this.#date.textContent = systemTime.date; - this.#cancelClock = this.#clock.schedule(() => this.#updateClock(), CLOCK_UPDATE_INTERVAL_MS); } - readonly #handleLauncherClick = (event: MouseEvent): void => { + #refreshDesktop(invoker: HTMLElement | null): void { + this.#contextMenu.close(false); + this.#drawer.close(false); + this.#drawer.refresh(); + this.#renderTasks(); + this.#windowLayer.render(); + this.#renderClock(); + this.#refreshCount += 1; + this.#status.textContent = `Desktop refreshed ${this.#refreshCount.toString()}`; + if (invoker?.isConnected) { + invoker.focus({ preventScroll: true }); + } + } + + readonly #handleDesktopContextMenu = (event: MouseEvent): void => { const target = event.target instanceof Element ? event.target : null; - const applicationId = - target?.closest("[data-application-id]")?.dataset.applicationId; - if (applicationId) { - this.#applicationManager.launch(toApplicationId(applicationId)); + if (target?.closest(".os-window")) { + return; + } + + event.preventDefault(); + this.#drawer.close(false); + const invoker = + this.#document.activeElement instanceof HTMLElement + ? this.#document.activeElement + : this.#workspace; + const workspaceBounds = this.#workspace.getBoundingClientRect(); + const keyboardInvocation = event.clientX === 0 && event.clientY === 0; + this.#contextMenu.open( + keyboardInvocation ? workspaceBounds.left + 16 : event.clientX, + keyboardInvocation ? workspaceBounds.top + 16 : event.clientY, + invoker, + ); + }; + + readonly #handleContextAction = ( + actionId: DesktopContextMenuActionId, + invoker: HTMLElement | null, + ): void => { + if (actionId === "open-application-drawer") { + this.#drawer.open(); + } else { + this.#refreshDesktop(invoker); } }; diff --git a/src/styles/windows.css b/src/styles/windows.css index dce7677..42c5569 100644 --- a/src/styles/windows.css +++ b/src/styles/windows.css @@ -31,6 +31,11 @@ animation: desktop-enter 350ms ease-out both; } +.desktop-shell__workspace:focus-visible { + outline: 1px solid var(--color-signal); + outline-offset: -3px; +} + .desktop-shell__identity { position: absolute; z-index: 0; @@ -193,12 +198,7 @@ overflow-x: auto; } -.application-launcher__label { - color: var(--color-signal); - font-size: 0.65rem; -} - -.application-launcher__button, +.application-drawer__trigger, .window-task-strip__button, .diagnostics-app__action { min-height: 2.5rem; @@ -210,6 +210,235 @@ cursor: pointer; } +.application-drawer__trigger { + display: inline-grid; + grid-template-columns: auto auto; + align-items: center; + gap: 0.6rem; + color: var(--color-ink); + font-size: 0.7rem; + text-transform: uppercase; +} + +.application-drawer__trigger::before { + width: 0.75rem; + height: 0.75rem; + border: 1px solid var(--color-signal); + background: + linear-gradient(90deg, transparent 42%, var(--color-signal) 42% 58%, transparent 58%), + linear-gradient(transparent 42%, var(--color-signal) 42% 58%, transparent 58%); + content: ""; +} + +.application-drawer__trigger:hover, +.application-drawer__trigger[aria-expanded="true"] { + border-color: var(--color-signal); + background: var(--color-panel-raised); +} + +.application-drawer__trigger[aria-expanded="true"]::before { + background: var(--color-signal); + box-shadow: 0 0 0.7rem rgb(143 240 189 / 30%); +} + +.application-drawer, +.desktop-context-menu { + z-index: 1000; + border: 1px solid var(--color-rule-strong); + color: var(--color-ink); + background: #0c1214; + box-shadow: 0 1.5rem 4rem rgb(0 0 0 / 65%); +} + +.application-drawer[hidden], +.desktop-context-menu[hidden] { + display: none; +} + +.application-drawer { + position: absolute; + bottom: 5rem; + left: 1rem; + display: grid; + width: min(24rem, calc(100% - 2rem)); + max-height: min(62vh, 28rem); + grid-template-rows: auto minmax(0, 1fr); + border-color: var(--color-rule-strong); + background: + linear-gradient(rgb(143 240 189 / 3%) 1px, transparent 1px), + linear-gradient(90deg, rgb(143 240 189 / 3%) 1px, transparent 1px), #0c1214; + background-size: 1.25rem 1.25rem; + box-shadow: + 0 0 0 1px rgb(143 240 189 / 6%), + 0 1.25rem 3rem rgb(0 0 0 / 58%); +} + +.application-drawer__header { + display: flex; + align-items: baseline; + gap: 0.35rem; + padding: 0.7rem 0.85rem; + border-bottom: 1px solid var(--color-rule); + background: rgb(16 23 25 / 94%); +} + +.application-drawer__eyebrow { + color: var(--color-signal); + font-size: 0.62rem; + text-transform: uppercase; +} + +.application-drawer__title { + margin: 0; + font-family: inherit; + font-size: 0.68rem; + font-weight: 700; + letter-spacing: 0; + text-transform: uppercase; +} + +.application-drawer__list { + display: grid; + grid-template-columns: repeat(3, minmax(0, 1fr)); + gap: 0.55rem; + min-height: 0; + padding: 0.85rem; + overflow-y: auto; + background: rgb(8 11 12 / 72%); +} + +.application-drawer__entry { + display: grid; + grid-template-rows: 3.25rem auto; + align-items: center; + justify-items: center; + gap: 0.65rem; + min-width: 0; + min-height: 7.5rem; + padding: 0.8rem 0.45rem; + border: 1px solid var(--color-rule); + border-radius: 2px; + color: var(--color-ink); + background: rgb(16 23 25 / 90%); + text-align: center; + cursor: pointer; +} + +.application-drawer__entry:hover, +.application-drawer__entry:focus-visible { + border-color: var(--color-signal); + background: rgb(22 32 35 / 96%); + box-shadow: inset 0 -2px var(--color-signal); +} + +.application-drawer__marker { + display: grid; + width: 3.25rem; + height: 3.25rem; + place-items: center; + border: 1px solid var(--color-signal); + color: var(--color-signal); + background: rgb(143 240 189 / 4%); + font-size: 0.75rem; +} + +.application-drawer__notes-icon { + width: 2.35rem; + height: 2.35rem; + stroke: currentColor; + stroke-width: 1.4; + stroke-linecap: square; + stroke-linejoin: miter; +} + +.application-drawer__notes-page { + fill: currentColor; + fill-opacity: 0.04; +} + +.application-drawer__notes-pencil { + fill: rgb(16 23 25); +} + +.application-drawer__calculator-icon { + width: 2.35rem; + height: 2.35rem; + stroke: currentColor; + stroke-width: 1.35; + stroke-linejoin: miter; +} + +.application-drawer__calculator-body { + fill: currentColor; + fill-opacity: 0.04; +} + +.application-drawer__calculator-display { + fill: rgb(16 23 25); +} + +.application-drawer__calculator-keys { + fill: currentColor; + stroke: none; +} + +.application-drawer__copy { + display: grid; + gap: 0; + min-width: 0; +} + +.application-drawer__name { + font-size: 0.66rem; + line-height: 1.35; + text-transform: uppercase; +} + +.application-drawer__description { + display: none; +} + +.desktop-context-menu { + position: fixed; + display: grid; + width: min(13rem, calc(100vw - 1rem)); + padding: 0.25rem; + border-color: var(--color-rule-strong); + box-shadow: + 0 0 0 1px rgb(143 240 189 / 5%), + 0 0.9rem 2rem rgb(0 0 0 / 55%); +} + +.desktop-context-menu__item { + display: grid; + min-height: 2rem; + grid-template-columns: minmax(0, 1fr) auto; + align-items: center; + gap: 0.75rem; + padding: 0.4rem 0.55rem; + border: 0; + border-radius: 0; + color: var(--color-ink); + background: transparent; + font-size: 0.65rem; + text-align: left; + text-transform: uppercase; + cursor: pointer; +} + +.desktop-context-menu__symbol { + color: var(--color-signal); + font-size: 0.85rem; + line-height: 1; +} + +.desktop-context-menu__item:hover, +.desktop-context-menu__item:focus-visible { + color: var(--color-signal); + background: rgb(143 240 189 / 9%); + box-shadow: inset 2px 0 var(--color-signal); +} + .window-task-strip__button { max-width: 13rem; overflow: hidden; @@ -303,6 +532,223 @@ line-height: 1.7; } +.notepad-app { + width: 100%; + height: 100%; + padding: 0.75rem; + background: + linear-gradient(rgb(143 240 189 / 3%) 1px, transparent 1px), + linear-gradient(90deg, rgb(143 240 189 / 3%) 1px, transparent 1px), #0c1214; + background-size: 1.5rem 1.5rem; +} + +.notepad-app__editor { + display: block; + width: 100%; + height: 100%; + min-width: 0; + min-height: 0; + padding: 1rem; + resize: none; + border: 1px solid var(--color-rule); + border-radius: 0; + outline: 0; + color: var(--color-ink); + caret-color: var(--color-signal); + background: rgb(8 11 12 / 92%); + font: inherit; + font-size: 0.78rem; + line-height: 1.7; +} + +.notepad-app__editor::placeholder { + color: var(--color-muted); +} + +.notepad-app__editor:focus-visible { + border-color: var(--color-signal); + box-shadow: inset 0 0 0 1px rgb(143 240 189 / 12%); +} + +.calculator-app { + display: grid; + grid-template-rows: minmax(5.5rem, auto) minmax(0, 1fr); + gap: 0.65rem; + width: 100%; + height: 100%; + min-width: 0; + min-height: 0; + padding: 0.75rem; + outline: 0; + background: + linear-gradient(rgb(143 240 189 / 3%) 1px, transparent 1px), + linear-gradient(90deg, rgb(143 240 189 / 3%) 1px, transparent 1px), #0c1214; + background-size: 1.5rem 1.5rem; +} + +.calculator-app__display-panel { + display: grid; + grid-template-rows: minmax(0.9rem, auto) minmax(0, 1fr); + gap: 0.35rem; + min-width: 0; + padding: 0.8rem 0.9rem; + border: 1px solid var(--color-rule-strong); + overflow: hidden; + background: rgb(8 11 12 / 96%); + font-variant-numeric: tabular-nums; + white-space: nowrap; +} + +.calculator-app:focus-visible .calculator-app__display-panel { + border-color: var(--color-signal); + box-shadow: inset 0 0 0 1px rgb(143 240 189 / 12%); +} + +.calculator-app__pending { + min-width: 0; + min-height: 0.9rem; + overflow: hidden; + color: var(--color-muted); + font-size: 0.68rem; + line-height: 1; + text-overflow: ellipsis; +} + +.calculator-app__display { + min-width: 0; + align-self: center; + overflow: hidden; + color: var(--color-ink); + font-size: 1.7rem; + line-height: 1; + text-align: right; + text-overflow: clip; +} + +.calculator-app__display-panel[data-state="error"] { + border-color: var(--color-alert); +} + +.calculator-app__display[data-state="error"] { + color: var(--color-alert); + font-size: 1.2rem; +} + +.calculator-app__keypad { + display: grid; + grid-template-columns: repeat(4, minmax(0, 1fr)); + grid-template-rows: repeat(5, minmax(2.7rem, 1fr)); + grid-auto-flow: row dense; + gap: 0.35rem; + min-width: 0; + min-height: 0; +} + +.calculator-app__key { + min-width: 0; + min-height: 0; + padding: 0.35rem; + border: 1px solid var(--color-rule); + border-radius: 0; + outline: 0; + color: var(--color-ink); + background: rgb(16 23 25 / 96%); + font: inherit; + font-size: 0.85rem; + cursor: pointer; +} + +.calculator-app__key:hover, +.calculator-app__key:focus-visible { + border-color: var(--color-signal); + background: rgb(22 32 35 / 98%); + box-shadow: inset 0 -2px var(--color-signal); +} + +.calculator-app__key--operator { + border-color: var(--color-rule-strong); + color: var(--color-signal); + font-size: 1rem; +} + +.calculator-app__key--operator[aria-pressed="true"] { + border-color: var(--color-signal); + color: var(--color-ink); + background: rgb(143 240 189 / 14%); + box-shadow: + inset 0 0 0 1px rgb(143 240 189 / 42%), + inset 0 -3px var(--color-signal); +} + +.calculator-app__key--utility { + color: var(--color-muted); + font-size: 0.7rem; +} + +.calculator-app__key--equals { + grid-row: span 2; + border-color: var(--color-signal); + color: #08110d; + background: var(--color-signal); + font-size: 1rem; +} + +.calculator-app__key--equals:hover, +.calculator-app__key--equals:focus-visible { + color: #08110d; + background: #b4ffd6; +} + +.calculator-app__key[data-calculator-command="digit:0"] { + grid-column: span 2; +} + +.clock-app { + display: grid; + width: 100%; + height: 100%; + min-width: 0; + min-height: 0; + padding: 1rem; + place-items: center; + overflow: hidden; + background: + linear-gradient(rgb(143 240 189 / 3%) 1px, transparent 1px), + linear-gradient(90deg, rgb(143 240 189 / 3%) 1px, transparent 1px), #0c1214; + background-size: 1.5rem 1.5rem; +} + +.clock-app__face { + display: grid; + width: min(100%, 28rem); + gap: 1rem; + padding: 1.35rem 1rem; + border-block: 1px solid var(--color-rule-strong); + justify-items: center; + background: rgb(8 11 12 / 72%); + text-align: center; +} + +.clock-app__time, +.clock-app__date { + display: block; + max-width: 100%; + overflow: hidden; + font-variant-numeric: tabular-nums; + line-height: 1; + white-space: nowrap; +} + +.clock-app__time { + color: var(--color-signal); + font-size: 3rem; +} + +.clock-app__date { + color: var(--color-muted); + font-size: 0.78rem; +} + @media (max-width: 44rem) { .desktop-shell { min-height: 28rem; @@ -342,6 +788,24 @@ grid-column: 1; } + .application-drawer { + right: 0.75rem; + bottom: 7.5rem; + left: 0.75rem; + width: auto; + max-height: min(56vh, 24rem); + } + + .application-drawer__list { + gap: 0.45rem; + padding: 0.7rem; + } + + .application-drawer__entry { + min-height: 6.75rem; + padding-inline: 0.3rem; + } + .window-task-strip { grid-column: 1 / -1; grid-row: 2; @@ -355,4 +819,8 @@ grid-column: 2; grid-row: 1; } + + .notepad-app { + padding: 0.5rem; + } } diff --git a/tests/e2e/calculator.spec.ts b/tests/e2e/calculator.spec.ts new file mode 100644 index 0000000..8400496 --- /dev/null +++ b/tests/e2e/calculator.spec.ts @@ -0,0 +1,226 @@ +import { expect, test, type Page } from "@playwright/test"; + +function monitorPageFailures(page: Page): string[] { + const failures: string[] = []; + page.on("console", (message) => { + if (message.type() === "error") { + failures.push(`console: ${message.text()}`); + } + }); + page.on("pageerror", (error) => failures.push(`page: ${error.message}`)); + page.on("requestfailed", (request) => { + failures.push(`request: ${request.url()} ${request.failure()?.errorText ?? "unknown failure"}`); + }); + return failures; +} + +async function openDesktop(page: Page): Promise { + const failures = monitorPageFailures(page); + await page.goto("/"); + await page.getByRole("button", { name: "Skip boot sequence" }).click(); + await expect(page.getByRole("heading", { name: "Desktop ready" })).toBeVisible(); + return failures; +} + +async function launchCalculator(page: Page): Promise { + await page.getByRole("button", { name: "Applications" }).click(); + const drawer = page.getByRole("dialog", { name: "Applications" }); + const calculatorEntry = drawer.getByRole("button", { name: "Calculator" }); + const marker = calculatorEntry.locator(".application-drawer__marker"); + const icon = marker.locator("svg.application-drawer__calculator-icon"); + await expect(calculatorEntry).toBeVisible(); + await expect(marker).toHaveAttribute("aria-hidden", "true"); + await expect(marker).toBeEmpty(); + await expect(icon).toBeVisible(); + await expect(icon).toHaveAttribute("viewBox", "0 0 32 32"); + await expect(icon).toHaveAttribute("aria-hidden", "true"); + await calculatorEntry.click(); + await expect(page.getByRole("dialog", { name: "Calculator" })).toBeVisible(); +} + +async function pressKeys(page: Page, names: readonly string[]): Promise { + const calculator = page.getByRole("dialog", { name: "Calculator" }); + for (const name of names) { + await calculator.getByRole("button", { name, exact: true }).click(); + } +} + +test("performs basic pointer calculations through one Calculator instance", async ({ page }) => { + const failures = await openDesktop(page); + await launchCalculator(page); + + const calculator = page.getByRole("dialog", { name: "Calculator" }); + const surface = calculator.locator(".calculator-app"); + const display = calculator.getByLabel("Calculator display"); + const task = page.getByRole("button", { name: "Focus Calculator" }); + await expect(surface).toBeFocused(); + await expect(display).toHaveText("0"); + await expect(task).toHaveCount(1); + + await pressKeys(page, ["1", "2", "Add", "5", "Equals"]); + await expect(display).toHaveText("17"); + + await pressKeys(page, ["Clear", "5", "Subtract", "8", "Equals"]); + await expect(display).toHaveText("-3"); + + await pressKeys(page, ["Clear", "6", "Multiply", "7", "Equals"]); + await expect(display).toHaveText("42"); + + await pressKeys(page, ["Clear", "8", "Divide", "2", "Equals"]); + await expect(display).toHaveText("4"); + + await pressKeys(page, [ + "Clear", + "1", + "Decimal point", + "5", + "Add", + "2", + "Decimal point", + "2", + "5", + "Equals", + ]); + await expect(display).toHaveText("3.75"); + + await pressKeys(page, ["Clear", "1", "2", "3", "Backspace"]); + await expect(display).toHaveText("12"); + + await pressKeys(page, ["Clear", "9", "Divide", "0", "Equals"]); + await expect(display).toHaveText("ERROR"); + await expect(display).toHaveAttribute("data-state", "error"); + await calculator.getByRole("button", { name: "Clear" }).click(); + await expect(display).toHaveText("0"); + + await calculator.getByRole("button", { name: "Minimize window" }).click(); + await expect(calculator).toBeHidden(); + await launchCalculator(page); + await expect(calculator).toBeVisible(); + await expect(page.getByRole("dialog", { name: "Calculator" })).toHaveCount(1); + await expect(task).toHaveCount(1); + + await calculator.getByRole("button", { name: "Close window" }).click(); + await expect(calculator).toHaveCount(0); + await launchCalculator(page); + await expect(page.getByLabel("Calculator display")).toHaveText("0"); + expect(failures).toEqual([]); +}); + +test("projects pending operations into the display and selected operator", async ({ page }) => { + const failures = await openDesktop(page); + await launchCalculator(page); + + const calculator = page.getByRole("dialog", { name: "Calculator" }); + const display = calculator.getByLabel("Calculator display"); + const pendingDisplay = calculator.locator(".calculator-app__pending"); + const operators = [ + { name: "Add", symbol: "+" }, + { name: "Subtract", symbol: "−" }, + { name: "Multiply", symbol: "×" }, + { name: "Divide", symbol: "÷" }, + ] as const; + + await expect(calculator).not.toContainText("SHADOW / CALCULATOR"); + await expect(calculator).not.toContainText("4-OP"); + + for (const operator of operators) { + await pressKeys(page, ["Clear", "1", "2", operator.name]); + await expect(pendingDisplay).toHaveText(`12 ${operator.symbol}`); + await expect(calculator.getByRole("button", { name: operator.name })).toHaveAttribute( + "aria-pressed", + "true", + ); + } + + await pressKeys(page, ["Clear", "1", "2", "Add"]); + const add = calculator.getByRole("button", { name: "Add" }); + const multiply = calculator.getByRole("button", { name: "Multiply" }); + await multiply.click(); + await expect(display).toHaveText("12"); + await expect(pendingDisplay).toHaveText("12 ×"); + await expect(add).toHaveAttribute("aria-pressed", "false"); + await expect(multiply).toHaveAttribute("aria-pressed", "true"); + + await pressKeys(page, ["2", "0"]); + await expect(display).toHaveText("20"); + await expect(pendingDisplay).toHaveText("12 ×"); + await calculator.getByRole("button", { name: "Equals" }).click(); + await expect(display).toHaveText("240"); + await expect(pendingDisplay).toBeEmpty(); + await expect(multiply).toHaveAttribute("aria-pressed", "false"); + + await pressKeys(page, ["1", "2", "Subtract", "Clear"]); + await expect(pendingDisplay).toBeEmpty(); + await expect(calculator.getByRole("button", { name: "Subtract" })).toHaveAttribute( + "aria-pressed", + "false", + ); + + await pressKeys(page, ["9", "Divide", "0", "Equals"]); + await expect(display).toHaveText("ERROR"); + await expect(pendingDisplay).toBeEmpty(); + await expect(calculator.getByRole("button", { name: "Divide" })).toHaveAttribute( + "aria-pressed", + "false", + ); + expect(failures).toEqual([]); +}); + +test("supports calculator keyboard input, restart, and the mobile viewport", async ({ page }) => { + const failures = monitorPageFailures(page); + await page.setViewportSize({ width: 360, height: 740 }); + await page.goto("/"); + await page.getByRole("button", { name: "Skip boot sequence" }).click(); + await launchCalculator(page); + + const calculator = page.getByRole("dialog", { name: "Calculator" }); + const surface = calculator.locator(".calculator-app"); + const display = calculator.getByLabel("Calculator display"); + const pendingDisplay = calculator.locator(".calculator-app__pending"); + await expect(surface).toBeFocused(); + + await page.keyboard.type("12+"); + await expect(pendingDisplay).toHaveText("12 +"); + await expect(calculator.getByRole("button", { name: "Add" })).toHaveAttribute( + "aria-pressed", + "true", + ); + await page.keyboard.type("5"); + await page.keyboard.press("Enter"); + await expect(display).toHaveText("17"); + await expect(pendingDisplay).toBeEmpty(); + + await page.keyboard.press("Escape"); + await expect(display).toHaveText("0"); + await expect(calculator).toBeVisible(); + + await page.keyboard.type("9/0="); + await expect(display).toHaveText("ERROR"); + await page.keyboard.press("c"); + await expect(display).toHaveText("0"); + + const mobileBounds = await calculator.evaluate((windowElement) => { + const windowBounds = windowElement.getBoundingClientRect(); + const workAreaBounds = windowElement.parentElement!.getBoundingClientRect(); + const bounds = (rect: DOMRect): Record<"x" | "y" | "width" | "height", number> => ({ + x: rect.x, + y: rect.y, + width: rect.width, + height: rect.height, + }); + return { window: bounds(windowBounds), workArea: bounds(workAreaBounds) }; + }); + expect(mobileBounds.window).toEqual(mobileBounds.workArea); + + await page.getByRole("button", { name: "Restart SHADOW OS" }).click(); + await page.getByRole("button", { name: "Skip boot sequence" }).click(); + await launchCalculator(page); + await expect(page.getByLabel("Calculator display")).toHaveText("0"); + + const pageSize = await page.locator("body").evaluate((body) => ({ + scrollWidth: body.scrollWidth, + viewportWidth: document.documentElement.clientWidth, + })); + expect(pageSize.scrollWidth).toBeLessThanOrEqual(pageSize.viewportWidth); + expect(failures).toEqual([]); +}); diff --git a/tests/e2e/clock.spec.ts b/tests/e2e/clock.spec.ts new file mode 100644 index 0000000..d5bb484 --- /dev/null +++ b/tests/e2e/clock.spec.ts @@ -0,0 +1,190 @@ +import { expect, test, type Page } from "@playwright/test"; + +async function installTimerCounter(page: Page): Promise { + await page.addInitScript(() => { + const originalSetTimeout = window.setTimeout.bind(window); + const originalClearTimeout = window.clearTimeout.bind(window); + const activeTimers = new Set(); + + window.setTimeout = (( + handler: TimerHandler, + timeout?: number, + ...arguments_: unknown[] + ): number => { + if (typeof handler !== "function") { + const timeoutId = originalSetTimeout(handler, timeout, ...arguments_); + activeTimers.add(timeoutId); + return timeoutId; + } + + const callback = handler as (...callbackArguments: unknown[]) => void; + let timeoutId = 0; + const trackedHandler = (...callbackArguments: unknown[]): void => { + activeTimers.delete(timeoutId); + callback(...callbackArguments); + }; + timeoutId = originalSetTimeout(trackedHandler, timeout, ...arguments_); + activeTimers.add(timeoutId); + return timeoutId; + }) as typeof window.setTimeout; + + window.clearTimeout = ((timeoutId?: number): void => { + if (timeoutId !== undefined) { + activeTimers.delete(timeoutId); + } + originalClearTimeout(timeoutId); + }) as typeof window.clearTimeout; + + Object.defineProperty(window, "__afterbootActiveTimerCount", { + get: () => activeTimers.size, + }); + }); +} + +async function activeTimerCount(page: Page): Promise { + return page.evaluate( + () => + (window as unknown as Window & { readonly __afterbootActiveTimerCount: number }) + .__afterbootActiveTimerCount, + ); +} + +function monitorPageFailures(page: Page): string[] { + const failures: string[] = []; + page.on("console", (message) => { + if (message.type() === "error") { + failures.push(`console: ${message.text()}`); + } + }); + page.on("pageerror", (error) => failures.push(`page: ${error.message}`)); + page.on("requestfailed", (request) => { + failures.push(`request: ${request.url()} ${request.failure()?.errorText ?? "unknown failure"}`); + }); + return failures; +} + +async function openDesktop(page: Page): Promise { + const failures = monitorPageFailures(page); + await page.goto("/"); + await page.getByRole("button", { name: "Skip boot sequence" }).click(); + await expect(page.getByRole("heading", { name: "Desktop ready" })).toBeVisible(); + return failures; +} + +async function launchClock(page: Page): Promise { + await page.getByRole("button", { name: "Applications" }).click(); + const drawer = page.getByRole("dialog", { name: "Applications" }); + const clockEntry = drawer.getByRole("button", { name: "Clock" }); + await expect(clockEntry).toBeVisible(); + await clockEntry.click(); + await expect(page.getByRole("dialog", { name: "Clock" })).toBeVisible(); +} + +test("displays and updates the injected local time through one Clock instance", async ({ + page, +}) => { + await installTimerCounter(page); + const failures = await openDesktop(page); + const baselineTimers = await activeTimerCount(page); + await launchClock(page); + + const clockWindow = page.getByRole("dialog", { name: "Clock" }); + const time = clockWindow.locator(".clock-app__time"); + const date = clockWindow.locator(".clock-app__date"); + const task = page.getByRole("button", { name: "Focus Clock" }); + const initialIso = await time.getAttribute("datetime"); + expect(initialIso).not.toBeNull(); + + const expected = await page.evaluate((timestamp) => { + const value = new Date(timestamp!); + const pad = (part: number): string => part.toString().padStart(2, "0"); + return { + time: `${pad(value.getHours())}:${pad(value.getMinutes())}:${pad(value.getSeconds())}`, + date: `${value.getFullYear()}.${pad(value.getMonth() + 1)}.${pad(value.getDate())}`, + }; + }, initialIso); + + await expect(time).toHaveText(expected.time); + await expect(date).toHaveText(expected.date); + await expect(time).toHaveAttribute("aria-label", `Current time: ${expected.time}`); + await expect(date).toHaveAttribute("aria-label", `Current date: ${expected.date}`); + await expect(task).toHaveCount(1); + expect(await activeTimerCount(page)).toBe(baselineTimers + 1); + + await expect.poll(() => time.getAttribute("datetime"), { timeout: 2_500 }).not.toBe(initialIso); + + await launchClock(page); + await expect(page.getByRole("dialog", { name: "Clock" })).toHaveCount(1); + await expect(task).toHaveCount(1); + expect(await activeTimerCount(page)).toBe(baselineTimers + 1); + + await clockWindow.getByRole("button", { name: "Minimize window" }).click(); + await expect(clockWindow).toBeHidden(); + expect(await activeTimerCount(page)).toBe(baselineTimers + 1); + await page.getByRole("button", { name: "Restore Clock" }).click(); + await expect(clockWindow).toBeVisible(); + + await clockWindow.getByRole("button", { name: "Close window" }).click(); + await expect(clockWindow).toHaveCount(0); + await expect(task).toHaveCount(0); + expect(await activeTimerCount(page)).toBe(baselineTimers); + + await launchClock(page); + await expect(page.getByRole("dialog", { name: "Clock" })).toHaveCount(1); + await expect(page.getByRole("dialog", { name: "Clock" }).locator(".clock-app__time")).toHaveText( + /^\d{2}:\d{2}:\d{2}$/, + ); + expect(await activeTimerCount(page)).toBe(baselineTimers + 1); + expect(failures).toEqual([]); +}); + +test("keeps Clock contained and restart-safe at the mobile viewport", async ({ page }) => { + const failures = monitorPageFailures(page); + await page.setViewportSize({ width: 360, height: 740 }); + await page.goto("/"); + await page.getByRole("button", { name: "Skip boot sequence" }).click(); + await launchClock(page); + + const clockWindow = page.getByRole("dialog", { name: "Clock" }); + const time = clockWindow.locator(".clock-app__time"); + const date = clockWindow.locator(".clock-app__date"); + await expect(time).toHaveText(/^\d{2}:\d{2}:\d{2}$/); + await expect(date).toHaveText(/^\d{4}\.\d{2}\.\d{2}$/); + + const mobileBounds = await clockWindow.evaluate((windowElement) => { + const windowBounds = windowElement.getBoundingClientRect(); + const workAreaBounds = windowElement.parentElement!.getBoundingClientRect(); + const timeBounds = windowElement.querySelector(".clock-app__time")!.getBoundingClientRect(); + const bounds = (rect: DOMRect): Record<"x" | "y" | "width" | "height", number> => ({ + x: rect.x, + y: rect.y, + width: rect.width, + height: rect.height, + }); + return { + window: bounds(windowBounds), + workArea: bounds(workAreaBounds), + time: bounds(timeBounds), + }; + }); + expect(mobileBounds.window).toEqual(mobileBounds.workArea); + expect(mobileBounds.time.x).toBeGreaterThanOrEqual(mobileBounds.window.x); + expect(mobileBounds.time.x + mobileBounds.time.width).toBeLessThanOrEqual( + mobileBounds.window.x + mobileBounds.window.width, + ); + + await page.getByRole("button", { name: "Restart SHADOW OS" }).click(); + await page.getByRole("button", { name: "Skip boot sequence" }).click(); + await expect(page.getByRole("dialog", { name: "Clock" })).toHaveCount(0); + await launchClock(page); + await expect(page.getByRole("dialog", { name: "Clock" }).locator(".clock-app__time")).toHaveText( + /^\d{2}:\d{2}:\d{2}$/, + ); + + const pageSize = await page.locator("body").evaluate((body) => ({ + scrollWidth: body.scrollWidth, + viewportWidth: document.documentElement.clientWidth, + })); + expect(pageSize.scrollWidth).toBeLessThanOrEqual(pageSize.viewportWidth); + expect(failures).toEqual([]); +}); diff --git a/tests/e2e/notepad.spec.ts b/tests/e2e/notepad.spec.ts new file mode 100644 index 0000000..9668f1a --- /dev/null +++ b/tests/e2e/notepad.spec.ts @@ -0,0 +1,153 @@ +import { expect, test, type Page } from "@playwright/test"; + +function monitorPageFailures(page: Page): string[] { + const failures: string[] = []; + page.on("console", (message) => { + if (message.type() === "error") { + failures.push(`console: ${message.text()}`); + } + }); + page.on("pageerror", (error) => failures.push(`page: ${error.message}`)); + page.on("requestfailed", (request) => { + failures.push(`request: ${request.url()} ${request.failure()?.errorText ?? "unknown failure"}`); + }); + return failures; +} + +async function openDesktop(page: Page): Promise { + const failures = monitorPageFailures(page); + await page.goto("/"); + await page.getByRole("button", { name: "Skip boot sequence" }).click(); + await expect(page.getByRole("heading", { name: "Desktop ready" })).toBeVisible(); + return failures; +} + +async function launchNotepad(page: Page): Promise { + await page.getByRole("button", { name: "Applications" }).click(); + const drawer = page.getByRole("dialog", { name: "Applications" }); + const notesEntry = drawer.getByRole("button", { name: "Notes" }); + const marker = notesEntry.locator(".application-drawer__marker"); + const icon = marker.locator("svg.application-drawer__notes-icon"); + await expect(notesEntry).toBeVisible(); + await expect(marker).toHaveAttribute("aria-hidden", "true"); + await expect(marker).toBeEmpty(); + await expect(icon).toBeVisible(); + await expect(icon).toHaveAttribute("viewBox", "0 0 32 32"); + await expect(icon).toHaveAttribute("aria-hidden", "true"); + await notesEntry.click(); + await expect(page.getByRole("dialog", { name: "Notes" })).toBeVisible(); +} + +test("edits temporary text through one running Notepad instance", async ({ page }) => { + const failures = await openDesktop(page); + await launchNotepad(page); + + const notepad = page.getByRole("dialog", { name: "Notes" }); + const editor = page.getByRole("textbox", { name: "Notes editor" }); + const task = page.getByRole("button", { name: "Focus Notes" }); + await expect(editor).toBeFocused(); + await expect(task).toHaveCount(1); + + await page.keyboard.insertText("First line\nSecond line"); + await expect(editor).toHaveValue("First line\nSecond line"); + await page.keyboard.press("Control+A"); + await page.keyboard.insertText("Revised text\nWith two lines"); + await expect(editor).toHaveValue("Revised text\nWith two lines"); + await page.keyboard.press("Escape"); + await expect(editor).toHaveValue("Revised text\nWith two lines"); + + await launchNotepad(page); + await expect(page.getByRole("dialog", { name: "Notes" })).toHaveCount(1); + await expect(task).toHaveCount(1); + await expect(editor).toHaveValue("Revised text\nWith two lines"); + + const titleBar = notepad.locator(".os-window__titlebar"); + const initialBounds = await notepad.boundingBox(); + const titleBounds = await titleBar.boundingBox(); + expect(initialBounds).not.toBeNull(); + expect(titleBounds).not.toBeNull(); + await page.mouse.move(titleBounds!.x + 80, titleBounds!.y + 20); + await page.mouse.down(); + await page.mouse.move(titleBounds!.x + 130, titleBounds!.y + 55, { steps: 3 }); + await page.mouse.up(); + expect((await notepad.boundingBox())!.x).toBeGreaterThan(initialBounds!.x + 30); + + const resizeHandle = notepad.locator(".os-window__resize-handle"); + const handleBounds = await resizeHandle.boundingBox(); + expect(handleBounds).not.toBeNull(); + await page.mouse.move(handleBounds!.x + 8, handleBounds!.y + 8); + await page.mouse.down(); + await page.mouse.move(handleBounds!.x + 68, handleBounds!.y + 48, { steps: 3 }); + await page.mouse.up(); + await expect(editor).toHaveValue("Revised text\nWith two lines"); + + const desktop = page.getByLabel("SHADOW OS desktop work area"); + await desktop.focus(); + await page.keyboard.press("Shift+F10"); + await page.getByRole("menuitem", { name: "Refresh Desktop" }).click(); + await expect(editor).toHaveValue("Revised text\nWith two lines"); + + await notepad.getByRole("button", { name: "Minimize window" }).click(); + await expect(notepad).toBeHidden(); + await page.getByRole("button", { name: "Restore Notes" }).click(); + await expect(notepad).toBeVisible(); + await expect(editor).toHaveValue("Revised text\nWith two lines"); + + await notepad.getByRole("button", { name: "Maximize window" }).click(); + await expect(notepad).toHaveAttribute("data-mode", "maximized"); + await notepad.getByRole("button", { name: "Restore window" }).click(); + await expect(notepad).toHaveAttribute("data-mode", "normal"); + await expect(editor).toHaveValue("Revised text\nWith two lines"); + + const nativeContextMenu = await editor.evaluate((surface) => { + const event = new MouseEvent("contextmenu", { bubbles: true, cancelable: true }); + surface.dispatchEvent(event); + return !event.defaultPrevented; + }); + expect(nativeContextMenu).toBe(true); + + await notepad.getByRole("button", { name: "Close window" }).click(); + await expect(notepad).toHaveCount(0); + await expect(task).toHaveCount(0); + + await launchNotepad(page); + await expect(page.getByRole("textbox", { name: "Notes editor" })).toBeFocused(); + await expect(page.getByRole("textbox", { name: "Notes editor" })).toHaveValue(""); + expect(failures).toEqual([]); +}); + +test("discards Notepad text on restart and remains usable on mobile", async ({ page }) => { + const failures = monitorPageFailures(page); + await page.setViewportSize({ width: 360, height: 740 }); + await page.goto("/"); + await page.getByRole("button", { name: "Skip boot sequence" }).click(); + await launchNotepad(page); + + const editor = page.getByRole("textbox", { name: "Notes editor" }); + await editor.fill("Temporary mobile text"); + await expect(editor).toHaveValue("Temporary mobile text"); + const mobileBounds = await page.getByRole("dialog", { name: "Notes" }).evaluate((notepad) => { + const windowBounds = notepad.getBoundingClientRect(); + const workAreaBounds = notepad.parentElement!.getBoundingClientRect(); + const bounds = (rect: DOMRect): Record<"x" | "y" | "width" | "height", number> => ({ + x: rect.x, + y: rect.y, + width: rect.width, + height: rect.height, + }); + return { window: bounds(windowBounds), workArea: bounds(workAreaBounds) }; + }); + expect(mobileBounds.window).toEqual(mobileBounds.workArea); + + await page.getByRole("button", { name: "Restart SHADOW OS" }).click(); + await page.getByRole("button", { name: "Skip boot sequence" }).click(); + await launchNotepad(page); + await expect(page.getByRole("textbox", { name: "Notes editor" })).toHaveValue(""); + + const pageSize = await page.locator("body").evaluate((body) => ({ + scrollWidth: body.scrollWidth, + viewportWidth: document.documentElement.clientWidth, + })); + expect(pageSize.scrollWidth).toBeLessThanOrEqual(pageSize.viewportWidth); + expect(failures).toEqual([]); +}); diff --git a/tests/e2e/shell-foundation.spec.ts b/tests/e2e/shell-foundation.spec.ts new file mode 100644 index 0000000..630316f --- /dev/null +++ b/tests/e2e/shell-foundation.spec.ts @@ -0,0 +1,143 @@ +import { expect, test, type Page } from "@playwright/test"; + +function monitorPageFailures(page: Page): string[] { + const failures: string[] = []; + page.on("console", (message) => { + if (message.type() === "error") { + failures.push(`console: ${message.text()}`); + } + }); + page.on("pageerror", (error) => failures.push(`page: ${error.message}`)); + page.on("requestfailed", (request) => { + failures.push(`request: ${request.url()} ${request.failure()?.errorText ?? "unknown failure"}`); + }); + return failures; +} + +async function openDesktop(page: Page): Promise { + const failures = monitorPageFailures(page); + await page.goto("/"); + await page.getByRole("button", { name: "Skip boot sequence" }).click(); + await expect(page.getByRole("heading", { name: "Desktop ready" })).toBeVisible(); + return failures; +} + +async function openDrawer(page: Page): Promise { + await page.getByRole("button", { name: "Applications" }).click(); + await expect(page.getByRole("dialog", { name: "Applications" })).toBeVisible(); +} + +async function launchDiagnostics(page: Page): Promise { + await openDrawer(page); + await page + .getByRole("dialog", { name: "Applications" }) + .getByRole("button", { name: /System Diagnostics/ }) + .click(); + await expect(page.getByRole("dialog", { name: "System Diagnostics" })).toBeVisible(); +} + +test("discovers applications in the drawer while the task strip tracks running windows", async ({ + page, +}) => { + const failures = await openDesktop(page); + const trigger = page.getByRole("button", { name: "Applications" }); + const taskStrip = page.getByRole("navigation", { name: "Open windows" }); + + await expect(taskStrip.getByRole("button")).toHaveCount(0); + await trigger.focus(); + await page.keyboard.press("Enter"); + const drawer = page.getByRole("dialog", { name: "Applications" }); + const diagnostics = drawer.getByRole("button", { name: /System Diagnostics/ }); + await expect(diagnostics).toBeFocused(); + + await page.keyboard.press("Escape"); + await expect(drawer).toBeHidden(); + await expect(trigger).toBeFocused(); + + await openDrawer(page); + await page.locator(".system-header").click(); + await expect(drawer).toBeHidden(); + + await launchDiagnostics(page); + await expect(taskStrip.getByRole("button", { name: "Focus System Diagnostics" })).toHaveCount(1); + expect(failures).toEqual([]); +}); + +test("provides a scoped keyboard-accessible desktop context menu", async ({ page }) => { + const failures = await openDesktop(page); + const desktop = page.getByLabel("SHADOW OS desktop work area"); + + const desktopPrevented = await desktop.evaluate((surface) => { + const event = new MouseEvent("contextmenu", { + bubbles: true, + cancelable: true, + clientX: 40, + clientY: 40, + }); + surface.dispatchEvent(event); + return event.defaultPrevented; + }); + expect(desktopPrevented).toBe(true); + const menu = page.getByRole("menu", { name: "Desktop actions" }); + await expect(menu).toBeVisible(); + await expect(menu.getByRole("menuitem", { name: "Refresh Desktop" })).toBeFocused(); + + await page.keyboard.press("Escape"); + await expect(menu).toBeHidden(); + + await desktop.focus(); + await page.keyboard.press("Shift+F10"); + await expect(menu).toBeVisible(); + await page.keyboard.press("ArrowDown"); + await expect(menu.getByRole("menuitem", { name: "Applications" })).toBeFocused(); + await page.keyboard.press("Enter"); + const drawer = page.getByRole("dialog", { name: "Applications" }); + await expect(drawer).toBeVisible(); + + await drawer.getByRole("button", { name: /System Diagnostics/ }).click(); + await expect(page.getByRole("dialog", { name: "System Diagnostics" })).toBeVisible(); + const applicationPrevented = await page.locator(".diagnostics-app").evaluate((surface) => { + const event = new MouseEvent("contextmenu", { bubbles: true, cancelable: true }); + surface.dispatchEvent(event); + return event.defaultPrevented; + }); + expect(applicationPrevented).toBe(false); + expect(failures).toEqual([]); +}); + +test("refreshes desktop presentation without navigation or application loss", async ({ page }) => { + const failures = await openDesktop(page); + await launchDiagnostics(page); + const primary = page.getByRole("dialog", { name: "System Diagnostics" }); + await primary.getByRole("button", { name: "Open lifecycle detail" }).click(); + const detail = page.getByRole("dialog", { name: "Lifecycle Detail 01" }); + await detail.getByRole("button", { name: "Maximize window" }).click(); + const primaryBounds = await primary.boundingBox(); + const detailBounds = await detail.boundingBox(); + await page.evaluate(() => { + document.documentElement.dataset.refreshSentinel = "present"; + }); + + const desktop = page.getByLabel("SHADOW OS desktop work area"); + await desktop.focus(); + await page.keyboard.press("Shift+F10"); + await page.getByRole("menuitem", { name: "Refresh Desktop" }).click(); + + await expect(page.getByText("Desktop refreshed 1")).toHaveText("Desktop refreshed 1"); + await expect(page.getByText("ENVIRONMENT / CYCLE 01")).toBeVisible(); + await expect(page.getByRole("dialog")).toHaveCount(2); + await expect(detail).toHaveAttribute("data-mode", "maximized"); + await expect(detail).toHaveAttribute("data-active", "true"); + expect(await primary.boundingBox()).toEqual(primaryBounds); + expect(await detail.boundingBox()).toEqual(detailBounds); + expect(await page.evaluate(() => document.documentElement.dataset.refreshSentinel)).toBe( + "present", + ); + + await desktop.focus(); + await page.keyboard.press("Shift+F10"); + await expect(page.getByRole("menu", { name: "Desktop actions" })).toBeVisible(); + await page.locator(".system-header").click(); + await expect(page.getByRole("menu", { name: "Desktop actions" })).toBeHidden(); + expect(failures).toEqual([]); +}); diff --git a/tests/e2e/windows-applications.spec.ts b/tests/e2e/windows-applications.spec.ts index b8037ed..9334095 100644 --- a/tests/e2e/windows-applications.spec.ts +++ b/tests/e2e/windows-applications.spec.ts @@ -23,8 +23,17 @@ async function openDesktop(page: Page): Promise { return failures; } +async function openAppDrawer(page: Page): Promise { + await page.getByRole("button", { name: "Applications" }).click(); + await expect(page.getByRole("dialog", { name: "Applications" })).toBeVisible(); +} + async function launchDiagnostics(page: Page): Promise { - await page.getByRole("button", { name: "System Diagnostics" }).click(); + await openAppDrawer(page); + await page + .getByRole("dialog", { name: "Applications" }) + .getByRole("button", { name: /System Diagnostics/ }) + .click(); await expect(page.getByRole("dialog", { name: "System Diagnostics" })).toBeVisible(); } @@ -32,14 +41,12 @@ test("launches one application instance and coordinates multiple owned windows", page, }) => { const failures = await openDesktop(page); - const launcher = page.getByRole("button", { name: "System Diagnostics", exact: true }); - - await launcher.click(); + await launchDiagnostics(page); const primary = page.getByRole("dialog", { name: "System Diagnostics" }); await expect(primary).toBeVisible(); await expect(primary).toContainText("application-instance-1"); - await launcher.click(); + await launchDiagnostics(page); await expect(page.getByRole("dialog")).toHaveCount(1); await expect(primary).toHaveAttribute("data-active", "true"); @@ -105,15 +112,21 @@ test("minimizes, restores, maximizes, restores, and closes a window", async ({ p await dialog.getByRole("button", { name: "Close window" }).click(); await expect(dialog).toHaveCount(0); - await expect(page.getByRole("button", { name: "System Diagnostics" })).toBeFocused(); + await expect(page.getByRole("button", { name: "Applications" })).toBeFocused(); expect(failures).toEqual([]); }); test("supports keyboard launch and window controls without global shortcuts", async ({ page }) => { const failures = await openDesktop(page); - const launcher = page.getByRole("button", { name: "System Diagnostics" }); + const launcher = page.getByRole("button", { name: "Applications" }); await launcher.focus(); await page.keyboard.press("Enter"); + await expect( + page + .getByRole("dialog", { name: "Applications" }) + .getByRole("button", { name: /System Diagnostics/ }), + ).toBeFocused(); + await page.keyboard.press("Enter"); const dialog = page.getByRole("dialog", { name: "System Diagnostics" }); await expect(dialog).toBeFocused(); diff --git a/tests/integration/application-window-lifecycle.test.ts b/tests/integration/application-window-lifecycle.test.ts index 3e95e1f..ad5c436 100644 --- a/tests/integration/application-window-lifecycle.test.ts +++ b/tests/integration/application-window-lifecycle.test.ts @@ -1,13 +1,139 @@ import { describe, expect, it, vi } from "vitest"; +import { + CALCULATOR_APPLICATION_ID, + createCalculatorDefinition, +} from "../../src/applications/built-in/calculator"; +import { CLOCK_APPLICATION_ID, createClockDefinition } from "../../src/applications/built-in/clock"; +import { + createNotepadDefinition, + NOTEPAD_APPLICATION_ID, +} from "../../src/applications/built-in/notepad"; import type { ApplicationContext } from "../../src/applications/framework/application"; import { ApplicationManager } from "../../src/applications/framework/application-manager"; import { ApplicationRegistry } from "../../src/applications/framework/application-registry"; import { toApplicationId } from "../../src/core/identity/identifiers"; import { WindowManager } from "../../src/shell/windows/window-manager"; import { FakeIdGenerator } from "../helpers/fake-id-generator"; +import { FakeClock } from "../helpers/fake-clock"; describe("application and window lifecycle", () => { + it("registers Clock and gives closed or reset launches fresh instances", () => { + const registry = new ApplicationRegistry([createClockDefinition(new FakeClock())]); + const ids = new FakeIdGenerator(); + const windows = new WindowManager(ids, { x: 0, y: 0, width: 1000, height: 700 }); + const applications = new ApplicationManager(registry, windows, ids); + + expect(registry.list().map((manifest) => manifest.name)).toEqual(["Clock"]); + + const firstInstanceId = applications.launch(CLOCK_APPLICATION_ID); + const firstWindowId = applications.snapshot.instances[0]!.primaryWindowId; + + expect(applications.launch(CLOCK_APPLICATION_ID)).toBe(firstInstanceId); + expect(applications.snapshot.instances).toHaveLength(1); + expect(windows.snapshot.windows[0]).toMatchObject({ id: firstWindowId, title: "Clock" }); + + expect(applications.closeWindow(firstWindowId)).toBe(true); + expect(applications.snapshot.instances).toEqual([]); + expect(windows.snapshot.windows).toEqual([]); + + const secondInstanceId = applications.launch(CLOCK_APPLICATION_ID); + expect(secondInstanceId).not.toBe(firstInstanceId); + + applications.reset(); + expect(applications.snapshot.instances).toEqual([]); + expect(windows.snapshot.windows).toEqual([]); + }); + + it("registers Calculator and gives closed or reset launches fresh instances", () => { + const registry = new ApplicationRegistry([createCalculatorDefinition()]); + const ids = new FakeIdGenerator(); + const windows = new WindowManager(ids, { x: 0, y: 0, width: 1000, height: 700 }); + const applications = new ApplicationManager(registry, windows, ids); + + expect(registry.list().map((manifest) => manifest.name)).toEqual(["Calculator"]); + + const firstInstanceId = applications.launch(CALCULATOR_APPLICATION_ID); + const firstWindowId = applications.snapshot.instances[0]!.primaryWindowId; + + expect(applications.launch(CALCULATOR_APPLICATION_ID)).toBe(firstInstanceId); + expect(applications.snapshot.instances).toHaveLength(1); + expect(windows.snapshot.windows[0]).toMatchObject({ + id: firstWindowId, + title: "Calculator", + }); + + expect(applications.closeWindow(firstWindowId)).toBe(true); + expect(applications.snapshot.instances).toEqual([]); + expect(windows.snapshot.windows).toEqual([]); + + const secondInstanceId = applications.launch(CALCULATOR_APPLICATION_ID); + expect(secondInstanceId).not.toBe(firstInstanceId); + + applications.reset(); + expect(applications.snapshot.instances).toEqual([]); + expect(windows.snapshot.windows).toEqual([]); + }); + + it("registers Notepad and gives each closed or reset lifecycle a fresh instance", () => { + const registry = new ApplicationRegistry([createNotepadDefinition()]); + const ids = new FakeIdGenerator(); + const windows = new WindowManager(ids, { x: 0, y: 0, width: 1000, height: 700 }); + const applications = new ApplicationManager(registry, windows, ids); + + expect(registry.list().map((manifest) => manifest.name)).toEqual(["Notes"]); + + const firstInstanceId = applications.launch(NOTEPAD_APPLICATION_ID); + const firstWindowId = applications.snapshot.instances[0]!.primaryWindowId; + + expect(applications.launch(NOTEPAD_APPLICATION_ID)).toBe(firstInstanceId); + expect(applications.snapshot.instances).toHaveLength(1); + expect(windows.snapshot.windows[0]).toMatchObject({ + id: firstWindowId, + title: "Notes", + }); + + expect(applications.closeWindow(firstWindowId)).toBe(true); + expect(applications.snapshot.instances).toEqual([]); + expect(windows.snapshot.windows).toEqual([]); + + const secondInstanceId = applications.launch(NOTEPAD_APPLICATION_ID); + expect(secondInstanceId).not.toBe(firstInstanceId); + + applications.reset(); + expect(applications.snapshot.instances).toEqual([]); + expect(windows.snapshot.windows).toEqual([]); + }); + + it("launches the registry catalog through the manager without duplicating an instance", () => { + const applicationId = toApplicationId("system.diagnostics"); + const registry = new ApplicationRegistry([ + { + manifest: { + id: applicationId, + name: "System Diagnostics", + description: "Inspect the M2 application contract.", + window: { title: "System Diagnostics" }, + }, + create: () => ({ + primaryView: { mount: () => () => undefined }, + dispose: () => undefined, + }), + }, + ]); + const ids = new FakeIdGenerator(); + const windows = new WindowManager(ids, { x: 0, y: 0, width: 1000, height: 700 }); + const applications = new ApplicationManager(registry, windows, ids); + const installedApplicationId = registry.list()[0]!.id; + + expect(windows.snapshot.windows).toEqual([]); + const instanceId = applications.launch(installedApplicationId); + + expect(applications.launch(installedApplicationId)).toBe(instanceId); + expect(applications.snapshot.instances).toHaveLength(1); + expect(windows.snapshot.windows).toHaveLength(1); + }); + it("coordinates startup registration, launch, multiple windows, relaunch, and close", () => { const applicationId = toApplicationId("system.diagnostics"); const dispose = vi.fn(); diff --git a/tests/unit/calculator-model.test.ts b/tests/unit/calculator-model.test.ts new file mode 100644 index 0000000..2129294 --- /dev/null +++ b/tests/unit/calculator-model.test.ts @@ -0,0 +1,201 @@ +import { describe, expect, it } from "vitest"; + +import { + CalculatorModel, + type CalculatorOperator, +} from "../../src/applications/built-in/calculator-model"; + +function enter(model: CalculatorModel, value: string): void { + for (const character of value) { + if (character === ".") { + model.inputDecimal(); + } else { + model.inputDigit(character); + } + } +} + +function calculate(left: string, operator: CalculatorOperator, right: string): CalculatorModel { + const model = new CalculatorModel(); + enter(model, left); + model.chooseOperator(operator); + enter(model, right); + model.equals(); + return model; +} + +describe("CalculatorModel", () => { + it("starts at zero and accepts multi-digit input", () => { + const model = new CalculatorModel(); + + expect(model.display).toBe("0"); + expect(model.hasError).toBe(false); + expect(model.pendingOperation).toBeNull(); + + enter(model, "1205"); + expect(model.display).toBe("1205"); + }); + + it("accepts one decimal point and normalizes leading decimals", () => { + const model = new CalculatorModel(); + + enter(model, ".125.5"); + + expect(model.display).toBe("0.1255"); + }); + + it.each([ + ["addition", "add", "12", "5", "17"], + ["subtraction", "subtract", "12", "5", "7"], + ["multiplication", "multiply", "12", "5", "60"], + ["division", "divide", "12", "5", "2.4"], + ] as const)("performs %s", (_name, operator, left, right, expected) => { + expect(calculate(left, operator, right).display).toBe(expected); + }); + + it("evaluates chained operations immediately from left to right", () => { + const model = new CalculatorModel(); + enter(model, "12"); + model.chooseOperator("add"); + enter(model, "5"); + model.chooseOperator("multiply"); + enter(model, "2"); + model.equals(); + + expect(model.display).toBe("34"); + }); + + it("produces negative results", () => { + expect(calculate("5", "subtract", "12").display).toBe("-7"); + }); + + it("clears all calculation state", () => { + const model = calculate("9", "add", "4"); + + model.clear(); + model.inputDigit("2"); + model.equals(); + + expect(model.display).toBe("2"); + expect(model.hasError).toBe(false); + }); + + it("backspaces only the current input", () => { + const model = new CalculatorModel(); + enter(model, "123"); + + model.backspace(); + expect(model.display).toBe("12"); + model.backspace(); + model.backspace(); + expect(model.display).toBe("0"); + }); + + it("replaces a pending operator deterministically", () => { + const model = new CalculatorModel(); + enter(model, "8"); + model.chooseOperator("add"); + model.chooseOperator("multiply"); + enter(model, "3"); + model.equals(); + + expect(model.display).toBe("24"); + }); + + it.each([ + ["add", "12"], + ["subtract", "12"], + ["multiply", "12"], + ["divide", "12"], + ] as const)("exposes the stored operand and pending %s operation", (operator, operand) => { + const model = new CalculatorModel(); + enter(model, operand); + + model.chooseOperator(operator); + + expect(model.pendingOperation).toEqual({ operand, operator }); + }); + + it("projects operator replacement without evaluating prematurely", () => { + const model = new CalculatorModel(); + enter(model, "12"); + model.chooseOperator("add"); + + model.chooseOperator("multiply"); + + expect(model.display).toBe("12"); + expect(model.pendingOperation).toEqual({ operand: "12", operator: "multiply" }); + }); + + it("clears the pending projection on clear, equals, and errors", () => { + const model = new CalculatorModel(); + enter(model, "12"); + model.chooseOperator("add"); + model.clear(); + expect(model.pendingOperation).toBeNull(); + + enter(model, "12"); + model.chooseOperator("add"); + enter(model, "5"); + model.equals(); + expect(model.pendingOperation).toBeNull(); + + model.clear(); + enter(model, "9"); + model.chooseOperator("divide"); + enter(model, "0"); + model.equals(); + expect(model.pendingOperation).toBeNull(); + }); + + it("repeats the last equals operation", () => { + const model = calculate("2", "add", "3"); + + model.equals(); + expect(model.display).toBe("8"); + model.equals(); + expect(model.display).toBe("11"); + }); + + it("enters an error state on division by zero and recovers with numeric input", () => { + const model = calculate("9", "divide", "0"); + + expect(model.display).toBe("ERROR"); + expect(model.hasError).toBe(true); + + model.inputDigit("4"); + expect(model.display).toBe("4"); + expect(model.hasError).toBe(false); + }); + + it("recovers from an error through clear", () => { + const model = calculate("1", "divide", "0"); + + model.clear(); + + expect(model.display).toBe("0"); + expect(model.hasError).toBe(false); + }); + + it("caps direct input and formats large results without overflowing the display", () => { + const model = new CalculatorModel(); + enter(model, "123456789012345"); + expect(model.display).toBe("123456789012"); + + model.chooseOperator("multiply"); + enter(model, "999999999999"); + model.equals(); + + expect(model.display.length).toBeLessThanOrEqual(16); + expect(model.display).toMatch(/e\+/); + }); + + it("clears temporary state when disposed", () => { + const model = calculate("7", "multiply", "6"); + + model.dispose(); + + expect(model.display).toBe("0"); + expect(model.hasError).toBe(false); + }); +}); diff --git a/tests/unit/clock-model.test.ts b/tests/unit/clock-model.test.ts new file mode 100644 index 0000000..33c8fb0 --- /dev/null +++ b/tests/unit/clock-model.test.ts @@ -0,0 +1,108 @@ +import { describe, expect, it, vi } from "vitest"; + +import { ClockModel } from "../../src/applications/built-in/clock-model"; +import { FakeClock } from "../helpers/fake-clock"; + +describe("ClockModel", () => { + it("formats the injected time deterministically", () => { + const timestamp = new Date(2042, 6, 9, 4, 5, 6).getTime(); + const model = new ClockModel(new FakeClock(timestamp)); + + expect(model.snapshot).toEqual({ + iso: new Date(timestamp).toISOString(), + time: "04:05:06", + date: "2042.07.09", + }); + }); + + it("aligns updates to second boundaries and keeps one scheduled tick", () => { + const timestamp = new Date(2042, 6, 9, 4, 5, 6, 250).getTime(); + const clock = new FakeClock(timestamp); + const model = new ClockModel(clock); + const listener = vi.fn(); + + const unsubscribe = model.subscribe(listener); + expect(clock.pendingTaskCount).toBe(1); + + clock.advanceBy(749); + expect(listener).not.toHaveBeenCalled(); + clock.advanceBy(1); + expect(listener).toHaveBeenLastCalledWith( + expect.objectContaining({ time: "04:05:07", date: "2042.07.09" }), + ); + expect(clock.pendingTaskCount).toBe(1); + + clock.advanceBy(2_000); + expect(listener).toHaveBeenCalledTimes(3); + expect(listener).toHaveBeenLastCalledWith( + expect.objectContaining({ time: "04:05:09", date: "2042.07.09" }), + ); + expect(clock.pendingTaskCount).toBe(1); + unsubscribe(); + expect(clock.pendingTaskCount).toBe(0); + }); + + it("updates the local date when the injected time crosses midnight", () => { + const timestamp = new Date(2042, 11, 31, 23, 59, 59).getTime(); + const clock = new FakeClock(timestamp); + const model = new ClockModel(clock); + const listener = vi.fn(); + const unsubscribe = model.subscribe(listener); + + clock.advanceBy(1_000); + + expect(model.snapshot).toMatchObject({ time: "00:00:00", date: "2043.01.01" }); + expect(listener).toHaveBeenLastCalledWith(model.snapshot); + unsubscribe(); + }); + + it("shares one scheduled tick across subscribers and cancels it after the last unsubscribe", () => { + const clock = new FakeClock(); + const model = new ClockModel(clock); + + const unsubscribeFirst = model.subscribe(() => undefined); + const unsubscribeSecond = model.subscribe(() => undefined); + expect(clock.pendingTaskCount).toBe(1); + + unsubscribeFirst(); + expect(clock.pendingTaskCount).toBe(1); + unsubscribeSecond(); + expect(clock.pendingTaskCount).toBe(0); + }); + + it("does not accumulate timers across dispose and reopen cycles", () => { + const clock = new FakeClock(); + const firstListener = vi.fn(); + const firstModel = new ClockModel(clock); + firstModel.subscribe(firstListener); + expect(clock.pendingTaskCount).toBe(1); + + firstModel.dispose(); + expect(clock.pendingTaskCount).toBe(0); + clock.advanceBy(2_000); + expect(firstListener).not.toHaveBeenCalled(); + + const secondListener = vi.fn(); + const secondModel = new ClockModel(clock); + secondModel.subscribe(secondListener); + expect(clock.pendingTaskCount).toBe(1); + clock.advanceBy(1_000); + expect(secondListener).toHaveBeenCalledTimes(1); + expect(clock.pendingTaskCount).toBe(1); + + secondModel.dispose(); + expect(clock.pendingTaskCount).toBe(0); + }); + + it("rejects subscriptions after disposal without scheduling work", () => { + const clock = new FakeClock(); + const model = new ClockModel(clock); + + model.dispose(); + + expect(() => model.subscribe(() => undefined)).toThrow( + "Cannot subscribe to a disposed Clock model.", + ); + expect(clock.pendingTaskCount).toBe(0); + }); +}); diff --git a/tests/unit/context-menu-model.test.ts b/tests/unit/context-menu-model.test.ts new file mode 100644 index 0000000..91f3278 --- /dev/null +++ b/tests/unit/context-menu-model.test.ts @@ -0,0 +1,42 @@ +import { describe, expect, it } from "vitest"; + +import { clampOverlayPosition } from "../../src/shell/desktop/context-menu-model"; + +describe("clampOverlayPosition", () => { + it("preserves an anchor that already fits inside the viewport", () => { + expect( + clampOverlayPosition( + { x: 120, y: 80 }, + { width: 200, height: 120 }, + { width: 800, height: 600 }, + ), + ).toEqual({ x: 120, y: 80 }); + }); + + it("keeps the overlay inside every viewport edge", () => { + expect( + clampOverlayPosition( + { x: 790, y: 590 }, + { width: 220, height: 160 }, + { width: 800, height: 600 }, + ), + ).toEqual({ x: 572, y: 432 }); + expect( + clampOverlayPosition( + { x: -40, y: -20 }, + { width: 220, height: 160 }, + { width: 800, height: 600 }, + ), + ).toEqual({ x: 8, y: 8 }); + }); + + it("uses the margin when the overlay is larger than the viewport", () => { + expect( + clampOverlayPosition( + { x: 100, y: 100 }, + { width: 500, height: 400 }, + { width: 320, height: 240 }, + ), + ).toEqual({ x: 8, y: 8 }); + }); +}); diff --git a/tests/unit/notepad-model.test.ts b/tests/unit/notepad-model.test.ts new file mode 100644 index 0000000..b0fc569 --- /dev/null +++ b/tests/unit/notepad-model.test.ts @@ -0,0 +1,26 @@ +import { describe, expect, it } from "vitest"; + +import { NotepadModel } from "../../src/applications/built-in/notepad-model"; + +describe("NotepadModel", () => { + it("starts blank and retains multiline edits for the running instance", () => { + const model = new NotepadModel(); + + expect(model.text).toBe(""); + + model.setText("First line\nSecond line"); + expect(model.text).toBe("First line\nSecond line"); + + model.setText("Revised text"); + expect(model.text).toBe("Revised text"); + }); + + it("clears its temporary text when disposed", () => { + const model = new NotepadModel(); + model.setText("Temporary session text"); + + model.dispose(); + + expect(model.text).toBe(""); + }); +});