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.", + ); + }); +});