diff --git a/docs/SESSION_RESULTS.md b/docs/SESSION_RESULTS.md index 58de7ad..3c8c482 100644 --- a/docs/SESSION_RESULTS.md +++ b/docs/SESSION_RESULTS.md @@ -680,3 +680,614 @@ Existing M1 unit, integration, and Playwright tests remain unchanged and pass as No virtual filesystem, file manager, text editor, terminal, process/task simulation, notifications, settings, persistence, accounts, networking, scenarios, backend, real machine access, dynamic application installation, multi-instance policy, global window-cycling shortcut, or keyboard move/resize behavior was introduced. No release, version tag, GitHub Release, PR, merge, or branch change was created. + +--- + +# Milestone 3 Architecture Planning Session + +- **Date:** 2026-09-27 +- **Branch:** `feature/m3-applications-os-experience` +- **Starting `develop` commit:** `0135404d61219ac1e3071123179d45911c04e44a` +- **Authoritative roadmap ref:** `origin/documentation` at `a719f3fe598ea523cdb783059677a026173f6c84` +- **Task type:** Architecture review and implementation planning only +- **Implementation status:** Not started + +## Planning Context and Scope + +The post-M2 roadmap was intentionally revised before this planning session. The authoritative documentation now defines M3 as **Applications + OS Experience**, moves the shared Virtual Filesystem to M4, and leaves M5 as Scenario Foundation. Earlier entries in this file preserve the former filesystem-first M3 plan as historical context; this entry supersedes that prospective plan without rewriting it. + +M3 is limited to: + +- a temporary in-memory Notepad; +- a basic Calculator; +- a small digital Clock; +- the existing System Diagnostics application; +- a registry-backed, keyboard-accessible Application Drawer; +- the existing task strip as a projection of open windows only; +- a SHADOW OS desktop context menu; and +- a projection-only Refresh Desktop command that does not reload or reboot the application. + +M3 explicitly excludes the Virtual Filesystem, File Manager, file saving/loading, persistent application data, Browser, Email, Image Viewer, Settings application, themes, Calendar, Tasks, Terminal, networking, accounts, backend/cloud persistence, and scenario runtime/gameplay. M4 owns the shared Virtual Filesystem and coherent filesystem-backed sandbox. + +## Documentation and Implementation Reviewed + +Documentation reviewed: + +- `README.md` +- `CHANGELOG.md` +- `docs/AFTERBOOT_PROJECT.md` +- `docs/SESSION_RESULTS.md` +- canonical `docs/AFTERBOOT_MILESTONES.md` from `origin/documentation` +- the post-M2 roadmap revisions on `origin/documentation` + +Implementation and tests reviewed: + +- composition in `src/bootstrap/start-afterboot.ts`; +- runtime/reset behavior in `src/core/runtime/shadow-runtime.ts`; +- typed events, disposables, identifiers, and the clock boundary; +- application contracts, registry, and manager; +- `WindowManager` and `WindowLayerView`; +- `ShellView`, `DesktopView`, launcher, task strip, system clock, and responsive styles; +- the existing System Diagnostics application; and +- M0-M2 unit, integration, and Playwright coverage. + +## Existing Architecture Assessment + +The M2 architecture is sufficient for M3 without a framework rewrite or a second catalog: + +- `ApplicationRegistry` already owns the immutable startup catalog and exposes ordered manifests through `list()`. +- `ApplicationManager` already owns single-instance launch, focus/restore-on-relaunch, application instances, primary and auxiliary windows, reset, and disposal. +- `WindowManager` remains the only authority for window geometry, modes, z-order, focus, and work-area constraints. +- `WindowLayerView` already mounts application views by stable window identity and translates DOM interaction into manager commands. +- `DesktopView` is the correct owner for shell composition, task-strip projection, transient launcher/context-menu presentation, and focus handoff. +- `ShadowRuntime` should remain limited to boot/reset/failure lifecycle and should not absorb M3 overlay or application state. +- The existing `Clock` and `formatSystemTime` boundaries are deterministic and reusable by the Clock application. +- Reset and failure already dispose applications and windows through the composition root; M3 additions must join those existing disposal paths. + +The current `ApplicationContext` is intentionally narrow and remains sufficient. M3 does not justify exposing the runtime, registry, managers, clock, or broad system services to every application. The Clock definition can receive the existing `Clock` explicitly from the composition root through its factory. + +Application definitions must remain construction-only: `create()` returns an instance and must not call `context.openWindow()` synchronously before the manager has registered that instance. M3 applications require only a primary window, so no manager contract change is needed for this ordering constraint. + +## A. Application Architecture + +- Register Notepad, Calculator, Clock, and the existing System Diagnostics definition together at startup in the composition root. +- Continue using registry manifests as the sole installed-application metadata source. The current ID, name, description, and window metadata are enough for M3; icon, grouping, search, sort-key, and launch-policy fields are not required. +- Preserve registration order as deterministic drawer order unless later usability evidence requires explicit sorting metadata. +- Continue routing all launches through `ApplicationManager.launch()`. Relaunching an existing M3 application restores or focuses its primary window and does not create another instance. +- Keep each application's mutable state inside its application instance/model, not in the DOM, shell, registry, or application manager. +- Keep application views on the existing `mount(host, document): Disposable` contract. +- Closing a primary window, runtime reset/failure, and application disposal release application-local resources exactly once. Reopening after close creates a fresh instance. +- Do not add multi-instance launch policies during M3; no planned M3 application requires one. + +## B. Application Drawer + +`ApplicationRegistry` owns discovery, and `ApplicationManager` owns launch. A new domain-level `AppLauncher` service would duplicate those authorities and is not justified. + +The drawer should be a disposable shell view/controller owned by `DesktopView`: + +1. Read immutable manifests from `ApplicationRegistry.list()`. +2. Render one entry per registered application, including System Diagnostics. +3. Dispatch the selected application ID to `ApplicationManager.launch()`. +4. Close after a successful launch and allow the existing window layer to focus the launched or restored window. + +The bottom bar should expose one clearly labeled drawer trigger rather than one permanent button per installed application. The trigger uses `aria-expanded`, `aria-controls`, and an appropriate popup relationship. Opening by pointer or keyboard moves focus to the first available application. Arrow keys move among entries; Home and End move to the bounds; Enter or Space launches; Escape closes and restores focus to the trigger. Pointer interaction outside the drawer dismisses it and restores focus when appropriate. + +The drawer remains viewport-contained and scrollable. It may appear as an anchored panel on desktop and a constrained sheet/panel on small screens, but both layouts use the same catalog and launch commands. Reduced-motion mode must not depend on an animated transition to make the drawer usable. + +## C. Task Strip and Bottom Bar + +M3 should refine, not replace, the current footer composition: + +- the application area becomes one App Drawer trigger; +- the task strip continues to show open windows only and continues to focus or restore them; +- the status area retains the existing clock and restart control; and +- responsive layouts may rearrange these zones without changing their ownership or data sources. + +The task strip must not become an installed-application catalog and must not duplicate drawer entries. Existing focus recovery after window minimize/close remains part of the contract, with the drawer trigger replacing the first permanent application button as the shell fallback target. + +## D. Context Menu + +The initial context menu is transient shell presentation state owned by `DesktopView`, not a new OS domain service. Its model should use typed surface and action identifiers plus immutable item data; DOM elements and executable callbacks do not belong in the menu model. + +The first registered surface is the desktop workspace/background. The browser's native `contextmenu` is suppressed only when a SHADOW OS surface has explicitly claimed that interaction. Window/application content and editable controls, especially the Notepad editing surface, are not suppressed by the desktop provider. Future window, application, and file providers can supply their own typed item definitions without changing the initial action-dispatch path. + +The initial desktop menu contains only: + +- **Refresh Desktop**; and +- **Open App Drawer**. + +No Settings placeholder is needed because M3 has no settings capability. + +Menu behavior requirements: + +- pointer invocation anchors at the pointer location; +- keyboard invocation through the Context Menu key or Shift+F10 anchors to the focused desktop surface; +- placement clamps to the visible workspace/viewport and handles all edges; +- focus moves to the first enabled item; +- Arrow Up/Down and Home/End navigate enabled items; +- Enter or Space invokes the focused item; +- Escape, outside pointer interaction, a second invocation, or successful action dismisses the menu; +- dismissal restores focus to the invoker when it remains available; and +- disposal removes document-level listeners and any active menu DOM. + +The initial implementation may use a focused context-menu view/controller plus typed desktop definitions. A global provider registry or context-menu service should be deferred until a second context-specific consumer proves that abstraction necessary. + +## E. Refresh Desktop + +Refresh Desktop is a shell command, not a runtime reset. It must: + +- close transient drawer/context-menu overlays; +- re-read the immutable registry and current application/window snapshots; +- reconcile launcher, task-strip, window-layer, clock, and work-area presentation from those authoritative sources; and +- preserve running application instances, application-local state, open windows, window modes, geometry, z-order, and the current runtime boot cycle. + +It must not call `location.reload()`, navigate, invoke `ShadowRuntime.reset()`, recreate the composition root, dispose applications, close windows, or mutate unrelated OS state. The smallest implementation is an explicit `DesktopView` refresh command that invokes existing projection/reconciliation methods. No new persistent desktop model or event is required because refresh does not change domain state. + +## F. Notepad + +- Create one instance-local text model whose value is independent from its rendered control. +- Use a native multiline text control for editing, selection, copy, paste, undo, and standard keyboard behavior rather than reimplementing browser text editing. +- Synchronize input into the instance model so a shell projection refresh or view remount does not lose text while the application instance remains alive. +- Start each new instance blank. +- Preserve text while the same single instance is minimized, restored, focused again, or retained through Refresh Desktop. +- Discard text when the primary window closes, the application is disposed, or SHADOW OS resets/fails. +- Do not expose save/open commands, filenames, fake paths, storage adapters, local storage, IndexedDB, import/export, or any placeholder filesystem API. + +## G. Calculator + +Use a small pure deterministic state machine rather than evaluating strings with `eval()` or introducing a parser/library. + +The locked M3 operation set is addition, subtraction, multiplication, and division with integer and decimal input. The model tracks the current entry, accumulator, pending operator, entry-replacement state, and an error state. Operations evaluate in immediate pocket-calculator order; expression precedence, history, memory registers, percentages, scientific operations, and programmable expressions are out of scope. + +Required controls are digits, decimal point, the four operators, equals, clear, and backspace. Keyboard input maps to the same commands; Enter invokes equals, Escape clears, and Backspace removes the current entry. Division by zero and non-finite results enter a visible `Error` state. Clear or the next numeric entry recovers deterministically. Display formatting and maximum practical input length should be finalized during implementation without changing this operation model. + +## H. Clock + +- Inject the existing `Clock` into the Clock application definition factory from the composition root; do not call `Date.now()` directly and do not add a second clock source. +- Reuse `formatSystemTime` for browser-local date/time presentation unless a separate pure formatter is proven necessary. +- Render a small digital time/date view and schedule one update at a time through `Clock.schedule()`. +- Cancel the pending scheduled update when the view unmounts or the application instance is disposed. +- Use the existing fake clock strategy for deterministic tests. +- Do not broaden `ApplicationContext` solely for Clock. Reconsider a read-only time capability only when another application needs application-context clock access. + +The current clock abstraction requires no architectural change for M3. + +## I. Accessibility, Focus, and Responsive Behavior + +- Preserve semantic headings, labels, native buttons, visible focus, and logical source/tab order. +- The App Drawer and context menu must be completely operable without a pointer and must restore focus on dismissal. +- The context menu uses menu/menuitem semantics; the drawer uses a labeled panel/dialog or navigation region with ordinary application buttons rather than falsely presenting application launch as a command menu. +- The desktop surface must provide a discoverable focus target for keyboard context-menu invocation. +- Notepad retains native text-selection and clipboard shortcuts and must have an accessible label. +- Calculator controls need unambiguous accessible names, a readable result/status, and no color-only error state. +- Clock uses semantic time output and must not announce every one-second update through an intrusive live region. +- Existing window focus behavior and task-strip restore behavior remain intact when drawer entries replace permanent launcher buttons. +- Desktop and current small-screen active-window layouts must contain drawer, menus, and application content without horizontal overflow or inaccessible controls. +- New transitions must honor the existing reduced-motion setting; no essential state change may depend on animation. + +## J. Testing Strategy + +### Domain and Unit Tests + +- Notepad model: initial blank value, text replacement/edit synchronization, retention while the instance lives, and fresh state after a new instance. +- Calculator model: each operation, decimals, chained immediate operations, operator replacement, equals, clear, backspace, division by zero, non-finite/error recovery, and immutable/read-only snapshots if snapshots are exposed. +- Clock: initial formatting, scheduled updates, one active scheduled callback, and cancellation on disposal using a fake clock. +- Any extracted drawer/context-menu reducer: deterministic open, navigation, selection, dismissal, and edge-position calculations independent from DOM nodes. + +### Service Integration Tests + +- Registry lists all four definitions exactly once in deterministic order. +- Application Manager launches each M3 application through the existing contract. +- Relaunch restores/focuses the existing primary window and does not create a second instance. +- Closing and reset dispose application models/timers and leave no windows or running instances. +- Refresh Desktop preserves application/window snapshots and application-local Notepad state. +- Context-menu actions dispatch only approved shell commands and do not invoke runtime reset or navigation. + +### View and Browser Tests + +The repository has no DOM component-test environment and M3 does not justify adding one solely for these views. Keep models and positioning logic unit-testable, service workflows in Vitest, and semantic DOM/focus interaction in Playwright. + +Playwright should verify: + +- pointer and keyboard drawer open, navigation, launch, dismissal, and focus restoration; +- deterministic catalog contents including System Diagnostics; +- task strip contains only running windows; +- Notepad typing, selection/clipboard-compatible behavior, relaunch retention, close/reopen discard, and reset cleanup; +- Calculator pointer and keyboard arithmetic, clear/backspace, decimal, and division-by-zero recovery; +- Clock date/time rendering and cleanup behavior without direct wall-clock flakiness; +- desktop pointer and keyboard context-menu invocation, edge clamping, menu navigation, outside/Escape dismissal, and focus restoration; +- native context-menu suppression on owned desktop surfaces but not on editable Notepad content; +- Refresh Desktop causes no navigation/reload, boot-cycle change, app disposal, window loss, or Notepad text loss; +- existing System Diagnostics, window interactions, restart, focus recovery, and M0-M2 workflows remain operational; +- desktop and current 360 x 740 small-screen behavior have no horizontal overflow or blocked critical controls; and +- no unexpected console errors, page errors, failed requests, or external runtime dependencies occur. + +All checks should prefer roles, accessible names, stable domain markers, injected time, and observable manager results over arbitrary delays or implementation-specific selectors. + +## Locked Architectural Decisions + +1. **Use the M2 application framework unchanged for M3 application ownership.** + +- **Reason:** Registry discovery, single-instance launch, primary-window ownership, reset, and disposal already satisfy M3. +- **Alternative considered:** A new application runtime or launcher service. +- **Consequence:** All M3 apps register at startup and launch only through `ApplicationManager`. + +2. **Keep the registry as the only installed-application catalog.** + +- **Reason:** A second drawer catalog would introduce conflicting truth. +- **Alternative considered:** Drawer-owned application configuration. +- **Consequence:** Drawer order and metadata come directly from immutable manifests. + +3. **Keep drawer and context-menu state in disposable shell views.** + +- **Reason:** Open/position/focus state is transient presentation state, not OS domain state. +- **Alternative considered:** New global services or runtime state. +- **Consequence:** `DesktopView` owns and disposes both overlays; domain managers remain unchanged. + +4. **Keep the task strip limited to open windows.** + +- **Reason:** Installed applications and running windows are different concepts with existing owners. +- **Alternative considered:** Keep permanent application launch buttons mixed with running-window controls. +- **Consequence:** One drawer trigger replaces permanent per-application launcher buttons. + +5. **Define Refresh Desktop as projection reconciliation only.** + +- **Reason:** A refresh should correct/rebuild presentation from authoritative state without becoming restart. +- **Alternatives considered:** Browser reload, runtime reset, or composition-root reconstruction. +- **Consequence:** Apps, windows, local app state, geometry, and boot cycle survive refresh. + +6. **Keep Notepad text instance-local and ephemeral.** + +- **Reason:** M3 needs useful editing but M4 owns shared storage. +- **Alternative considered:** Local storage or a temporary filesystem. +- **Consequence:** Text survives view reconciliation while the instance lives and is discarded on close/reset. + +7. **Use an explicit calculator state machine with four arithmetic operations.** + +- **Reason:** It is deterministic, testable, and avoids unsafe evaluation or unnecessary parsing. +- **Alternatives considered:** Evaluate expression strings or add a general expression parser. +- **Consequence:** History, precedence parsing, memory, percentage, and scientific behavior remain excluded. + +8. **Inject the existing Clock into the Clock definition factory.** + +- **Reason:** This reuses deterministic time without broadening every application's context. +- **Alternative considered:** Direct browser time or adding Clock to `ApplicationContext`. +- **Consequence:** The composition root wires Clock explicitly and disposal cancels scheduled ticks. + +9. **Claim native context-menu behavior only for registered SHADOW OS surfaces.** + +- **Reason:** Application/editable content may need native browser behavior until it has its own provider. +- **Alternatives considered:** Suppress the native menu across the entire shell or introduce a global provider service before a second provider exists. +- **Consequence:** M3 begins with the desktop background and leaves future typed providers incremental. + +10. **Add no new external dependency or DOM test environment for M3.** + +- **Reason:** Existing TypeScript, browser APIs, Vitest service tests, and Playwright cover the planned behavior. +- **Alternative considered:** Add a browser-like DOM unit-test dependency solely for M3 views. +- **Consequence:** Pure logic stays DOM-independent and browser semantics are verified end to end. + +## Open Questions + +- What exact visual composition gives the App Drawer a distinct SHADOW OS identity while preserving the behavioral contract above? +- What practical Calculator input-length and floating-point display policy avoids misleading output without expanding into arbitrary precision? +- Should a second context-specific consumer in M3 appear, or should the generalized provider registry wait until M4 file contexts exist? +- Which formal browser and assistive-technology matrix will gate M3 beyond the current Chromium baseline and manual keyboard review? + +These questions may be resolved during implementation without changing subsystem ownership or the M3/M4 boundary. + +## Deferred Decisions + +- Virtual Filesystem contracts, paths, metadata, events, seed data, and storage adapters. +- File Manager and Notepad save/open workflows. +- Browser persistence, import/export, and shared application data. +- Image Viewer and file associations. +- Settings application, themes, Calendar, Tasks, Terminal, Browser, Email, networking, accounts, and backend services. +- Process/task-service semantics. +- Scenario packages, setup/reset, objectives, progression, and gameplay. +- Multi-instance launch policies and dynamic application installation. +- Global context-provider registration until more than one concrete provider exists. + +## Future Ideas + +- Drawer search, grouping, favorites, and optional manifest icon metadata after the base catalog proves a need. +- A command palette sharing typed action IDs with context menus. +- Application/window grouping in the task strip. +- Capability-filtered context providers for windows, applications, and M4 file surfaces. + +None of these ideas is an M3 requirement. + +## Proposed M3 Definition of Done + +### Applications + +- Notepad, Calculator, Clock, and System Diagnostics are registered once in the startup registry and launch through `ApplicationManager`. +- Repeated launch restores/focuses the existing single instance. +- Notepad provides labeled native multiline editing with temporary instance-local text, retains it while that instance lives, and discards it on close/reset without any save, load, path, storage, or persistence API. +- Calculator provides deterministic pointer and keyboard use for addition, subtraction, multiplication, division, decimals, equals, clear, and backspace, including recoverable division-by-zero/non-finite errors. +- Clock presents local digital date/time from the injected existing `Clock`, updates predictably, and cancels scheduled work on close/reset/disposal. +- System Diagnostics remains launchable and functionally unchanged except for normal drawer integration. + +### Shell and Interaction + +- One keyboard-accessible App Drawer trigger replaces permanent per-application bottom-bar entries. +- The drawer lists registry manifests in deterministic order and launches only through `ApplicationManager`. +- The task strip lists only open windows and preserves focus/restore behavior. +- Desktop pointer and keyboard invocation opens a viewport-clamped SHADOW OS context menu with Refresh Desktop and Open App Drawer. +- Native context-menu suppression is limited to the registered desktop surface; editable Notepad behavior remains native. +- Escape, outside interaction, launch/action completion, and disposal dismiss overlays with deterministic focus restoration. +- Refresh Desktop causes no browser navigation, runtime reset, boot-cycle change, application disposal, window loss, geometry reset, or Notepad text loss. + +### Quality and Lifecycle + +- Drawer, context menu, all applications, and critical shell paths are accessible by keyboard with semantic labels, visible focus, and reduced-motion-safe behavior. +- Desktop and the current supported small-screen presentation remain coherent without horizontal overflow or blocked critical controls. +- Closing applications, restart/reset, runtime failure, and top-level disposal leave no stale instances, windows, overlays, event listeners, or scheduled clock work. +- Focus recovery remains predictable after overlay dismissal, application launch, window minimize/close, and reset. +- Focused unit and integration tests cover application models, registry/manager workflows, refresh invariants, commands, and disposal. +- Playwright covers the critical pointer, keyboard, responsive, lifecycle, focus, context-menu, drawer, and application workflows with no console/page/network failures. +- Prettier, strict TypeScript, ESLint, all Vitest tests, production build, and all Playwright tests pass. +- Manual desktop, current small-screen, keyboard-only, focus, and reduced-motion review passes. +- A final scope audit confirms no Virtual Filesystem, file workflow, persistent data, deferred application/service, backend, or scenario behavior entered M3. + +## Recommended Implementation Order + +1. Add pure Notepad and Calculator models with focused unit tests. +2. Add the three application definitions/views and inject the existing Clock through composition. +3. Replace permanent application buttons with the registry-backed App Drawer while preserving task-strip behavior. +4. Add the typed desktop context-menu model/view and shell command dispatch. +5. Add projection-only Refresh Desktop and lock its state-preservation tests. +6. Complete responsive/accessibility styling and Playwright workflows incrementally. +7. Run all quality gates, manual verification, and strict M3/M4 scope review before declaring implementation ready. + +## Planning Outcome + +The existing M2 ownership model is sufficient for M3. No new global state store, application catalog, launcher service, context-menu domain service, clock source, persistence mechanism, filesystem substitute, or external dependency is justified. M3 implementation should extend the composition root with three definitions, add instance-local application models/views, and add disposable shell projections for the drawer and desktop context menu. + +No M3 source code, tests, styles, package files, workflows, configuration, application implementations, release, tag, PR, merge, or deployment was created during this planning session. + +--- + +# M3 Phase 1 — Shell Foundation Implementation + Visual Refinement + +- **Date:** 2026-09-28 +- **Branch:** `feature/m3-applications-os-experience` +- **Implementation commit:** `ad088e41dd6c99faf5ae764036b5167271e0e219` +- **Visual refinement commit:** `41113dd9a618c1eeddb025621c7ffb894b411ce9` +- **Checkpoint status:** M3 Phase 1 implemented and manually verified; Milestone 3 remains in progress + +## Scope Implemented + +- Added a registry-backed floating Application Drawer/Launcher. +- Kept the task strip limited to running windows. +- Added a scoped SHADOW OS desktop context menu. +- Added projection-only Refresh Desktop behavior. +- Preserved accessible keyboard interaction, focus recovery, and overlay dismissal. +- Added responsive launcher and context-menu behavior. +- Refined the launcher into a compact floating SHADOW OS surface. +- Refined the context menu into a minimal two-action command surface. + +## Architecture + +- `ApplicationRegistry` remains the sole installed-application catalog. +- `ApplicationManager` remains responsible for application launch and lifecycle. +- `WindowManager` remains responsible for windows, focus, geometry, and z-order. +- The drawer and context menu remain disposable shell views/overlays owned by `DesktopView`. +- The task strip represents running windows rather than installed applications. +- Context-menu interception remains scoped to registered desktop surfaces; application content retains native browser context-menu behavior. +- Refresh Desktop performs projection/reconciliation only. It does not reload the page, reset the runtime, or mutate application/window manager state. +- No new global service, dependency, persistence mechanism, filesystem behavior, or application architecture was introduced. + +## Visual Refinement + +Manual review of the initial Phase 1 presentation led to a focused visual pass: + +- The App Drawer became a compact floating launcher above the task strip. +- Its single-application state was deliberately composed as a bounded application tile rather than an empty large panel. +- The context menu became a compact two-action SHADOW OS command surface containing Refresh Desktop and Applications. +- The refinement was CSS-led, with typed presentation symbols rendered separately from accessible action names. +- Existing behavior, ownership boundaries, and application/window architecture were preserved. + +## Verification + +- Prettier: PASS +- Strict TypeScript: PASS +- ESLint: PASS +- Vitest: 38 tests PASS across 9 files +- Production build: PASS +- Playwright Chromium: 16 tests PASS + +Manual viewport inspection passed at 1440px, 1024px, 768px, and 360 × 740. The launcher and context menu remained contained without clipping or horizontal page overflow. Launcher opening and launching, context-menu edge clamping, keyboard/focus behavior, and the existing window interactions remained functional. Refresh Desktop did not reload the browser or disturb open application/window state. Right-click inside application content retained the native browser context menu, and restart returned SHADOW OS to a clean desktop. + +Reduced-motion behavior passed the existing automated Playwright coverage. Manual reduced-motion verification was not performed for this checkpoint. + +## Remaining M3 Work + +Milestone 3 is not complete. Remaining work includes: + +- Notepad. +- Calculator. +- Clock. +- Broader M3 integration. +- Final accessibility and manual acceptance. +- Final M3 quality-gate audit. +- M3 documentation and milestone closure. + +## Commit References + +- `ad088e41dd6c99faf5ae764036b5167271e0e219` — `feat: add M3 application launcher and context menu` +- `41113dd9a618c1eeddb025621c7ffb894b411ce9` — `style: refine M3 launcher and context menu` + +## Scope Review + +This checkpoint introduced no Notepad, Calculator, Clock, Settings, virtual filesystem, persistence, scenarios, networking, backend, account, release, or version changes. It records the timeline from M3 planning through Phase 1 implementation and visual refinement while leaving the remaining M3 application work explicit. + +--- + +# M3 Phase 2A — Notepad Implementation + +- **Date:** 2026-09-28 +- **Branch:** `feature/m3-applications-os-experience` +- **Checkpoint status:** Notepad implemented and manually verified; Milestone 3 remains in progress + +## Scope Implemented + +- Added Notepad as a startup-registered application discovered through the existing App Drawer. +- Added a pure instance-local text model with blank initial state and explicit disposal cleanup. +- Added a native multiline textarea with browser-provided editing, selection, cursor movement, clipboard, and undo/redo behavior. +- Added a restrained SHADOW OS editor surface with visible focus and responsive sizing. +- Preserved text while the single running instance is focused, moved, resized, minimized, restored, maximized, or reconciled through Refresh Desktop. +- Discarded text when Notepad closes or SHADOW OS restarts; reopening creates a fresh blank instance. + +## Architecture + +- `ApplicationRegistry` remains the sole application catalog, and `ApplicationManager` remains the launch/lifecycle authority. +- Notepad uses the existing `ApplicationView.mount(host, document)` contract and the existing single-instance application policy. +- `WindowManager` remains the sole owner of Notepad window geometry, mode, focus, and z-order. +- Mutable text is owned only by the running Notepad instance and is synchronized from the native editor into its model. +- No framework contract, application context, global service, dependency, filesystem abstraction, or persistence mechanism was added. + +## Tests Added + +- Unit tests cover blank initial state, multiline edits, replacement, and disposal cleanup. +- Service integration covers registration, manager-backed launch, single-instance relaunch, close/reopen identity, and reset cleanup. +- Playwright covers drawer discovery, launch, initial focus, multiline editing and selection, Escape behavior, task-strip projection, single-instance relaunch, move/resize, minimize/restore, maximize/restore, Refresh Desktop retention, native editor context menus, close/fresh reopen, restart cleanup, and mobile containment. + +## Verification + +- Prettier: PASS +- Strict TypeScript: PASS +- ESLint: PASS +- Vitest: 41 tests PASS across 10 files +- Production build: PASS +- Playwright Chromium: 18 tests PASS + +Manual verification passed at 1280px desktop and 360 × 740 mobile. The App Drawer listed both System Diagnostics and Notepad. Typing, multiline text, selection, native editing, keyboard focus, move/resize, minimize/restore, maximize/restore, Refresh Desktop, close/reopen, restart, task-strip behavior, and responsive active-window presentation worked without clipping or horizontal overflow. Right-click inside the editor retained the native browser context menu. Existing M3 Phase 1 and System Diagnostics workflows remained functional. + +Reduced-motion behavior remained covered by the existing automated Playwright workflow; manual reduced-motion verification was not performed for this checkpoint. + +## M3/M4 Leakage Audit + +Notepad introduces no Save, Save As, Open, file picker, file path, file/folder model, virtual filesystem, local or browser storage, cookies, URL state, backend call, shared file state, or other persistence behavior. Text exists only for the running application instance. + +## Remaining M3 Work + +Milestone 3 is not complete. Calculator and Clock remain unimplemented. Broader M3 integration, final accessibility/manual acceptance, the final M3 quality-gate audit, and M3 documentation/milestone closure also remain outstanding. + +--- + +# M3 Phase 2B — Calculator Implementation + +- **Date:** 2026-09-28 +- **Branch:** `feature/m3-applications-os-experience` +- **Checkpoint status:** Calculator implemented and manually verified; Milestone 3 remains in progress + +## Scope Implemented + +- Added Calculator as a startup-registered application discovered through the existing App Drawer. +- Added a compact four-operation SHADOW OS interface with semantic digit, decimal, operator, clear, backspace, and equals buttons. +- Added direct keyboard input for digits, decimal, `+`, `-`, `*`, `/`, `Enter`, `=`, `Escape`, `C`, `Backspace`, and `Delete` while preserving native Tab navigation. +- Added accessible button names, a live labeled display, visible keyboard focus, and a concise visible `ERROR` state. +- Preserved state while the single running instance is focused, moved, resized, minimized, restored, maximized, or reconciled through Refresh Desktop. +- Discarded calculations when Calculator closes or SHADOW OS restarts; reopening creates a fresh instance displaying zero. + +## Architecture + +- `ApplicationRegistry` remains the sole application catalog, and `ApplicationManager` remains the launch/lifecycle authority. +- Calculator uses the existing `ApplicationView.mount(host, document)` contract and single-instance application policy. +- `WindowManager` remains the sole owner of Calculator window geometry, mode, focus, and z-order. +- Arithmetic state is owned by a pure DOM-independent `CalculatorModel` created for each running application instance. +- The existing Clock abstraction, framework contracts, application context, global services, shell projections, and dependency graph remain unchanged. + +## State-Machine Decisions + +- Operations execute immediately from left to right, matching a conventional pocket calculator rather than expression precedence. For example, `12 + 5 × 2` produces `34`. +- Choosing another operator before entering the right operand replaces the pending operator. +- Repeated equals reapplies the last completed operator and right operand. +- Division by zero and non-finite arithmetic enter `ERROR`; Clear or a new numeric entry recovers deterministically. +- Direct entry is limited to 12 characters. Results are normalized to 12 significant digits and use compact scientific notation when needed to stay within a 16-character display budget. +- No evaluated expression string, parser, calculation history, memory, percentage, or scientific operation was introduced. + +## Tests Added + +- Sixteen pure-model tests cover initial state, digit and multi-digit entry, decimals, all four operations, immediate chained evaluation, equals, clear, backspace, negative results, division by zero, operator replacement, repeated equals, malformed decimal prevention, bounded large-number formatting, recovery, and disposal. +- Service integration covers Calculator registration, manager-backed launch, window title, single-instance relaunch, close/fresh reopen identity, and reset cleanup. +- Playwright covers drawer discovery, launch, initial focus, task-strip projection, pointer addition/subtraction/multiplication/division, decimal arithmetic, clear, backspace, visible error and recovery, keyboard input, Escape handling, single-instance restore, close/fresh reopen, restart cleanup, and mobile containment. + +## Verification + +- Prettier: PASS +- Strict TypeScript: PASS +- ESLint: PASS +- Vitest: 58 tests PASS across 11 files +- Production build: PASS +- Playwright Chromium: 20 tests PASS + +Manual verification passed at 1280 × 800 desktop and 360 × 740 mobile. App Drawer launch, pointer and keyboard arithmetic, decimals, division by zero, clear, backspace, initial focus, task-strip behavior, move/resize, minimize/restore, maximize/restore, existing-instance focus, Refresh Desktop retention, close/fresh reopen, restart cleanup, and responsive containment worked without clipping or horizontal overflow. Existing Notes editing, System Diagnostics, the desktop context menu, and Refresh Desktop remained functional with no console errors, page errors, or failed requests. + +Reduced-motion behavior remains covered by the existing automated Playwright workflow; manual reduced-motion verification was not performed for this checkpoint. + +## M3/M4 Leakage Audit + +Calculator introduces no filesystem or file model, persistence, `localStorage`, IndexedDB, cookies, backend or network call, shared file state, new global service, external dependency, advanced expression parser, history, memory, Settings, Browser, Clock implementation, or M4 process behavior. Calculator state exists only for the running application instance. + +## Remaining M3 Work + +Milestone 3 is not complete. Clock remains unimplemented. Broader M3 integration, final accessibility/manual acceptance, the final M3 quality-gate audit, and M3 documentation/milestone closure also remain outstanding. + +--- + +# M3 Phase 2C — Clock Implementation + +- **Date:** 2026-09-28 +- **Branch:** `feature/m3-applications-os-experience` +- **Checkpoint status:** Clock implemented and manually verified; Milestone 3 remains in progress + +## Scope Implemented + +- Added Clock as a startup-registered application discovered through the existing App Drawer. +- Added a compact SHADOW OS digital clock view with dominant 24-hour time including seconds and a secondary local date. +- Added semantic time/date elements with explicit accessible names and machine-readable values. +- Preserved the live display while the single running instance is focused, moved, resized, minimized, restored, maximized, or reconciled through Refresh Desktop. +- Stopped application-owned updates on close/reset and created one fresh update lifecycle when Clock reopened. + +## Existing Clock Integration + +- The composition root injects the existing M1 `Clock` into `createClockDefinition(clock)`; `ApplicationContext` and global runtime contracts remain unchanged. +- An instance-local `ClockModel` reads only `Clock.now()`, schedules only through `Clock.schedule()`, and reuses the existing pure `formatSystemTime` presentation convention. +- Clock uses the existing `ApplicationView.mount(host, document)` contract, registry catalog, manager single-instance policy, and WindowManager geometry/focus lifecycle. +- The application contains no direct `Date.now()`, `new Date()`, browser timer source, or second clock service. + +## Update and Disposal Behavior + +- The model aligns each update to the next whole-second boundary and keeps at most one scheduled callback while subscribed. +- Multiple subscribers share that single scheduled callback. +- Final unsubscribe and instance disposal both cancel the pending callback idempotently. +- Closing Clock returns browser timer activity to its pre-launch baseline; relaunch adds exactly one fresh Clock timer rather than accumulating callbacks. +- Restart/reset disposes the running instance and leaves no Clock window, task entry, subscription, or scheduled application update. + +## Tests Added + +- Six deterministic model tests cover fixed injected formatting, second-boundary alignment, repeated ticking, local midnight rollover, one-task sharing, final-unsubscribe cancellation, disposal, rejected post-disposal subscriptions, and reopen without timer accumulation. +- Service integration covers Clock registration, manager-backed launch, window title, single-instance relaunch, close/fresh reopen identity, and reset cleanup. +- Playwright covers drawer discovery, launch, accessible time/date values, live updates without fixed wall-clock assumptions, task-strip projection, single-instance relaunch, minimize/restore, close/reopen, browser timer-count cleanup, restart disposal, mobile active-window containment, and horizontal-overflow prevention. + +## Verification + +- Prettier: PASS +- Strict TypeScript: PASS +- ESLint: PASS +- Vitest: 71 tests PASS across 12 files +- Production build: PASS +- Playwright Chromium: 23 tests PASS + +Manual verification passed at 1280 × 800, 1024 × 768, 768 × 720, and 360 × 740. App Drawer launch, synchronized application/system time, local date, visible ticking, initial focus, task-strip behavior, move/resize, minimize/restore, maximize/restore, existing-instance focus, Refresh Desktop retention, close/fresh reopen, restart cleanup, and responsive containment worked without clipping or horizontal overflow. Existing Notes editing, Calculator pointer/keyboard arithmetic, System Diagnostics, the desktop context menu, Refresh Desktop, and window controls remained functional with no observed browser errors. + +Reduced-motion behavior remains covered by the existing automated Playwright workflow; manual reduced-motion verification was not performed for this checkpoint. + +## M3/M4 Leakage Audit + +Clock introduces no filesystem or file model, persistence, `localStorage`, IndexedDB, cookies, backend or network call, shared state service, global ticking service, external dependency, Calendar behavior, timezone configuration, user setting, alarm, timer, stopwatch, world clock, weather, or M4 process behavior. Its only time source is the existing injected OS `Clock`. + +## Remaining M3 Work + +Milestone 3 is not complete. Broader M3 integration, final accessibility/manual acceptance, the final M3 quality-gate audit, and M3 documentation/milestone closure remain outstanding. No final integration or closure work was started in this phase. diff --git a/src/applications/built-in/calculator-model.ts b/src/applications/built-in/calculator-model.ts new file mode 100644 index 0000000..db69e76 --- /dev/null +++ b/src/applications/built-in/calculator-model.ts @@ -0,0 +1,222 @@ +export type CalculatorOperator = "add" | "subtract" | "multiply" | "divide"; + +export interface CalculatorPendingOperation { + readonly operand: string; + readonly operator: CalculatorOperator; +} + +const ERROR_DISPLAY = "ERROR"; +const MAX_ENTRY_LENGTH = 12; +const MAX_DISPLAY_LENGTH = 16; +const MAX_SIGNIFICANT_DIGITS = 12; + +export class CalculatorModel { + #display = "0"; + #accumulator: number | null = null; + #pendingOperator: CalculatorOperator | null = null; + #replaceDisplay = false; + #lastOperator: CalculatorOperator | null = null; + #lastOperand: number | null = null; + #hasError = false; + + get display(): string { + return this.#display; + } + + get hasError(): boolean { + return this.#hasError; + } + + get pendingOperation(): CalculatorPendingOperation | null { + if (this.#accumulator === null || this.#pendingOperator === null || this.#hasError) { + return null; + } + + return Object.freeze({ + operand: formatResult(this.#accumulator), + operator: this.#pendingOperator, + }); + } + + inputDigit(digit: string): void { + if (!/^\d$/.test(digit)) { + throw new RangeError(`Calculator digit must be between 0 and 9: ${digit}`); + } + + this.#recoverForNumericInput(); + this.#clearRepeatedOperation(); + + if (this.#replaceDisplay || this.#display === "0") { + this.#display = digit; + this.#replaceDisplay = false; + return; + } + + if (this.#display.length < MAX_ENTRY_LENGTH) { + this.#display += digit; + } + } + + inputDecimal(): void { + this.#recoverForNumericInput(); + this.#clearRepeatedOperation(); + + if (this.#replaceDisplay) { + this.#display = "0."; + this.#replaceDisplay = false; + return; + } + + if (!this.#display.includes(".") && this.#display.length < MAX_ENTRY_LENGTH) { + this.#display += "."; + } + } + + chooseOperator(operator: CalculatorOperator): void { + if (this.#hasError) { + return; + } + + const currentValue = Number(this.#display); + + if (this.#pendingOperator !== null && !this.#replaceDisplay) { + const result = this.#calculate(this.#accumulator ?? currentValue, currentValue); + if (result === null) { + return; + } + this.#accumulator = result; + } else if (this.#pendingOperator === null) { + this.#accumulator = currentValue; + } + + this.#pendingOperator = operator; + this.#replaceDisplay = true; + this.#clearRepeatedOperation(); + } + + equals(): void { + if (this.#hasError) { + return; + } + + const currentValue = Number(this.#display); + + if (this.#pendingOperator !== null) { + const operator = this.#pendingOperator; + const result = this.#calculate(this.#accumulator ?? currentValue, currentValue); + if (result === null) { + return; + } + this.#pendingOperator = null; + this.#accumulator = null; + this.#lastOperator = operator; + this.#lastOperand = currentValue; + this.#replaceDisplay = true; + return; + } + + if (this.#lastOperator !== null && this.#lastOperand !== null) { + this.#calculate(currentValue, this.#lastOperand); + this.#replaceDisplay = true; + return; + } + + this.#replaceDisplay = true; + } + + backspace(): void { + if (this.#hasError || this.#replaceDisplay) { + return; + } + + if ( + this.#display.length === 1 || + (this.#display.startsWith("-") && this.#display.length === 2) + ) { + this.#display = "0"; + return; + } + + this.#display = this.#display.slice(0, -1); + } + + clear(): void { + this.#display = "0"; + this.#accumulator = null; + this.#pendingOperator = null; + this.#replaceDisplay = false; + this.#clearRepeatedOperation(); + this.#hasError = false; + } + + dispose(): void { + this.clear(); + } + + #recoverForNumericInput(): void { + if (this.#hasError) { + this.clear(); + } + } + + #clearRepeatedOperation(): void { + this.#lastOperator = null; + this.#lastOperand = null; + } + + #calculate(left: number, right: number): number | null { + let result: number; + + switch (this.#pendingOperator ?? this.#lastOperator) { + case "add": + result = left + right; + break; + case "subtract": + result = left - right; + break; + case "multiply": + result = left * right; + break; + case "divide": + if (right === 0) { + this.#enterError(); + return null; + } + result = left / right; + break; + default: + return null; + } + + if (!Number.isFinite(result)) { + this.#enterError(); + return null; + } + + this.#display = formatResult(result); + return result; + } + + #enterError(): void { + this.#display = ERROR_DISPLAY; + this.#accumulator = null; + this.#pendingOperator = null; + this.#replaceDisplay = true; + this.#clearRepeatedOperation(); + this.#hasError = true; + } +} + +function formatResult(value: number): string { + const normalized = Number.parseFloat(value.toPrecision(MAX_SIGNIFICANT_DIGITS)); + const plain = normalized.toString(); + + if (plain.length <= MAX_DISPLAY_LENGTH) { + return plain; + } + + return normalized + .toExponential(8) + .replace(/\.0+e/, "e") + .replace(/(\.\d*?)0+e/, "$1e"); +} diff --git a/src/applications/built-in/calculator.ts b/src/applications/built-in/calculator.ts new file mode 100644 index 0000000..308a275 --- /dev/null +++ b/src/applications/built-in/calculator.ts @@ -0,0 +1,266 @@ +import { toApplicationId } from "../../core/identity/identifiers"; +import type { ApplicationDefinition, ApplicationView } from "../framework/application"; +import { CalculatorModel, type CalculatorOperator } from "./calculator-model"; + +export const CALCULATOR_APPLICATION_ID = toApplicationId("system.calculator"); + +interface CalculatorKey { + readonly label: string; + readonly name: string; + readonly command: string; + readonly kind: "digit" | "operator" | "utility" | "equals"; + readonly shortcuts?: string; +} + +const CALCULATOR_KEYS: readonly CalculatorKey[] = [ + { label: "C", name: "Clear", command: "clear", kind: "utility", shortcuts: "Escape C" }, + { + label: "DEL", + name: "Backspace", + command: "backspace", + kind: "utility", + shortcuts: "Backspace Delete", + }, + { label: "÷", name: "Divide", command: "operator:divide", kind: "operator", shortcuts: "/" }, + { + label: "×", + name: "Multiply", + command: "operator:multiply", + kind: "operator", + shortcuts: "*", + }, + { label: "7", name: "7", command: "digit:7", kind: "digit" }, + { label: "8", name: "8", command: "digit:8", kind: "digit" }, + { label: "9", name: "9", command: "digit:9", kind: "digit" }, + { + label: "−", + name: "Subtract", + command: "operator:subtract", + kind: "operator", + shortcuts: "-", + }, + { label: "4", name: "4", command: "digit:4", kind: "digit" }, + { label: "5", name: "5", command: "digit:5", kind: "digit" }, + { label: "6", name: "6", command: "digit:6", kind: "digit" }, + { label: "+", name: "Add", command: "operator:add", kind: "operator", shortcuts: "+" }, + { label: "1", name: "1", command: "digit:1", kind: "digit" }, + { label: "2", name: "2", command: "digit:2", kind: "digit" }, + { label: "3", name: "3", command: "digit:3", kind: "digit" }, + { label: "=", name: "Equals", command: "equals", kind: "equals", shortcuts: "Enter =" }, + { label: "0", name: "0", command: "digit:0", kind: "digit" }, + { label: ".", name: "Decimal point", command: "decimal", kind: "digit", shortcuts: "." }, +]; + +const OPERATOR_PRESENTATION: Readonly< + Record +> = { + add: { symbol: "+", name: "plus" }, + subtract: { symbol: "−", name: "minus" }, + multiply: { symbol: "×", name: "times" }, + divide: { symbol: "÷", name: "divided by" }, +}; + +export function createCalculatorDefinition(): ApplicationDefinition { + return { + manifest: { + id: CALCULATOR_APPLICATION_ID, + name: "Calculator", + description: "Perform basic four-operation arithmetic.", + window: { + title: "Calculator", + preferredWidth: 350, + preferredHeight: 480, + constraints: { minWidth: 300, minHeight: 390 }, + }, + }, + create: () => { + const model = new CalculatorModel(); + + return { + primaryView: createCalculatorView(model), + dispose: () => model.dispose(), + }; + }, + }; +} + +function createCalculatorView(model: CalculatorModel): ApplicationView { + return { + mount(host, document): () => void { + const content = document.createElement("section"); + content.className = "calculator-app"; + content.tabIndex = 0; + content.setAttribute("aria-label", "Calculator keyboard input"); + + const displayPanel = document.createElement("div"); + displayPanel.className = "calculator-app__display-panel"; + + const pendingDisplay = document.createElement("output"); + pendingDisplay.className = "calculator-app__pending"; + pendingDisplay.setAttribute("aria-live", "polite"); + pendingDisplay.setAttribute("aria-atomic", "true"); + + const display = document.createElement("output"); + display.className = "calculator-app__display"; + display.setAttribute("aria-label", "Calculator display"); + display.setAttribute("aria-live", "polite"); + display.setAttribute("aria-atomic", "true"); + displayPanel.append(pendingDisplay, display); + + const keypad = document.createElement("div"); + keypad.className = "calculator-app__keypad"; + keypad.setAttribute("aria-label", "Calculator keypad"); + keypad.append(...CALCULATOR_KEYS.map((key) => createKey(document, key))); + const operatorButtons = [ + ...keypad.querySelectorAll(".calculator-app__key--operator"), + ]; + + const render = (): void => { + const state = model.hasError ? "error" : "ready"; + const pendingOperation = model.pendingOperation; + const presentation = pendingOperation + ? OPERATOR_PRESENTATION[pendingOperation.operator] + : null; + const pendingText = + pendingOperation && presentation + ? `${pendingOperation.operand} ${presentation.symbol}` + : ""; + + if (display.textContent !== model.display) { + display.textContent = model.display; + } + display.dataset.state = state; + displayPanel.dataset.state = state; + + if (pendingDisplay.textContent !== pendingText) { + pendingDisplay.textContent = pendingText; + } + if (pendingOperation && presentation) { + pendingDisplay.setAttribute( + "aria-label", + `Pending operation: ${pendingOperation.operand} ${presentation.name}`, + ); + } else { + pendingDisplay.removeAttribute("aria-label"); + } + + for (const button of operatorButtons) { + button.setAttribute( + "aria-pressed", + String(button.dataset.calculatorCommand === `operator:${pendingOperation?.operator}`), + ); + } + }; + const runCommand = (command: string): void => { + applyCommand(model, command); + render(); + }; + const handleClick = (event: MouseEvent): void => { + const target = event.target instanceof Element ? event.target : null; + const button = target?.closest("[data-calculator-command]"); + if (button && keypad.contains(button)) { + runCommand(button.dataset.calculatorCommand ?? ""); + } + }; + const handleKeyDown = (event: KeyboardEvent): void => { + const command = keyboardCommand(event); + if (command === null) { + return; + } + + event.preventDefault(); + event.stopPropagation(); + runCommand(command); + }; + + keypad.addEventListener("click", handleClick); + content.addEventListener("keydown", handleKeyDown); + content.append(displayPanel, keypad); + host.replaceChildren(content); + render(); + content.focus({ preventScroll: true }); + + return () => { + keypad.removeEventListener("click", handleClick); + content.removeEventListener("keydown", handleKeyDown); + host.replaceChildren(); + }; + }, + }; +} + +function createKey(document: Document, key: CalculatorKey): HTMLButtonElement { + const button = document.createElement("button"); + button.className = `calculator-app__key calculator-app__key--${key.kind}`; + button.type = "button"; + button.textContent = key.label; + button.dataset.calculatorCommand = key.command; + button.setAttribute("aria-label", key.name); + if (key.kind === "operator") { + button.setAttribute("aria-pressed", "false"); + } + if (key.shortcuts !== undefined) { + button.setAttribute("aria-keyshortcuts", key.shortcuts); + } + return button; +} + +function keyboardCommand(event: KeyboardEvent): string | null { + if (event.key === "Enter" && event.target instanceof HTMLButtonElement) { + return null; + } + if (/^\d$/.test(event.key)) { + return `digit:${event.key}`; + } + + switch (event.key) { + case ".": + return "decimal"; + case "+": + return "operator:add"; + case "-": + return "operator:subtract"; + case "*": + return "operator:multiply"; + case "/": + return "operator:divide"; + case "Enter": + case "=": + return "equals"; + case "Escape": + case "c": + case "C": + return "clear"; + case "Backspace": + case "Delete": + return "backspace"; + default: + return null; + } +} + +function applyCommand(model: CalculatorModel, command: string): void { + if (command.startsWith("digit:")) { + model.inputDigit(command.slice(-1)); + return; + } + if (command.startsWith("operator:")) { + model.chooseOperator(command.slice("operator:".length) as CalculatorOperator); + return; + } + + switch (command) { + case "decimal": + model.inputDecimal(); + break; + case "equals": + model.equals(); + break; + case "clear": + model.clear(); + break; + case "backspace": + model.backspace(); + break; + } +} diff --git a/src/applications/built-in/clock-model.ts b/src/applications/built-in/clock-model.ts new file mode 100644 index 0000000..ce3d260 --- /dev/null +++ b/src/applications/built-in/clock-model.ts @@ -0,0 +1,77 @@ +import type { Disposable } from "../../core/disposable"; +import type { Clock } from "../../core/time/clock"; +import { formatSystemTime, type SystemTime } from "../../shell/system-time"; + +export type ClockListener = (snapshot: SystemTime) => void; + +export class ClockModel { + readonly #clock: Clock; + readonly #listeners = new Set(); + #snapshot: SystemTime; + #cancelTick: Disposable | null = null; + #disposed = false; + + constructor(clock: Clock) { + this.#clock = clock; + this.#snapshot = formatSystemTime(clock.now()); + } + + get snapshot(): SystemTime { + return this.#snapshot; + } + + subscribe(listener: ClockListener): Disposable { + if (this.#disposed) { + throw new Error("Cannot subscribe to a disposed Clock model."); + } + + this.#listeners.add(listener); + if (this.#listeners.size === 1) { + this.#scheduleNextTick(); + } + + let subscribed = true; + return () => { + if (!subscribed) { + return; + } + subscribed = false; + this.#listeners.delete(listener); + if (this.#listeners.size === 0) { + this.#cancelScheduledTick(); + } + }; + } + + dispose(): void { + if (this.#disposed) { + return; + } + + this.#disposed = true; + this.#cancelScheduledTick(); + this.#listeners.clear(); + } + + #scheduleNextTick(): void { + const now = this.#clock.now(); + const elapsedInSecond = ((now % 1_000) + 1_000) % 1_000; + const delayMs = elapsedInSecond === 0 ? 1_000 : 1_000 - elapsedInSecond; + + this.#cancelTick = this.#clock.schedule(() => { + this.#cancelTick = null; + this.#snapshot = formatSystemTime(this.#clock.now()); + for (const listener of [...this.#listeners]) { + listener(this.#snapshot); + } + if (!this.#disposed && this.#listeners.size > 0) { + this.#scheduleNextTick(); + } + }, delayMs); + } + + #cancelScheduledTick(): void { + this.#cancelTick?.(); + this.#cancelTick = null; + } +} diff --git a/src/applications/built-in/clock.ts b/src/applications/built-in/clock.ts new file mode 100644 index 0000000..d4a676f --- /dev/null +++ b/src/applications/built-in/clock.ts @@ -0,0 +1,74 @@ +import type { Clock } from "../../core/time/clock"; +import { toApplicationId } from "../../core/identity/identifiers"; +import type { SystemTime } from "../../shell/system-time"; +import type { ApplicationDefinition, ApplicationView } from "../framework/application"; +import { ClockModel } from "./clock-model"; + +export const CLOCK_APPLICATION_ID = toApplicationId("system.clock"); + +export function createClockDefinition(clock: Clock): ApplicationDefinition { + return { + manifest: { + id: CLOCK_APPLICATION_ID, + name: "Clock", + description: "View the current local time and date.", + window: { + title: "Clock", + preferredWidth: 440, + preferredHeight: 300, + constraints: { minWidth: 300, minHeight: 240 }, + }, + }, + create: () => { + const model = new ClockModel(clock); + + return { + primaryView: createClockView(model), + dispose: () => model.dispose(), + }; + }, + }; +} + +function createClockView(model: ClockModel): ApplicationView { + return { + mount(host, document): () => void { + const content = document.createElement("section"); + content.className = "clock-app"; + + const face = document.createElement("div"); + face.className = "clock-app__face"; + + const time = document.createElement("time"); + time.className = "clock-app__time"; + + const date = document.createElement("time"); + date.className = "clock-app__date"; + + const render = (snapshot: SystemTime): void => { + if (time.textContent !== snapshot.time) { + time.textContent = snapshot.time; + } + time.dateTime = snapshot.iso; + time.setAttribute("aria-label", `Current time: ${snapshot.time}`); + + if (date.textContent !== snapshot.date) { + date.textContent = snapshot.date; + } + date.dateTime = snapshot.date.replaceAll(".", "-"); + date.setAttribute("aria-label", `Current date: ${snapshot.date}`); + }; + + face.append(time, date); + content.append(face); + host.replaceChildren(content); + render(model.snapshot); + const unsubscribe = model.subscribe(render); + + return () => { + unsubscribe(); + host.replaceChildren(); + }; + }, + }; +} diff --git a/src/applications/built-in/notepad-model.ts b/src/applications/built-in/notepad-model.ts new file mode 100644 index 0000000..267e50c --- /dev/null +++ b/src/applications/built-in/notepad-model.ts @@ -0,0 +1,15 @@ +export class NotepadModel { + #text = ""; + + get text(): string { + return this.#text; + } + + setText(text: string): void { + this.#text = text; + } + + dispose(): void { + this.#text = ""; + } +} diff --git a/src/applications/built-in/notepad.ts b/src/applications/built-in/notepad.ts new file mode 100644 index 0000000..2ca8327 --- /dev/null +++ b/src/applications/built-in/notepad.ts @@ -0,0 +1,55 @@ +import { toApplicationId } from "../../core/identity/identifiers"; +import type { ApplicationDefinition, ApplicationView } from "../framework/application"; +import { NotepadModel } from "./notepad-model"; + +export const NOTEPAD_APPLICATION_ID = toApplicationId("system.notepad"); + +export function createNotepadDefinition(): ApplicationDefinition { + return { + manifest: { + id: NOTEPAD_APPLICATION_ID, + name: "Notes", + description: "Write and edit temporary session text.", + window: { + title: "Notes", + preferredWidth: 620, + preferredHeight: 440, + constraints: { minWidth: 320, minHeight: 240 }, + }, + }, + create: () => { + const model = new NotepadModel(); + + return { + primaryView: createNotepadView(model), + dispose: () => model.dispose(), + }; + }, + }; +} + +function createNotepadView(model: NotepadModel): ApplicationView { + return { + mount(host, document): () => void { + const content = document.createElement("section"); + content.className = "notepad-app"; + + const editor = document.createElement("textarea"); + editor.className = "notepad-app__editor"; + editor.value = model.text; + editor.placeholder = "Start typing..."; + editor.setAttribute("aria-label", "Notes editor"); + + const handleInput = (): void => model.setText(editor.value); + editor.addEventListener("input", handleInput); + content.append(editor); + host.replaceChildren(content); + editor.focus({ preventScroll: true }); + + return () => { + editor.removeEventListener("input", handleInput); + host.replaceChildren(); + }; + }, + }; +} diff --git a/src/bootstrap/start-afterboot.ts b/src/bootstrap/start-afterboot.ts index 3c6683d..6386630 100644 --- a/src/bootstrap/start-afterboot.ts +++ b/src/bootstrap/start-afterboot.ts @@ -2,6 +2,9 @@ import { ShadowRuntime, type BootStageDurations } from "../core/runtime/shadow-r import { SequentialIdGenerator } from "../core/identity/identifiers"; import { ApplicationRegistry } from "../applications/framework/application-registry"; import { ApplicationManager } from "../applications/framework/application-manager"; +import { createCalculatorDefinition } from "../applications/built-in/calculator"; +import { createClockDefinition } from "../applications/built-in/clock"; +import { createNotepadDefinition } from "../applications/built-in/notepad"; import { createSystemDiagnosticsDefinition } from "../applications/built-in/system-diagnostics"; import { BrowserClock } from "../platform/browser-clock"; import { prefersReducedMotion } from "../platform/motion-preference"; @@ -51,7 +54,12 @@ export function startAfterboot(document: Document, browserWindow: Window): After }); const ids = new SequentialIdGenerator(); const windowManager = new WindowManager(ids, { x: 0, y: 0, width: 1, height: 1 }); - const registry = new ApplicationRegistry([createSystemDiagnosticsDefinition()]); + const registry = new ApplicationRegistry([ + createSystemDiagnosticsDefinition(), + createNotepadDefinition(), + createCalculatorDefinition(), + createClockDefinition(clock), + ]); const applicationManager = new ApplicationManager(registry, windowManager, ids); const disposeRuntimeServices = runtime.onStateChanged((event) => { if (event.reason === "reset-requested" || event.reason === "runtime-failed") { diff --git a/src/shell/desktop/application-drawer-view.ts b/src/shell/desktop/application-drawer-view.ts new file mode 100644 index 0000000..9ba9604 --- /dev/null +++ b/src/shell/desktop/application-drawer-view.ts @@ -0,0 +1,302 @@ +import type { ApplicationManager } from "../../applications/framework/application-manager"; +import type { ApplicationRegistry } from "../../applications/framework/application-registry"; +import type { ApplicationManifest } from "../../applications/framework/application"; +import type { Disposable } from "../../core/disposable"; +import { toApplicationId } from "../../core/identity/identifiers"; + +const DRAWER_ID = "application-drawer"; +const DRAWER_TITLE_ID = "application-drawer-title"; +const SVG_NAMESPACE = "http://www.w3.org/2000/svg"; + +export class ApplicationDrawerView { + readonly trigger: HTMLButtonElement; + readonly element: HTMLElement; + readonly #document: Document; + readonly #registry: ApplicationRegistry; + readonly #applicationManager: ApplicationManager; + readonly #list: HTMLElement; + + constructor( + document: Document, + registry: ApplicationRegistry, + applicationManager: ApplicationManager, + ) { + this.#document = document; + this.#registry = registry; + this.#applicationManager = applicationManager; + + this.trigger = document.createElement("button"); + this.trigger.className = "application-drawer__trigger"; + this.trigger.type = "button"; + this.trigger.textContent = "Applications"; + this.trigger.setAttribute("aria-controls", DRAWER_ID); + this.trigger.setAttribute("aria-expanded", "false"); + this.trigger.setAttribute("aria-haspopup", "dialog"); + + this.element = document.createElement("section"); + this.element.id = DRAWER_ID; + this.element.className = "application-drawer"; + this.element.hidden = true; + this.element.setAttribute("role", "dialog"); + this.element.setAttribute("aria-labelledby", DRAWER_TITLE_ID); + + const header = document.createElement("header"); + header.className = "application-drawer__header"; + const eyebrow = document.createElement("span"); + eyebrow.className = "application-drawer__eyebrow"; + eyebrow.textContent = "SHADOW OS /"; + const title = document.createElement("h2"); + title.id = DRAWER_TITLE_ID; + title.className = "application-drawer__title"; + title.textContent = "Applications"; + header.append(eyebrow, title); + + this.#list = document.createElement("div"); + this.#list.className = "application-drawer__list"; + this.#list.setAttribute("aria-label", "Installed applications"); + this.element.append(header, this.#list); + this.refresh(); + } + + get isOpen(): boolean { + return !this.element.hidden; + } + + mount(): Disposable { + this.trigger.addEventListener("click", this.#handleTriggerClick); + this.trigger.addEventListener("keydown", this.#handleTriggerKeyDown); + this.element.addEventListener("click", this.#handleDrawerClick); + this.element.addEventListener("keydown", this.#handleDrawerKeyDown); + this.#document.addEventListener("pointerdown", this.#handleDocumentPointerDown); + this.#document.addEventListener("focusin", this.#handleDocumentFocusIn); + + return () => { + this.trigger.removeEventListener("click", this.#handleTriggerClick); + this.trigger.removeEventListener("keydown", this.#handleTriggerKeyDown); + this.element.removeEventListener("click", this.#handleDrawerClick); + this.element.removeEventListener("keydown", this.#handleDrawerKeyDown); + this.#document.removeEventListener("pointerdown", this.#handleDocumentPointerDown); + this.#document.removeEventListener("focusin", this.#handleDocumentFocusIn); + this.close(false); + }; + } + + refresh(): void { + this.#list.replaceChildren(...this.#registry.list().map((manifest) => this.#entry(manifest))); + } + + open(focusFirst = true): void { + if (this.isOpen) { + if (focusFirst) { + this.#entryButtons()[0]?.focus(); + } + return; + } + + this.element.hidden = false; + this.trigger.setAttribute("aria-expanded", "true"); + if (focusFirst) { + this.#entryButtons()[0]?.focus(); + } + } + + close(restoreFocus = true): void { + if (!this.isOpen) { + return; + } + + this.element.hidden = true; + this.trigger.setAttribute("aria-expanded", "false"); + if (restoreFocus && this.trigger.isConnected) { + this.trigger.focus({ preventScroll: true }); + } + } + + #entry(manifest: ApplicationManifest): HTMLButtonElement { + const button = this.#document.createElement("button"); + button.className = "application-drawer__entry"; + button.type = "button"; + button.dataset.applicationId = manifest.id; + + const marker = this.#document.createElement("span"); + marker.className = "application-drawer__marker"; + marker.setAttribute("aria-hidden", "true"); + if (manifest.name === "Notes") { + marker.append(createNotesIcon(this.#document)); + } else if (manifest.name === "Calculator") { + marker.append(createCalculatorIcon(this.#document)); + } else { + marker.textContent = markerFor(manifest.name); + } + const copy = this.#document.createElement("span"); + copy.className = "application-drawer__copy"; + const name = this.#document.createElement("span"); + name.className = "application-drawer__name"; + name.textContent = manifest.name; + const description = this.#document.createElement("span"); + description.className = "application-drawer__description"; + description.textContent = manifest.description; + copy.append(name, description); + button.append(marker, copy); + return button; + } + + #entryButtons(): HTMLButtonElement[] { + return [...this.#list.querySelectorAll("[data-application-id]")]; + } + + readonly #handleTriggerClick = (): void => { + if (this.isOpen) { + this.close(); + } else { + this.open(); + } + }; + + readonly #handleTriggerKeyDown = (event: KeyboardEvent): void => { + if (event.key === "ArrowDown") { + event.preventDefault(); + this.open(); + } else if (event.key === "Escape" && this.isOpen) { + event.preventDefault(); + this.close(); + } + }; + + readonly #handleDrawerClick = (event: MouseEvent): void => { + const target = event.target instanceof Element ? event.target : null; + const applicationId = + target?.closest("[data-application-id]")?.dataset.applicationId; + if (!applicationId) { + return; + } + + this.#applicationManager.launch(toApplicationId(applicationId)); + this.close(false); + }; + + readonly #handleDrawerKeyDown = (event: KeyboardEvent): void => { + if (event.key === "Escape") { + event.preventDefault(); + this.close(); + return; + } + + const entries = this.#entryButtons(); + const currentIndex = entries.indexOf(this.#document.activeElement as HTMLButtonElement); + let nextIndex: number | null = null; + + switch (event.key) { + case "ArrowDown": + case "ArrowRight": + nextIndex = currentIndex < 0 ? 0 : (currentIndex + 1) % entries.length; + break; + case "ArrowUp": + case "ArrowLeft": + nextIndex = + currentIndex < 0 + ? entries.length - 1 + : (currentIndex - 1 + entries.length) % entries.length; + break; + case "Home": + nextIndex = 0; + break; + case "End": + nextIndex = entries.length - 1; + break; + } + + const nextEntry = nextIndex === null ? undefined : entries[nextIndex]; + if (nextEntry) { + event.preventDefault(); + nextEntry.focus(); + } + }; + + readonly #handleDocumentPointerDown = (event: PointerEvent): void => { + const target = event.target; + if ( + this.isOpen && + target instanceof Node && + !this.element.contains(target) && + !this.trigger.contains(target) + ) { + this.close(false); + } + }; + + readonly #handleDocumentFocusIn = (event: FocusEvent): void => { + const target = event.target; + if ( + this.isOpen && + target instanceof Node && + !this.element.contains(target) && + !this.trigger.contains(target) + ) { + this.close(false); + } + }; +} + +function markerFor(name: string): string { + const marker = name + .trim() + .split(/\s+/) + .slice(0, 2) + .map((part) => part[0]?.toUpperCase() ?? "") + .join(""); + return marker || "APP"; +} + +function createNotesIcon(document: Document): SVGSVGElement { + const icon = document.createElementNS(SVG_NAMESPACE, "svg"); + icon.classList.add("application-drawer__notes-icon"); + icon.setAttribute("viewBox", "0 0 32 32"); + icon.setAttribute("fill", "none"); + icon.setAttribute("aria-hidden", "true"); + icon.setAttribute("focusable", "false"); + + const page = document.createElementNS(SVG_NAMESPACE, "path"); + page.classList.add("application-drawer__notes-page"); + page.setAttribute("d", "M7 4.5h12l6 6v17H7z M19 4.5v6h6 M11 15h10 M11 19h8 M11 23h4"); + + const pencil = document.createElementNS(SVG_NAMESPACE, "path"); + pencil.classList.add("application-drawer__notes-pencil"); + pencil.setAttribute("d", "m16 26.5 1-4 8-8 3.5 3.5-8 8z M24 15.5l3.5 3.5 M17 22.5l3.5 3.5"); + + icon.append(page, pencil); + return icon; +} + +function createCalculatorIcon(document: Document): SVGSVGElement { + const icon = document.createElementNS(SVG_NAMESPACE, "svg"); + icon.classList.add("application-drawer__calculator-icon"); + icon.setAttribute("viewBox", "0 0 32 32"); + icon.setAttribute("fill", "none"); + icon.setAttribute("aria-hidden", "true"); + icon.setAttribute("focusable", "false"); + + const body = document.createElementNS(SVG_NAMESPACE, "rect"); + body.classList.add("application-drawer__calculator-body"); + body.setAttribute("x", "6"); + body.setAttribute("y", "3.5"); + body.setAttribute("width", "20"); + body.setAttribute("height", "25"); + + const display = document.createElementNS(SVG_NAMESPACE, "rect"); + display.classList.add("application-drawer__calculator-display"); + display.setAttribute("x", "9"); + display.setAttribute("y", "7"); + display.setAttribute("width", "14"); + display.setAttribute("height", "5.5"); + + const keys = document.createElementNS(SVG_NAMESPACE, "path"); + keys.classList.add("application-drawer__calculator-keys"); + keys.setAttribute( + "d", + "M9 16h3v3H9z M14.5 16h3v3h-3z M20 16h3v3h-3z M9 21.5h3v3H9z M14.5 21.5h3v3h-3z M20 21.5h3v3h-3z", + ); + + icon.append(body, display, keys); + return icon; +} diff --git a/src/shell/desktop/context-menu-model.ts b/src/shell/desktop/context-menu-model.ts new file mode 100644 index 0000000..e4687ff --- /dev/null +++ b/src/shell/desktop/context-menu-model.ts @@ -0,0 +1,32 @@ +export type DesktopContextMenuActionId = "refresh-desktop" | "open-application-drawer"; + +export interface ContextMenuItem { + readonly id: DesktopContextMenuActionId; + readonly label: string; + readonly symbol: string; +} + +export interface OverlayPoint { + readonly x: number; + readonly y: number; +} + +export interface OverlaySize { + readonly width: number; + readonly height: number; +} + +export function clampOverlayPosition( + anchor: OverlayPoint, + overlay: OverlaySize, + viewport: OverlaySize, + margin = 8, +): OverlayPoint { + const maximumX = Math.max(margin, viewport.width - overlay.width - margin); + const maximumY = Math.max(margin, viewport.height - overlay.height - margin); + + return Object.freeze({ + x: Math.min(Math.max(margin, anchor.x), maximumX), + y: Math.min(Math.max(margin, anchor.y), maximumY), + }); +} diff --git a/src/shell/desktop/context-menu-view.ts b/src/shell/desktop/context-menu-view.ts new file mode 100644 index 0000000..74f3a40 --- /dev/null +++ b/src/shell/desktop/context-menu-view.ts @@ -0,0 +1,171 @@ +import type { Disposable } from "../../core/disposable"; +import { + clampOverlayPosition, + type ContextMenuItem, + type DesktopContextMenuActionId, +} from "./context-menu-model"; + +export type ContextMenuActionHandler = ( + actionId: DesktopContextMenuActionId, + invoker: HTMLElement | null, +) => void; + +export class ContextMenuView { + readonly element: HTMLElement; + readonly #document: Document; + readonly #browserWindow: Window; + readonly #onAction: ContextMenuActionHandler; + #invoker: HTMLElement | null = null; + + constructor( + document: Document, + browserWindow: Window, + items: readonly ContextMenuItem[], + onAction: ContextMenuActionHandler, + ) { + this.#document = document; + this.#browserWindow = browserWindow; + this.#onAction = onAction; + + this.element = document.createElement("div"); + this.element.className = "desktop-context-menu"; + this.element.hidden = true; + this.element.setAttribute("role", "menu"); + this.element.setAttribute("aria-label", "Desktop actions"); + this.element.append(...items.map((item) => this.#item(item))); + } + + get isOpen(): boolean { + return !this.element.hidden; + } + + mount(): Disposable { + this.element.addEventListener("click", this.#handleClick); + this.element.addEventListener("keydown", this.#handleKeyDown); + this.#document.addEventListener("pointerdown", this.#handleDocumentPointerDown); + + return () => { + this.element.removeEventListener("click", this.#handleClick); + this.element.removeEventListener("keydown", this.#handleKeyDown); + this.#document.removeEventListener("pointerdown", this.#handleDocumentPointerDown); + this.close(false); + }; + } + + open(anchorX: number, anchorY: number, invoker: HTMLElement | null): void { + this.#invoker = invoker; + this.element.hidden = false; + this.element.style.left = `${anchorX}px`; + this.element.style.top = `${anchorY}px`; + + const bounds = this.element.getBoundingClientRect(); + const position = clampOverlayPosition( + { x: anchorX, y: anchorY }, + { width: bounds.width, height: bounds.height }, + { width: this.#browserWindow.innerWidth, height: this.#browserWindow.innerHeight }, + ); + this.element.style.left = `${position.x}px`; + this.element.style.top = `${position.y}px`; + this.#focusItem(0); + } + + close(restoreFocus = true): void { + if (!this.isOpen) { + return; + } + + const invoker = this.#invoker; + this.element.hidden = true; + this.#invoker = null; + if (restoreFocus && invoker?.isConnected) { + invoker.focus({ preventScroll: true }); + } + } + + #item(item: ContextMenuItem): HTMLButtonElement { + const button = this.#document.createElement("button"); + button.className = "desktop-context-menu__item"; + button.type = "button"; + button.tabIndex = -1; + button.dataset.contextAction = item.id; + button.setAttribute("role", "menuitem"); + const label = this.#document.createElement("span"); + label.textContent = item.label; + const symbol = this.#document.createElement("span"); + symbol.className = "desktop-context-menu__symbol"; + symbol.textContent = item.symbol; + symbol.setAttribute("aria-hidden", "true"); + button.append(label, symbol); + return button; + } + + #items(): HTMLButtonElement[] { + return [...this.element.querySelectorAll("[role='menuitem']")]; + } + + #focusItem(index: number): void { + const items = this.#items(); + const item = items[index]; + if (!item) { + return; + } + + for (const candidate of items) { + candidate.tabIndex = candidate === item ? 0 : -1; + } + item.focus({ preventScroll: true }); + } + + readonly #handleClick = (event: MouseEvent): void => { + const target = event.target instanceof Element ? event.target : null; + const actionId = target?.closest("[data-context-action]")?.dataset + .contextAction as DesktopContextMenuActionId | undefined; + if (!actionId) { + return; + } + + const invoker = this.#invoker; + this.close(false); + this.#onAction(actionId, invoker); + }; + + readonly #handleKeyDown = (event: KeyboardEvent): void => { + if (event.key === "Escape" || event.key === "Tab") { + event.preventDefault(); + this.close(); + return; + } + + const items = this.#items(); + const currentIndex = items.indexOf(this.#document.activeElement as HTMLButtonElement); + let nextIndex: number | null = null; + + switch (event.key) { + case "ArrowDown": + nextIndex = currentIndex < 0 ? 0 : (currentIndex + 1) % items.length; + break; + case "ArrowUp": + nextIndex = + currentIndex < 0 ? items.length - 1 : (currentIndex - 1 + items.length) % items.length; + break; + case "Home": + nextIndex = 0; + break; + case "End": + nextIndex = items.length - 1; + break; + } + + if (nextIndex !== null && items[nextIndex]) { + event.preventDefault(); + this.#focusItem(nextIndex); + } + }; + + readonly #handleDocumentPointerDown = (event: PointerEvent): void => { + const target = event.target; + if (this.isOpen && target instanceof Node && !this.element.contains(target)) { + this.close(false); + } + }; +} diff --git a/src/shell/desktop/desktop-view.ts b/src/shell/desktop/desktop-view.ts index 663315a..a8c7ae5 100644 --- a/src/shell/desktop/desktop-view.ts +++ b/src/shell/desktop/desktop-view.ts @@ -1,12 +1,15 @@ import type { ApplicationManager } from "../../applications/framework/application-manager"; import type { ApplicationRegistry } from "../../applications/framework/application-registry"; import type { Disposable } from "../../core/disposable"; -import { toApplicationId, toWindowId } from "../../core/identity/identifiers"; +import { toWindowId } from "../../core/identity/identifiers"; import type { ShadowRuntime } from "../../core/runtime/shadow-runtime"; import type { Clock } from "../../core/time/clock"; import type { WindowManager } from "../windows/window-manager"; import { WindowLayerView } from "../windows/window-layer-view"; import { formatSystemTime } from "../system-time"; +import { ApplicationDrawerView } from "./application-drawer-view"; +import type { DesktopContextMenuActionId } from "./context-menu-model"; +import { ContextMenuView } from "./context-menu-view"; const CLOCK_UPDATE_INTERVAL_MS = 1_000; @@ -15,17 +18,19 @@ export class DesktopView { readonly #document: Document; readonly #runtime: ShadowRuntime; readonly #clock: Clock; - readonly #registry: ApplicationRegistry; - readonly #applicationManager: ApplicationManager; readonly #windowManager: WindowManager; readonly #windowLayer: WindowLayerView; - readonly #launcher: HTMLElement; + readonly #workspace: HTMLElement; + readonly #drawer: ApplicationDrawerView; + readonly #contextMenu: ContextMenuView; readonly #taskStrip: HTMLElement; readonly #time: HTMLTimeElement; readonly #date: HTMLElement; + readonly #status: HTMLElement; readonly #resetButton: HTMLButtonElement; #cancelClock: Disposable | null = null; #unsubscribeWindows: Disposable | null = null; + #refreshCount = 0; constructor( document: Document, @@ -40,8 +45,6 @@ export class DesktopView { this.#document = document; this.#runtime = runtime; this.#clock = clock; - this.#registry = registry; - this.#applicationManager = applicationManager; this.#windowManager = windowManager; const main = element(document, "main", "desktop-shell"); @@ -58,6 +61,8 @@ export class DesktopView { const workspace = element(document, "section", "desktop-shell__workspace"); workspace.setAttribute("aria-label", "SHADOW OS desktop work area"); + workspace.dataset.contextSurface = "desktop"; + workspace.tabIndex = 0; const desktopIdentity = element(document, "div", "desktop-shell__identity"); desktopIdentity.setAttribute("aria-hidden", "true"); desktopIdentity.append( @@ -74,10 +79,21 @@ export class DesktopView { windowLayer.setAttribute("aria-label", "Open application windows"); workspace.append(desktopIdentity, windowLayer); + this.#workspace = workspace; + this.#drawer = new ApplicationDrawerView(document, registry, applicationManager); + this.#contextMenu = new ContextMenuView( + document, + browserWindow, + [ + { id: "refresh-desktop", label: "Refresh Desktop", symbol: "↻" }, + { id: "open-application-drawer", label: "Applications", symbol: "◇" }, + ], + this.#handleContextAction, + ); + const footer = element(document, "footer", "desktop-shell__footer"); - this.#launcher = element(document, "nav", "application-launcher"); - this.#launcher.setAttribute("aria-label", "Applications"); - this.#renderLauncher(); + const launcher = element(document, "div", "application-launcher"); + launcher.append(this.#drawer.trigger); this.#taskStrip = element(document, "nav", "window-task-strip"); this.#taskStrip.setAttribute("aria-label", "Open windows"); const clockPanel = element(document, "section", "system-clock"); @@ -87,8 +103,18 @@ export class DesktopView { clockPanel.append(this.#time, this.#date); this.#resetButton = element(document, "button", "desktop-shell__reset", "Restart SHADOW OS"); this.#resetButton.type = "button"; - footer.append(this.#launcher, this.#taskStrip, clockPanel, this.#resetButton); - main.append(header, workspace, footer); + this.#status = element(document, "p", "visually-hidden"); + this.#status.setAttribute("role", "status"); + this.#status.setAttribute("aria-live", "polite"); + footer.append(launcher, this.#taskStrip, clockPanel, this.#resetButton); + main.append( + header, + workspace, + this.#drawer.element, + this.#contextMenu.element, + footer, + this.#status, + ); this.element = main; this.#windowLayer = new WindowLayerView( @@ -101,7 +127,9 @@ export class DesktopView { } mount(): Disposable { - this.#launcher.addEventListener("click", this.#handleLauncherClick); + const disposeDrawer = this.#drawer.mount(); + const disposeContextMenu = this.#contextMenu.mount(); + this.#workspace.addEventListener("contextmenu", this.#handleDesktopContextMenu); this.#taskStrip.addEventListener("click", this.#handleTaskClick); this.#resetButton.addEventListener("click", this.#handleReset); this.#unsubscribeWindows = this.#windowManager.onStateChanged((event) => { @@ -114,7 +142,7 @@ export class DesktopView { } if (event.reason === "window-closed" && !event.snapshot.activeWindowId) { - this.#launcher.querySelector("[data-application-id]")?.focus(); + this.#drawer.trigger.focus(); } }); const disposeWindowLayer = this.#windowLayer.mount(); @@ -122,34 +150,19 @@ export class DesktopView { this.#updateClock(); return () => { - this.#launcher.removeEventListener("click", this.#handleLauncherClick); + this.#workspace.removeEventListener("contextmenu", this.#handleDesktopContextMenu); this.#taskStrip.removeEventListener("click", this.#handleTaskClick); this.#resetButton.removeEventListener("click", this.#handleReset); this.#unsubscribeWindows?.(); this.#unsubscribeWindows = null; this.#cancelClock?.(); this.#cancelClock = null; + disposeContextMenu(); + disposeDrawer(); disposeWindowLayer(); }; } - #renderLauncher(): void { - const label = element(this.#document, "span", "application-launcher__label", "APPS"); - const buttons = this.#registry.list().map((manifest) => { - const button = element( - this.#document, - "button", - "application-launcher__button", - manifest.name, - ); - button.type = "button"; - button.dataset.applicationId = manifest.id; - button.title = manifest.description; - return button; - }); - this.#launcher.replaceChildren(label, ...buttons); - } - #renderTasks(): void { const snapshot = this.#windowManager.snapshot; const tasks = snapshot.windows.map((windowState) => { @@ -173,19 +186,60 @@ export class DesktopView { } #updateClock(): void { + this.#renderClock(); + this.#cancelClock = this.#clock.schedule(() => this.#updateClock(), CLOCK_UPDATE_INTERVAL_MS); + } + + #renderClock(): void { const systemTime = formatSystemTime(this.#clock.now()); this.#time.dateTime = systemTime.iso; this.#time.textContent = systemTime.time; this.#date.textContent = systemTime.date; - this.#cancelClock = this.#clock.schedule(() => this.#updateClock(), CLOCK_UPDATE_INTERVAL_MS); } - readonly #handleLauncherClick = (event: MouseEvent): void => { + #refreshDesktop(invoker: HTMLElement | null): void { + this.#contextMenu.close(false); + this.#drawer.close(false); + this.#drawer.refresh(); + this.#renderTasks(); + this.#windowLayer.render(); + this.#renderClock(); + this.#refreshCount += 1; + this.#status.textContent = `Desktop refreshed ${this.#refreshCount.toString()}`; + if (invoker?.isConnected) { + invoker.focus({ preventScroll: true }); + } + } + + readonly #handleDesktopContextMenu = (event: MouseEvent): void => { const target = event.target instanceof Element ? event.target : null; - const applicationId = - target?.closest("[data-application-id]")?.dataset.applicationId; - if (applicationId) { - this.#applicationManager.launch(toApplicationId(applicationId)); + if (target?.closest(".os-window")) { + return; + } + + event.preventDefault(); + this.#drawer.close(false); + const invoker = + this.#document.activeElement instanceof HTMLElement + ? this.#document.activeElement + : this.#workspace; + const workspaceBounds = this.#workspace.getBoundingClientRect(); + const keyboardInvocation = event.clientX === 0 && event.clientY === 0; + this.#contextMenu.open( + keyboardInvocation ? workspaceBounds.left + 16 : event.clientX, + keyboardInvocation ? workspaceBounds.top + 16 : event.clientY, + invoker, + ); + }; + + readonly #handleContextAction = ( + actionId: DesktopContextMenuActionId, + invoker: HTMLElement | null, + ): void => { + if (actionId === "open-application-drawer") { + this.#drawer.open(); + } else { + this.#refreshDesktop(invoker); } }; diff --git a/src/styles/windows.css b/src/styles/windows.css index dce7677..42c5569 100644 --- a/src/styles/windows.css +++ b/src/styles/windows.css @@ -31,6 +31,11 @@ animation: desktop-enter 350ms ease-out both; } +.desktop-shell__workspace:focus-visible { + outline: 1px solid var(--color-signal); + outline-offset: -3px; +} + .desktop-shell__identity { position: absolute; z-index: 0; @@ -193,12 +198,7 @@ overflow-x: auto; } -.application-launcher__label { - color: var(--color-signal); - font-size: 0.65rem; -} - -.application-launcher__button, +.application-drawer__trigger, .window-task-strip__button, .diagnostics-app__action { min-height: 2.5rem; @@ -210,6 +210,235 @@ cursor: pointer; } +.application-drawer__trigger { + display: inline-grid; + grid-template-columns: auto auto; + align-items: center; + gap: 0.6rem; + color: var(--color-ink); + font-size: 0.7rem; + text-transform: uppercase; +} + +.application-drawer__trigger::before { + width: 0.75rem; + height: 0.75rem; + border: 1px solid var(--color-signal); + background: + linear-gradient(90deg, transparent 42%, var(--color-signal) 42% 58%, transparent 58%), + linear-gradient(transparent 42%, var(--color-signal) 42% 58%, transparent 58%); + content: ""; +} + +.application-drawer__trigger:hover, +.application-drawer__trigger[aria-expanded="true"] { + border-color: var(--color-signal); + background: var(--color-panel-raised); +} + +.application-drawer__trigger[aria-expanded="true"]::before { + background: var(--color-signal); + box-shadow: 0 0 0.7rem rgb(143 240 189 / 30%); +} + +.application-drawer, +.desktop-context-menu { + z-index: 1000; + border: 1px solid var(--color-rule-strong); + color: var(--color-ink); + background: #0c1214; + box-shadow: 0 1.5rem 4rem rgb(0 0 0 / 65%); +} + +.application-drawer[hidden], +.desktop-context-menu[hidden] { + display: none; +} + +.application-drawer { + position: absolute; + bottom: 5rem; + left: 1rem; + display: grid; + width: min(24rem, calc(100% - 2rem)); + max-height: min(62vh, 28rem); + grid-template-rows: auto minmax(0, 1fr); + border-color: var(--color-rule-strong); + background: + linear-gradient(rgb(143 240 189 / 3%) 1px, transparent 1px), + linear-gradient(90deg, rgb(143 240 189 / 3%) 1px, transparent 1px), #0c1214; + background-size: 1.25rem 1.25rem; + box-shadow: + 0 0 0 1px rgb(143 240 189 / 6%), + 0 1.25rem 3rem rgb(0 0 0 / 58%); +} + +.application-drawer__header { + display: flex; + align-items: baseline; + gap: 0.35rem; + padding: 0.7rem 0.85rem; + border-bottom: 1px solid var(--color-rule); + background: rgb(16 23 25 / 94%); +} + +.application-drawer__eyebrow { + color: var(--color-signal); + font-size: 0.62rem; + text-transform: uppercase; +} + +.application-drawer__title { + margin: 0; + font-family: inherit; + font-size: 0.68rem; + font-weight: 700; + letter-spacing: 0; + text-transform: uppercase; +} + +.application-drawer__list { + display: grid; + grid-template-columns: repeat(3, minmax(0, 1fr)); + gap: 0.55rem; + min-height: 0; + padding: 0.85rem; + overflow-y: auto; + background: rgb(8 11 12 / 72%); +} + +.application-drawer__entry { + display: grid; + grid-template-rows: 3.25rem auto; + align-items: center; + justify-items: center; + gap: 0.65rem; + min-width: 0; + min-height: 7.5rem; + padding: 0.8rem 0.45rem; + border: 1px solid var(--color-rule); + border-radius: 2px; + color: var(--color-ink); + background: rgb(16 23 25 / 90%); + text-align: center; + cursor: pointer; +} + +.application-drawer__entry:hover, +.application-drawer__entry:focus-visible { + border-color: var(--color-signal); + background: rgb(22 32 35 / 96%); + box-shadow: inset 0 -2px var(--color-signal); +} + +.application-drawer__marker { + display: grid; + width: 3.25rem; + height: 3.25rem; + place-items: center; + border: 1px solid var(--color-signal); + color: var(--color-signal); + background: rgb(143 240 189 / 4%); + font-size: 0.75rem; +} + +.application-drawer__notes-icon { + width: 2.35rem; + height: 2.35rem; + stroke: currentColor; + stroke-width: 1.4; + stroke-linecap: square; + stroke-linejoin: miter; +} + +.application-drawer__notes-page { + fill: currentColor; + fill-opacity: 0.04; +} + +.application-drawer__notes-pencil { + fill: rgb(16 23 25); +} + +.application-drawer__calculator-icon { + width: 2.35rem; + height: 2.35rem; + stroke: currentColor; + stroke-width: 1.35; + stroke-linejoin: miter; +} + +.application-drawer__calculator-body { + fill: currentColor; + fill-opacity: 0.04; +} + +.application-drawer__calculator-display { + fill: rgb(16 23 25); +} + +.application-drawer__calculator-keys { + fill: currentColor; + stroke: none; +} + +.application-drawer__copy { + display: grid; + gap: 0; + min-width: 0; +} + +.application-drawer__name { + font-size: 0.66rem; + line-height: 1.35; + text-transform: uppercase; +} + +.application-drawer__description { + display: none; +} + +.desktop-context-menu { + position: fixed; + display: grid; + width: min(13rem, calc(100vw - 1rem)); + padding: 0.25rem; + border-color: var(--color-rule-strong); + box-shadow: + 0 0 0 1px rgb(143 240 189 / 5%), + 0 0.9rem 2rem rgb(0 0 0 / 55%); +} + +.desktop-context-menu__item { + display: grid; + min-height: 2rem; + grid-template-columns: minmax(0, 1fr) auto; + align-items: center; + gap: 0.75rem; + padding: 0.4rem 0.55rem; + border: 0; + border-radius: 0; + color: var(--color-ink); + background: transparent; + font-size: 0.65rem; + text-align: left; + text-transform: uppercase; + cursor: pointer; +} + +.desktop-context-menu__symbol { + color: var(--color-signal); + font-size: 0.85rem; + line-height: 1; +} + +.desktop-context-menu__item:hover, +.desktop-context-menu__item:focus-visible { + color: var(--color-signal); + background: rgb(143 240 189 / 9%); + box-shadow: inset 2px 0 var(--color-signal); +} + .window-task-strip__button { max-width: 13rem; overflow: hidden; @@ -303,6 +532,223 @@ line-height: 1.7; } +.notepad-app { + width: 100%; + height: 100%; + padding: 0.75rem; + background: + linear-gradient(rgb(143 240 189 / 3%) 1px, transparent 1px), + linear-gradient(90deg, rgb(143 240 189 / 3%) 1px, transparent 1px), #0c1214; + background-size: 1.5rem 1.5rem; +} + +.notepad-app__editor { + display: block; + width: 100%; + height: 100%; + min-width: 0; + min-height: 0; + padding: 1rem; + resize: none; + border: 1px solid var(--color-rule); + border-radius: 0; + outline: 0; + color: var(--color-ink); + caret-color: var(--color-signal); + background: rgb(8 11 12 / 92%); + font: inherit; + font-size: 0.78rem; + line-height: 1.7; +} + +.notepad-app__editor::placeholder { + color: var(--color-muted); +} + +.notepad-app__editor:focus-visible { + border-color: var(--color-signal); + box-shadow: inset 0 0 0 1px rgb(143 240 189 / 12%); +} + +.calculator-app { + display: grid; + grid-template-rows: minmax(5.5rem, auto) minmax(0, 1fr); + gap: 0.65rem; + width: 100%; + height: 100%; + min-width: 0; + min-height: 0; + padding: 0.75rem; + outline: 0; + background: + linear-gradient(rgb(143 240 189 / 3%) 1px, transparent 1px), + linear-gradient(90deg, rgb(143 240 189 / 3%) 1px, transparent 1px), #0c1214; + background-size: 1.5rem 1.5rem; +} + +.calculator-app__display-panel { + display: grid; + grid-template-rows: minmax(0.9rem, auto) minmax(0, 1fr); + gap: 0.35rem; + min-width: 0; + padding: 0.8rem 0.9rem; + border: 1px solid var(--color-rule-strong); + overflow: hidden; + background: rgb(8 11 12 / 96%); + font-variant-numeric: tabular-nums; + white-space: nowrap; +} + +.calculator-app:focus-visible .calculator-app__display-panel { + border-color: var(--color-signal); + box-shadow: inset 0 0 0 1px rgb(143 240 189 / 12%); +} + +.calculator-app__pending { + min-width: 0; + min-height: 0.9rem; + overflow: hidden; + color: var(--color-muted); + font-size: 0.68rem; + line-height: 1; + text-overflow: ellipsis; +} + +.calculator-app__display { + min-width: 0; + align-self: center; + overflow: hidden; + color: var(--color-ink); + font-size: 1.7rem; + line-height: 1; + text-align: right; + text-overflow: clip; +} + +.calculator-app__display-panel[data-state="error"] { + border-color: var(--color-alert); +} + +.calculator-app__display[data-state="error"] { + color: var(--color-alert); + font-size: 1.2rem; +} + +.calculator-app__keypad { + display: grid; + grid-template-columns: repeat(4, minmax(0, 1fr)); + grid-template-rows: repeat(5, minmax(2.7rem, 1fr)); + grid-auto-flow: row dense; + gap: 0.35rem; + min-width: 0; + min-height: 0; +} + +.calculator-app__key { + min-width: 0; + min-height: 0; + padding: 0.35rem; + border: 1px solid var(--color-rule); + border-radius: 0; + outline: 0; + color: var(--color-ink); + background: rgb(16 23 25 / 96%); + font: inherit; + font-size: 0.85rem; + cursor: pointer; +} + +.calculator-app__key:hover, +.calculator-app__key:focus-visible { + border-color: var(--color-signal); + background: rgb(22 32 35 / 98%); + box-shadow: inset 0 -2px var(--color-signal); +} + +.calculator-app__key--operator { + border-color: var(--color-rule-strong); + color: var(--color-signal); + font-size: 1rem; +} + +.calculator-app__key--operator[aria-pressed="true"] { + border-color: var(--color-signal); + color: var(--color-ink); + background: rgb(143 240 189 / 14%); + box-shadow: + inset 0 0 0 1px rgb(143 240 189 / 42%), + inset 0 -3px var(--color-signal); +} + +.calculator-app__key--utility { + color: var(--color-muted); + font-size: 0.7rem; +} + +.calculator-app__key--equals { + grid-row: span 2; + border-color: var(--color-signal); + color: #08110d; + background: var(--color-signal); + font-size: 1rem; +} + +.calculator-app__key--equals:hover, +.calculator-app__key--equals:focus-visible { + color: #08110d; + background: #b4ffd6; +} + +.calculator-app__key[data-calculator-command="digit:0"] { + grid-column: span 2; +} + +.clock-app { + display: grid; + width: 100%; + height: 100%; + min-width: 0; + min-height: 0; + padding: 1rem; + place-items: center; + overflow: hidden; + background: + linear-gradient(rgb(143 240 189 / 3%) 1px, transparent 1px), + linear-gradient(90deg, rgb(143 240 189 / 3%) 1px, transparent 1px), #0c1214; + background-size: 1.5rem 1.5rem; +} + +.clock-app__face { + display: grid; + width: min(100%, 28rem); + gap: 1rem; + padding: 1.35rem 1rem; + border-block: 1px solid var(--color-rule-strong); + justify-items: center; + background: rgb(8 11 12 / 72%); + text-align: center; +} + +.clock-app__time, +.clock-app__date { + display: block; + max-width: 100%; + overflow: hidden; + font-variant-numeric: tabular-nums; + line-height: 1; + white-space: nowrap; +} + +.clock-app__time { + color: var(--color-signal); + font-size: 3rem; +} + +.clock-app__date { + color: var(--color-muted); + font-size: 0.78rem; +} + @media (max-width: 44rem) { .desktop-shell { min-height: 28rem; @@ -342,6 +788,24 @@ grid-column: 1; } + .application-drawer { + right: 0.75rem; + bottom: 7.5rem; + left: 0.75rem; + width: auto; + max-height: min(56vh, 24rem); + } + + .application-drawer__list { + gap: 0.45rem; + padding: 0.7rem; + } + + .application-drawer__entry { + min-height: 6.75rem; + padding-inline: 0.3rem; + } + .window-task-strip { grid-column: 1 / -1; grid-row: 2; @@ -355,4 +819,8 @@ grid-column: 2; grid-row: 1; } + + .notepad-app { + padding: 0.5rem; + } } diff --git a/tests/e2e/calculator.spec.ts b/tests/e2e/calculator.spec.ts new file mode 100644 index 0000000..8400496 --- /dev/null +++ b/tests/e2e/calculator.spec.ts @@ -0,0 +1,226 @@ +import { expect, test, type Page } from "@playwright/test"; + +function monitorPageFailures(page: Page): string[] { + const failures: string[] = []; + page.on("console", (message) => { + if (message.type() === "error") { + failures.push(`console: ${message.text()}`); + } + }); + page.on("pageerror", (error) => failures.push(`page: ${error.message}`)); + page.on("requestfailed", (request) => { + failures.push(`request: ${request.url()} ${request.failure()?.errorText ?? "unknown failure"}`); + }); + return failures; +} + +async function openDesktop(page: Page): Promise { + const failures = monitorPageFailures(page); + await page.goto("/"); + await page.getByRole("button", { name: "Skip boot sequence" }).click(); + await expect(page.getByRole("heading", { name: "Desktop ready" })).toBeVisible(); + return failures; +} + +async function launchCalculator(page: Page): Promise { + await page.getByRole("button", { name: "Applications" }).click(); + const drawer = page.getByRole("dialog", { name: "Applications" }); + const calculatorEntry = drawer.getByRole("button", { name: "Calculator" }); + const marker = calculatorEntry.locator(".application-drawer__marker"); + const icon = marker.locator("svg.application-drawer__calculator-icon"); + await expect(calculatorEntry).toBeVisible(); + await expect(marker).toHaveAttribute("aria-hidden", "true"); + await expect(marker).toBeEmpty(); + await expect(icon).toBeVisible(); + await expect(icon).toHaveAttribute("viewBox", "0 0 32 32"); + await expect(icon).toHaveAttribute("aria-hidden", "true"); + await calculatorEntry.click(); + await expect(page.getByRole("dialog", { name: "Calculator" })).toBeVisible(); +} + +async function pressKeys(page: Page, names: readonly string[]): Promise { + const calculator = page.getByRole("dialog", { name: "Calculator" }); + for (const name of names) { + await calculator.getByRole("button", { name, exact: true }).click(); + } +} + +test("performs basic pointer calculations through one Calculator instance", async ({ page }) => { + const failures = await openDesktop(page); + await launchCalculator(page); + + const calculator = page.getByRole("dialog", { name: "Calculator" }); + const surface = calculator.locator(".calculator-app"); + const display = calculator.getByLabel("Calculator display"); + const task = page.getByRole("button", { name: "Focus Calculator" }); + await expect(surface).toBeFocused(); + await expect(display).toHaveText("0"); + await expect(task).toHaveCount(1); + + await pressKeys(page, ["1", "2", "Add", "5", "Equals"]); + await expect(display).toHaveText("17"); + + await pressKeys(page, ["Clear", "5", "Subtract", "8", "Equals"]); + await expect(display).toHaveText("-3"); + + await pressKeys(page, ["Clear", "6", "Multiply", "7", "Equals"]); + await expect(display).toHaveText("42"); + + await pressKeys(page, ["Clear", "8", "Divide", "2", "Equals"]); + await expect(display).toHaveText("4"); + + await pressKeys(page, [ + "Clear", + "1", + "Decimal point", + "5", + "Add", + "2", + "Decimal point", + "2", + "5", + "Equals", + ]); + await expect(display).toHaveText("3.75"); + + await pressKeys(page, ["Clear", "1", "2", "3", "Backspace"]); + await expect(display).toHaveText("12"); + + await pressKeys(page, ["Clear", "9", "Divide", "0", "Equals"]); + await expect(display).toHaveText("ERROR"); + await expect(display).toHaveAttribute("data-state", "error"); + await calculator.getByRole("button", { name: "Clear" }).click(); + await expect(display).toHaveText("0"); + + await calculator.getByRole("button", { name: "Minimize window" }).click(); + await expect(calculator).toBeHidden(); + await launchCalculator(page); + await expect(calculator).toBeVisible(); + await expect(page.getByRole("dialog", { name: "Calculator" })).toHaveCount(1); + await expect(task).toHaveCount(1); + + await calculator.getByRole("button", { name: "Close window" }).click(); + await expect(calculator).toHaveCount(0); + await launchCalculator(page); + await expect(page.getByLabel("Calculator display")).toHaveText("0"); + expect(failures).toEqual([]); +}); + +test("projects pending operations into the display and selected operator", async ({ page }) => { + const failures = await openDesktop(page); + await launchCalculator(page); + + const calculator = page.getByRole("dialog", { name: "Calculator" }); + const display = calculator.getByLabel("Calculator display"); + const pendingDisplay = calculator.locator(".calculator-app__pending"); + const operators = [ + { name: "Add", symbol: "+" }, + { name: "Subtract", symbol: "−" }, + { name: "Multiply", symbol: "×" }, + { name: "Divide", symbol: "÷" }, + ] as const; + + await expect(calculator).not.toContainText("SHADOW / CALCULATOR"); + await expect(calculator).not.toContainText("4-OP"); + + for (const operator of operators) { + await pressKeys(page, ["Clear", "1", "2", operator.name]); + await expect(pendingDisplay).toHaveText(`12 ${operator.symbol}`); + await expect(calculator.getByRole("button", { name: operator.name })).toHaveAttribute( + "aria-pressed", + "true", + ); + } + + await pressKeys(page, ["Clear", "1", "2", "Add"]); + const add = calculator.getByRole("button", { name: "Add" }); + const multiply = calculator.getByRole("button", { name: "Multiply" }); + await multiply.click(); + await expect(display).toHaveText("12"); + await expect(pendingDisplay).toHaveText("12 ×"); + await expect(add).toHaveAttribute("aria-pressed", "false"); + await expect(multiply).toHaveAttribute("aria-pressed", "true"); + + await pressKeys(page, ["2", "0"]); + await expect(display).toHaveText("20"); + await expect(pendingDisplay).toHaveText("12 ×"); + await calculator.getByRole("button", { name: "Equals" }).click(); + await expect(display).toHaveText("240"); + await expect(pendingDisplay).toBeEmpty(); + await expect(multiply).toHaveAttribute("aria-pressed", "false"); + + await pressKeys(page, ["1", "2", "Subtract", "Clear"]); + await expect(pendingDisplay).toBeEmpty(); + await expect(calculator.getByRole("button", { name: "Subtract" })).toHaveAttribute( + "aria-pressed", + "false", + ); + + await pressKeys(page, ["9", "Divide", "0", "Equals"]); + await expect(display).toHaveText("ERROR"); + await expect(pendingDisplay).toBeEmpty(); + await expect(calculator.getByRole("button", { name: "Divide" })).toHaveAttribute( + "aria-pressed", + "false", + ); + expect(failures).toEqual([]); +}); + +test("supports calculator keyboard input, restart, and the mobile viewport", async ({ page }) => { + const failures = monitorPageFailures(page); + await page.setViewportSize({ width: 360, height: 740 }); + await page.goto("/"); + await page.getByRole("button", { name: "Skip boot sequence" }).click(); + await launchCalculator(page); + + const calculator = page.getByRole("dialog", { name: "Calculator" }); + const surface = calculator.locator(".calculator-app"); + const display = calculator.getByLabel("Calculator display"); + const pendingDisplay = calculator.locator(".calculator-app__pending"); + await expect(surface).toBeFocused(); + + await page.keyboard.type("12+"); + await expect(pendingDisplay).toHaveText("12 +"); + await expect(calculator.getByRole("button", { name: "Add" })).toHaveAttribute( + "aria-pressed", + "true", + ); + await page.keyboard.type("5"); + await page.keyboard.press("Enter"); + await expect(display).toHaveText("17"); + await expect(pendingDisplay).toBeEmpty(); + + await page.keyboard.press("Escape"); + await expect(display).toHaveText("0"); + await expect(calculator).toBeVisible(); + + await page.keyboard.type("9/0="); + await expect(display).toHaveText("ERROR"); + await page.keyboard.press("c"); + await expect(display).toHaveText("0"); + + const mobileBounds = await calculator.evaluate((windowElement) => { + const windowBounds = windowElement.getBoundingClientRect(); + const workAreaBounds = windowElement.parentElement!.getBoundingClientRect(); + const bounds = (rect: DOMRect): Record<"x" | "y" | "width" | "height", number> => ({ + x: rect.x, + y: rect.y, + width: rect.width, + height: rect.height, + }); + return { window: bounds(windowBounds), workArea: bounds(workAreaBounds) }; + }); + expect(mobileBounds.window).toEqual(mobileBounds.workArea); + + await page.getByRole("button", { name: "Restart SHADOW OS" }).click(); + await page.getByRole("button", { name: "Skip boot sequence" }).click(); + await launchCalculator(page); + await expect(page.getByLabel("Calculator display")).toHaveText("0"); + + const pageSize = await page.locator("body").evaluate((body) => ({ + scrollWidth: body.scrollWidth, + viewportWidth: document.documentElement.clientWidth, + })); + expect(pageSize.scrollWidth).toBeLessThanOrEqual(pageSize.viewportWidth); + expect(failures).toEqual([]); +}); diff --git a/tests/e2e/clock.spec.ts b/tests/e2e/clock.spec.ts new file mode 100644 index 0000000..d5bb484 --- /dev/null +++ b/tests/e2e/clock.spec.ts @@ -0,0 +1,190 @@ +import { expect, test, type Page } from "@playwright/test"; + +async function installTimerCounter(page: Page): Promise { + await page.addInitScript(() => { + const originalSetTimeout = window.setTimeout.bind(window); + const originalClearTimeout = window.clearTimeout.bind(window); + const activeTimers = new Set(); + + window.setTimeout = (( + handler: TimerHandler, + timeout?: number, + ...arguments_: unknown[] + ): number => { + if (typeof handler !== "function") { + const timeoutId = originalSetTimeout(handler, timeout, ...arguments_); + activeTimers.add(timeoutId); + return timeoutId; + } + + const callback = handler as (...callbackArguments: unknown[]) => void; + let timeoutId = 0; + const trackedHandler = (...callbackArguments: unknown[]): void => { + activeTimers.delete(timeoutId); + callback(...callbackArguments); + }; + timeoutId = originalSetTimeout(trackedHandler, timeout, ...arguments_); + activeTimers.add(timeoutId); + return timeoutId; + }) as typeof window.setTimeout; + + window.clearTimeout = ((timeoutId?: number): void => { + if (timeoutId !== undefined) { + activeTimers.delete(timeoutId); + } + originalClearTimeout(timeoutId); + }) as typeof window.clearTimeout; + + Object.defineProperty(window, "__afterbootActiveTimerCount", { + get: () => activeTimers.size, + }); + }); +} + +async function activeTimerCount(page: Page): Promise { + return page.evaluate( + () => + (window as unknown as Window & { readonly __afterbootActiveTimerCount: number }) + .__afterbootActiveTimerCount, + ); +} + +function monitorPageFailures(page: Page): string[] { + const failures: string[] = []; + page.on("console", (message) => { + if (message.type() === "error") { + failures.push(`console: ${message.text()}`); + } + }); + page.on("pageerror", (error) => failures.push(`page: ${error.message}`)); + page.on("requestfailed", (request) => { + failures.push(`request: ${request.url()} ${request.failure()?.errorText ?? "unknown failure"}`); + }); + return failures; +} + +async function openDesktop(page: Page): Promise { + const failures = monitorPageFailures(page); + await page.goto("/"); + await page.getByRole("button", { name: "Skip boot sequence" }).click(); + await expect(page.getByRole("heading", { name: "Desktop ready" })).toBeVisible(); + return failures; +} + +async function launchClock(page: Page): Promise { + await page.getByRole("button", { name: "Applications" }).click(); + const drawer = page.getByRole("dialog", { name: "Applications" }); + const clockEntry = drawer.getByRole("button", { name: "Clock" }); + await expect(clockEntry).toBeVisible(); + await clockEntry.click(); + await expect(page.getByRole("dialog", { name: "Clock" })).toBeVisible(); +} + +test("displays and updates the injected local time through one Clock instance", async ({ + page, +}) => { + await installTimerCounter(page); + const failures = await openDesktop(page); + const baselineTimers = await activeTimerCount(page); + await launchClock(page); + + const clockWindow = page.getByRole("dialog", { name: "Clock" }); + const time = clockWindow.locator(".clock-app__time"); + const date = clockWindow.locator(".clock-app__date"); + const task = page.getByRole("button", { name: "Focus Clock" }); + const initialIso = await time.getAttribute("datetime"); + expect(initialIso).not.toBeNull(); + + const expected = await page.evaluate((timestamp) => { + const value = new Date(timestamp!); + const pad = (part: number): string => part.toString().padStart(2, "0"); + return { + time: `${pad(value.getHours())}:${pad(value.getMinutes())}:${pad(value.getSeconds())}`, + date: `${value.getFullYear()}.${pad(value.getMonth() + 1)}.${pad(value.getDate())}`, + }; + }, initialIso); + + await expect(time).toHaveText(expected.time); + await expect(date).toHaveText(expected.date); + await expect(time).toHaveAttribute("aria-label", `Current time: ${expected.time}`); + await expect(date).toHaveAttribute("aria-label", `Current date: ${expected.date}`); + await expect(task).toHaveCount(1); + expect(await activeTimerCount(page)).toBe(baselineTimers + 1); + + await expect.poll(() => time.getAttribute("datetime"), { timeout: 2_500 }).not.toBe(initialIso); + + await launchClock(page); + await expect(page.getByRole("dialog", { name: "Clock" })).toHaveCount(1); + await expect(task).toHaveCount(1); + expect(await activeTimerCount(page)).toBe(baselineTimers + 1); + + await clockWindow.getByRole("button", { name: "Minimize window" }).click(); + await expect(clockWindow).toBeHidden(); + expect(await activeTimerCount(page)).toBe(baselineTimers + 1); + await page.getByRole("button", { name: "Restore Clock" }).click(); + await expect(clockWindow).toBeVisible(); + + await clockWindow.getByRole("button", { name: "Close window" }).click(); + await expect(clockWindow).toHaveCount(0); + await expect(task).toHaveCount(0); + expect(await activeTimerCount(page)).toBe(baselineTimers); + + await launchClock(page); + await expect(page.getByRole("dialog", { name: "Clock" })).toHaveCount(1); + await expect(page.getByRole("dialog", { name: "Clock" }).locator(".clock-app__time")).toHaveText( + /^\d{2}:\d{2}:\d{2}$/, + ); + expect(await activeTimerCount(page)).toBe(baselineTimers + 1); + expect(failures).toEqual([]); +}); + +test("keeps Clock contained and restart-safe at the mobile viewport", async ({ page }) => { + const failures = monitorPageFailures(page); + await page.setViewportSize({ width: 360, height: 740 }); + await page.goto("/"); + await page.getByRole("button", { name: "Skip boot sequence" }).click(); + await launchClock(page); + + const clockWindow = page.getByRole("dialog", { name: "Clock" }); + const time = clockWindow.locator(".clock-app__time"); + const date = clockWindow.locator(".clock-app__date"); + await expect(time).toHaveText(/^\d{2}:\d{2}:\d{2}$/); + await expect(date).toHaveText(/^\d{4}\.\d{2}\.\d{2}$/); + + const mobileBounds = await clockWindow.evaluate((windowElement) => { + const windowBounds = windowElement.getBoundingClientRect(); + const workAreaBounds = windowElement.parentElement!.getBoundingClientRect(); + const timeBounds = windowElement.querySelector(".clock-app__time")!.getBoundingClientRect(); + const bounds = (rect: DOMRect): Record<"x" | "y" | "width" | "height", number> => ({ + x: rect.x, + y: rect.y, + width: rect.width, + height: rect.height, + }); + return { + window: bounds(windowBounds), + workArea: bounds(workAreaBounds), + time: bounds(timeBounds), + }; + }); + expect(mobileBounds.window).toEqual(mobileBounds.workArea); + expect(mobileBounds.time.x).toBeGreaterThanOrEqual(mobileBounds.window.x); + expect(mobileBounds.time.x + mobileBounds.time.width).toBeLessThanOrEqual( + mobileBounds.window.x + mobileBounds.window.width, + ); + + await page.getByRole("button", { name: "Restart SHADOW OS" }).click(); + await page.getByRole("button", { name: "Skip boot sequence" }).click(); + await expect(page.getByRole("dialog", { name: "Clock" })).toHaveCount(0); + await launchClock(page); + await expect(page.getByRole("dialog", { name: "Clock" }).locator(".clock-app__time")).toHaveText( + /^\d{2}:\d{2}:\d{2}$/, + ); + + const pageSize = await page.locator("body").evaluate((body) => ({ + scrollWidth: body.scrollWidth, + viewportWidth: document.documentElement.clientWidth, + })); + expect(pageSize.scrollWidth).toBeLessThanOrEqual(pageSize.viewportWidth); + expect(failures).toEqual([]); +}); diff --git a/tests/e2e/notepad.spec.ts b/tests/e2e/notepad.spec.ts new file mode 100644 index 0000000..9668f1a --- /dev/null +++ b/tests/e2e/notepad.spec.ts @@ -0,0 +1,153 @@ +import { expect, test, type Page } from "@playwright/test"; + +function monitorPageFailures(page: Page): string[] { + const failures: string[] = []; + page.on("console", (message) => { + if (message.type() === "error") { + failures.push(`console: ${message.text()}`); + } + }); + page.on("pageerror", (error) => failures.push(`page: ${error.message}`)); + page.on("requestfailed", (request) => { + failures.push(`request: ${request.url()} ${request.failure()?.errorText ?? "unknown failure"}`); + }); + return failures; +} + +async function openDesktop(page: Page): Promise { + const failures = monitorPageFailures(page); + await page.goto("/"); + await page.getByRole("button", { name: "Skip boot sequence" }).click(); + await expect(page.getByRole("heading", { name: "Desktop ready" })).toBeVisible(); + return failures; +} + +async function launchNotepad(page: Page): Promise { + await page.getByRole("button", { name: "Applications" }).click(); + const drawer = page.getByRole("dialog", { name: "Applications" }); + const notesEntry = drawer.getByRole("button", { name: "Notes" }); + const marker = notesEntry.locator(".application-drawer__marker"); + const icon = marker.locator("svg.application-drawer__notes-icon"); + await expect(notesEntry).toBeVisible(); + await expect(marker).toHaveAttribute("aria-hidden", "true"); + await expect(marker).toBeEmpty(); + await expect(icon).toBeVisible(); + await expect(icon).toHaveAttribute("viewBox", "0 0 32 32"); + await expect(icon).toHaveAttribute("aria-hidden", "true"); + await notesEntry.click(); + await expect(page.getByRole("dialog", { name: "Notes" })).toBeVisible(); +} + +test("edits temporary text through one running Notepad instance", async ({ page }) => { + const failures = await openDesktop(page); + await launchNotepad(page); + + const notepad = page.getByRole("dialog", { name: "Notes" }); + const editor = page.getByRole("textbox", { name: "Notes editor" }); + const task = page.getByRole("button", { name: "Focus Notes" }); + await expect(editor).toBeFocused(); + await expect(task).toHaveCount(1); + + await page.keyboard.insertText("First line\nSecond line"); + await expect(editor).toHaveValue("First line\nSecond line"); + await page.keyboard.press("Control+A"); + await page.keyboard.insertText("Revised text\nWith two lines"); + await expect(editor).toHaveValue("Revised text\nWith two lines"); + await page.keyboard.press("Escape"); + await expect(editor).toHaveValue("Revised text\nWith two lines"); + + await launchNotepad(page); + await expect(page.getByRole("dialog", { name: "Notes" })).toHaveCount(1); + await expect(task).toHaveCount(1); + await expect(editor).toHaveValue("Revised text\nWith two lines"); + + const titleBar = notepad.locator(".os-window__titlebar"); + const initialBounds = await notepad.boundingBox(); + const titleBounds = await titleBar.boundingBox(); + expect(initialBounds).not.toBeNull(); + expect(titleBounds).not.toBeNull(); + await page.mouse.move(titleBounds!.x + 80, titleBounds!.y + 20); + await page.mouse.down(); + await page.mouse.move(titleBounds!.x + 130, titleBounds!.y + 55, { steps: 3 }); + await page.mouse.up(); + expect((await notepad.boundingBox())!.x).toBeGreaterThan(initialBounds!.x + 30); + + const resizeHandle = notepad.locator(".os-window__resize-handle"); + const handleBounds = await resizeHandle.boundingBox(); + expect(handleBounds).not.toBeNull(); + await page.mouse.move(handleBounds!.x + 8, handleBounds!.y + 8); + await page.mouse.down(); + await page.mouse.move(handleBounds!.x + 68, handleBounds!.y + 48, { steps: 3 }); + await page.mouse.up(); + await expect(editor).toHaveValue("Revised text\nWith two lines"); + + const desktop = page.getByLabel("SHADOW OS desktop work area"); + await desktop.focus(); + await page.keyboard.press("Shift+F10"); + await page.getByRole("menuitem", { name: "Refresh Desktop" }).click(); + await expect(editor).toHaveValue("Revised text\nWith two lines"); + + await notepad.getByRole("button", { name: "Minimize window" }).click(); + await expect(notepad).toBeHidden(); + await page.getByRole("button", { name: "Restore Notes" }).click(); + await expect(notepad).toBeVisible(); + await expect(editor).toHaveValue("Revised text\nWith two lines"); + + await notepad.getByRole("button", { name: "Maximize window" }).click(); + await expect(notepad).toHaveAttribute("data-mode", "maximized"); + await notepad.getByRole("button", { name: "Restore window" }).click(); + await expect(notepad).toHaveAttribute("data-mode", "normal"); + await expect(editor).toHaveValue("Revised text\nWith two lines"); + + const nativeContextMenu = await editor.evaluate((surface) => { + const event = new MouseEvent("contextmenu", { bubbles: true, cancelable: true }); + surface.dispatchEvent(event); + return !event.defaultPrevented; + }); + expect(nativeContextMenu).toBe(true); + + await notepad.getByRole("button", { name: "Close window" }).click(); + await expect(notepad).toHaveCount(0); + await expect(task).toHaveCount(0); + + await launchNotepad(page); + await expect(page.getByRole("textbox", { name: "Notes editor" })).toBeFocused(); + await expect(page.getByRole("textbox", { name: "Notes editor" })).toHaveValue(""); + expect(failures).toEqual([]); +}); + +test("discards Notepad text on restart and remains usable on mobile", async ({ page }) => { + const failures = monitorPageFailures(page); + await page.setViewportSize({ width: 360, height: 740 }); + await page.goto("/"); + await page.getByRole("button", { name: "Skip boot sequence" }).click(); + await launchNotepad(page); + + const editor = page.getByRole("textbox", { name: "Notes editor" }); + await editor.fill("Temporary mobile text"); + await expect(editor).toHaveValue("Temporary mobile text"); + const mobileBounds = await page.getByRole("dialog", { name: "Notes" }).evaluate((notepad) => { + const windowBounds = notepad.getBoundingClientRect(); + const workAreaBounds = notepad.parentElement!.getBoundingClientRect(); + const bounds = (rect: DOMRect): Record<"x" | "y" | "width" | "height", number> => ({ + x: rect.x, + y: rect.y, + width: rect.width, + height: rect.height, + }); + return { window: bounds(windowBounds), workArea: bounds(workAreaBounds) }; + }); + expect(mobileBounds.window).toEqual(mobileBounds.workArea); + + await page.getByRole("button", { name: "Restart SHADOW OS" }).click(); + await page.getByRole("button", { name: "Skip boot sequence" }).click(); + await launchNotepad(page); + await expect(page.getByRole("textbox", { name: "Notes editor" })).toHaveValue(""); + + const pageSize = await page.locator("body").evaluate((body) => ({ + scrollWidth: body.scrollWidth, + viewportWidth: document.documentElement.clientWidth, + })); + expect(pageSize.scrollWidth).toBeLessThanOrEqual(pageSize.viewportWidth); + expect(failures).toEqual([]); +}); diff --git a/tests/e2e/shell-foundation.spec.ts b/tests/e2e/shell-foundation.spec.ts new file mode 100644 index 0000000..630316f --- /dev/null +++ b/tests/e2e/shell-foundation.spec.ts @@ -0,0 +1,143 @@ +import { expect, test, type Page } from "@playwright/test"; + +function monitorPageFailures(page: Page): string[] { + const failures: string[] = []; + page.on("console", (message) => { + if (message.type() === "error") { + failures.push(`console: ${message.text()}`); + } + }); + page.on("pageerror", (error) => failures.push(`page: ${error.message}`)); + page.on("requestfailed", (request) => { + failures.push(`request: ${request.url()} ${request.failure()?.errorText ?? "unknown failure"}`); + }); + return failures; +} + +async function openDesktop(page: Page): Promise { + const failures = monitorPageFailures(page); + await page.goto("/"); + await page.getByRole("button", { name: "Skip boot sequence" }).click(); + await expect(page.getByRole("heading", { name: "Desktop ready" })).toBeVisible(); + return failures; +} + +async function openDrawer(page: Page): Promise { + await page.getByRole("button", { name: "Applications" }).click(); + await expect(page.getByRole("dialog", { name: "Applications" })).toBeVisible(); +} + +async function launchDiagnostics(page: Page): Promise { + await openDrawer(page); + await page + .getByRole("dialog", { name: "Applications" }) + .getByRole("button", { name: /System Diagnostics/ }) + .click(); + await expect(page.getByRole("dialog", { name: "System Diagnostics" })).toBeVisible(); +} + +test("discovers applications in the drawer while the task strip tracks running windows", async ({ + page, +}) => { + const failures = await openDesktop(page); + const trigger = page.getByRole("button", { name: "Applications" }); + const taskStrip = page.getByRole("navigation", { name: "Open windows" }); + + await expect(taskStrip.getByRole("button")).toHaveCount(0); + await trigger.focus(); + await page.keyboard.press("Enter"); + const drawer = page.getByRole("dialog", { name: "Applications" }); + const diagnostics = drawer.getByRole("button", { name: /System Diagnostics/ }); + await expect(diagnostics).toBeFocused(); + + await page.keyboard.press("Escape"); + await expect(drawer).toBeHidden(); + await expect(trigger).toBeFocused(); + + await openDrawer(page); + await page.locator(".system-header").click(); + await expect(drawer).toBeHidden(); + + await launchDiagnostics(page); + await expect(taskStrip.getByRole("button", { name: "Focus System Diagnostics" })).toHaveCount(1); + expect(failures).toEqual([]); +}); + +test("provides a scoped keyboard-accessible desktop context menu", async ({ page }) => { + const failures = await openDesktop(page); + const desktop = page.getByLabel("SHADOW OS desktop work area"); + + const desktopPrevented = await desktop.evaluate((surface) => { + const event = new MouseEvent("contextmenu", { + bubbles: true, + cancelable: true, + clientX: 40, + clientY: 40, + }); + surface.dispatchEvent(event); + return event.defaultPrevented; + }); + expect(desktopPrevented).toBe(true); + const menu = page.getByRole("menu", { name: "Desktop actions" }); + await expect(menu).toBeVisible(); + await expect(menu.getByRole("menuitem", { name: "Refresh Desktop" })).toBeFocused(); + + await page.keyboard.press("Escape"); + await expect(menu).toBeHidden(); + + await desktop.focus(); + await page.keyboard.press("Shift+F10"); + await expect(menu).toBeVisible(); + await page.keyboard.press("ArrowDown"); + await expect(menu.getByRole("menuitem", { name: "Applications" })).toBeFocused(); + await page.keyboard.press("Enter"); + const drawer = page.getByRole("dialog", { name: "Applications" }); + await expect(drawer).toBeVisible(); + + await drawer.getByRole("button", { name: /System Diagnostics/ }).click(); + await expect(page.getByRole("dialog", { name: "System Diagnostics" })).toBeVisible(); + const applicationPrevented = await page.locator(".diagnostics-app").evaluate((surface) => { + const event = new MouseEvent("contextmenu", { bubbles: true, cancelable: true }); + surface.dispatchEvent(event); + return event.defaultPrevented; + }); + expect(applicationPrevented).toBe(false); + expect(failures).toEqual([]); +}); + +test("refreshes desktop presentation without navigation or application loss", async ({ page }) => { + const failures = await openDesktop(page); + await launchDiagnostics(page); + const primary = page.getByRole("dialog", { name: "System Diagnostics" }); + await primary.getByRole("button", { name: "Open lifecycle detail" }).click(); + const detail = page.getByRole("dialog", { name: "Lifecycle Detail 01" }); + await detail.getByRole("button", { name: "Maximize window" }).click(); + const primaryBounds = await primary.boundingBox(); + const detailBounds = await detail.boundingBox(); + await page.evaluate(() => { + document.documentElement.dataset.refreshSentinel = "present"; + }); + + const desktop = page.getByLabel("SHADOW OS desktop work area"); + await desktop.focus(); + await page.keyboard.press("Shift+F10"); + await page.getByRole("menuitem", { name: "Refresh Desktop" }).click(); + + await expect(page.getByText("Desktop refreshed 1")).toHaveText("Desktop refreshed 1"); + await expect(page.getByText("ENVIRONMENT / CYCLE 01")).toBeVisible(); + await expect(page.getByRole("dialog")).toHaveCount(2); + await expect(detail).toHaveAttribute("data-mode", "maximized"); + await expect(detail).toHaveAttribute("data-active", "true"); + expect(await primary.boundingBox()).toEqual(primaryBounds); + expect(await detail.boundingBox()).toEqual(detailBounds); + expect(await page.evaluate(() => document.documentElement.dataset.refreshSentinel)).toBe( + "present", + ); + + await desktop.focus(); + await page.keyboard.press("Shift+F10"); + await expect(page.getByRole("menu", { name: "Desktop actions" })).toBeVisible(); + await page.locator(".system-header").click(); + await expect(page.getByRole("menu", { name: "Desktop actions" })).toBeHidden(); + expect(failures).toEqual([]); +}); diff --git a/tests/e2e/windows-applications.spec.ts b/tests/e2e/windows-applications.spec.ts index b8037ed..9334095 100644 --- a/tests/e2e/windows-applications.spec.ts +++ b/tests/e2e/windows-applications.spec.ts @@ -23,8 +23,17 @@ async function openDesktop(page: Page): Promise { return failures; } +async function openAppDrawer(page: Page): Promise { + await page.getByRole("button", { name: "Applications" }).click(); + await expect(page.getByRole("dialog", { name: "Applications" })).toBeVisible(); +} + async function launchDiagnostics(page: Page): Promise { - await page.getByRole("button", { name: "System Diagnostics" }).click(); + await openAppDrawer(page); + await page + .getByRole("dialog", { name: "Applications" }) + .getByRole("button", { name: /System Diagnostics/ }) + .click(); await expect(page.getByRole("dialog", { name: "System Diagnostics" })).toBeVisible(); } @@ -32,14 +41,12 @@ test("launches one application instance and coordinates multiple owned windows", page, }) => { const failures = await openDesktop(page); - const launcher = page.getByRole("button", { name: "System Diagnostics", exact: true }); - - await launcher.click(); + await launchDiagnostics(page); const primary = page.getByRole("dialog", { name: "System Diagnostics" }); await expect(primary).toBeVisible(); await expect(primary).toContainText("application-instance-1"); - await launcher.click(); + await launchDiagnostics(page); await expect(page.getByRole("dialog")).toHaveCount(1); await expect(primary).toHaveAttribute("data-active", "true"); @@ -105,15 +112,21 @@ test("minimizes, restores, maximizes, restores, and closes a window", async ({ p await dialog.getByRole("button", { name: "Close window" }).click(); await expect(dialog).toHaveCount(0); - await expect(page.getByRole("button", { name: "System Diagnostics" })).toBeFocused(); + await expect(page.getByRole("button", { name: "Applications" })).toBeFocused(); expect(failures).toEqual([]); }); test("supports keyboard launch and window controls without global shortcuts", async ({ page }) => { const failures = await openDesktop(page); - const launcher = page.getByRole("button", { name: "System Diagnostics" }); + const launcher = page.getByRole("button", { name: "Applications" }); await launcher.focus(); await page.keyboard.press("Enter"); + await expect( + page + .getByRole("dialog", { name: "Applications" }) + .getByRole("button", { name: /System Diagnostics/ }), + ).toBeFocused(); + await page.keyboard.press("Enter"); const dialog = page.getByRole("dialog", { name: "System Diagnostics" }); await expect(dialog).toBeFocused(); diff --git a/tests/integration/application-window-lifecycle.test.ts b/tests/integration/application-window-lifecycle.test.ts index 3e95e1f..ad5c436 100644 --- a/tests/integration/application-window-lifecycle.test.ts +++ b/tests/integration/application-window-lifecycle.test.ts @@ -1,13 +1,139 @@ import { describe, expect, it, vi } from "vitest"; +import { + CALCULATOR_APPLICATION_ID, + createCalculatorDefinition, +} from "../../src/applications/built-in/calculator"; +import { CLOCK_APPLICATION_ID, createClockDefinition } from "../../src/applications/built-in/clock"; +import { + createNotepadDefinition, + NOTEPAD_APPLICATION_ID, +} from "../../src/applications/built-in/notepad"; import type { ApplicationContext } from "../../src/applications/framework/application"; import { ApplicationManager } from "../../src/applications/framework/application-manager"; import { ApplicationRegistry } from "../../src/applications/framework/application-registry"; import { toApplicationId } from "../../src/core/identity/identifiers"; import { WindowManager } from "../../src/shell/windows/window-manager"; import { FakeIdGenerator } from "../helpers/fake-id-generator"; +import { FakeClock } from "../helpers/fake-clock"; describe("application and window lifecycle", () => { + it("registers Clock and gives closed or reset launches fresh instances", () => { + const registry = new ApplicationRegistry([createClockDefinition(new FakeClock())]); + const ids = new FakeIdGenerator(); + const windows = new WindowManager(ids, { x: 0, y: 0, width: 1000, height: 700 }); + const applications = new ApplicationManager(registry, windows, ids); + + expect(registry.list().map((manifest) => manifest.name)).toEqual(["Clock"]); + + const firstInstanceId = applications.launch(CLOCK_APPLICATION_ID); + const firstWindowId = applications.snapshot.instances[0]!.primaryWindowId; + + expect(applications.launch(CLOCK_APPLICATION_ID)).toBe(firstInstanceId); + expect(applications.snapshot.instances).toHaveLength(1); + expect(windows.snapshot.windows[0]).toMatchObject({ id: firstWindowId, title: "Clock" }); + + expect(applications.closeWindow(firstWindowId)).toBe(true); + expect(applications.snapshot.instances).toEqual([]); + expect(windows.snapshot.windows).toEqual([]); + + const secondInstanceId = applications.launch(CLOCK_APPLICATION_ID); + expect(secondInstanceId).not.toBe(firstInstanceId); + + applications.reset(); + expect(applications.snapshot.instances).toEqual([]); + expect(windows.snapshot.windows).toEqual([]); + }); + + it("registers Calculator and gives closed or reset launches fresh instances", () => { + const registry = new ApplicationRegistry([createCalculatorDefinition()]); + const ids = new FakeIdGenerator(); + const windows = new WindowManager(ids, { x: 0, y: 0, width: 1000, height: 700 }); + const applications = new ApplicationManager(registry, windows, ids); + + expect(registry.list().map((manifest) => manifest.name)).toEqual(["Calculator"]); + + const firstInstanceId = applications.launch(CALCULATOR_APPLICATION_ID); + const firstWindowId = applications.snapshot.instances[0]!.primaryWindowId; + + expect(applications.launch(CALCULATOR_APPLICATION_ID)).toBe(firstInstanceId); + expect(applications.snapshot.instances).toHaveLength(1); + expect(windows.snapshot.windows[0]).toMatchObject({ + id: firstWindowId, + title: "Calculator", + }); + + expect(applications.closeWindow(firstWindowId)).toBe(true); + expect(applications.snapshot.instances).toEqual([]); + expect(windows.snapshot.windows).toEqual([]); + + const secondInstanceId = applications.launch(CALCULATOR_APPLICATION_ID); + expect(secondInstanceId).not.toBe(firstInstanceId); + + applications.reset(); + expect(applications.snapshot.instances).toEqual([]); + expect(windows.snapshot.windows).toEqual([]); + }); + + it("registers Notepad and gives each closed or reset lifecycle a fresh instance", () => { + const registry = new ApplicationRegistry([createNotepadDefinition()]); + const ids = new FakeIdGenerator(); + const windows = new WindowManager(ids, { x: 0, y: 0, width: 1000, height: 700 }); + const applications = new ApplicationManager(registry, windows, ids); + + expect(registry.list().map((manifest) => manifest.name)).toEqual(["Notes"]); + + const firstInstanceId = applications.launch(NOTEPAD_APPLICATION_ID); + const firstWindowId = applications.snapshot.instances[0]!.primaryWindowId; + + expect(applications.launch(NOTEPAD_APPLICATION_ID)).toBe(firstInstanceId); + expect(applications.snapshot.instances).toHaveLength(1); + expect(windows.snapshot.windows[0]).toMatchObject({ + id: firstWindowId, + title: "Notes", + }); + + expect(applications.closeWindow(firstWindowId)).toBe(true); + expect(applications.snapshot.instances).toEqual([]); + expect(windows.snapshot.windows).toEqual([]); + + const secondInstanceId = applications.launch(NOTEPAD_APPLICATION_ID); + expect(secondInstanceId).not.toBe(firstInstanceId); + + applications.reset(); + expect(applications.snapshot.instances).toEqual([]); + expect(windows.snapshot.windows).toEqual([]); + }); + + it("launches the registry catalog through the manager without duplicating an instance", () => { + const applicationId = toApplicationId("system.diagnostics"); + const registry = new ApplicationRegistry([ + { + manifest: { + id: applicationId, + name: "System Diagnostics", + description: "Inspect the M2 application contract.", + window: { title: "System Diagnostics" }, + }, + create: () => ({ + primaryView: { mount: () => () => undefined }, + dispose: () => undefined, + }), + }, + ]); + const ids = new FakeIdGenerator(); + const windows = new WindowManager(ids, { x: 0, y: 0, width: 1000, height: 700 }); + const applications = new ApplicationManager(registry, windows, ids); + const installedApplicationId = registry.list()[0]!.id; + + expect(windows.snapshot.windows).toEqual([]); + const instanceId = applications.launch(installedApplicationId); + + expect(applications.launch(installedApplicationId)).toBe(instanceId); + expect(applications.snapshot.instances).toHaveLength(1); + expect(windows.snapshot.windows).toHaveLength(1); + }); + it("coordinates startup registration, launch, multiple windows, relaunch, and close", () => { const applicationId = toApplicationId("system.diagnostics"); const dispose = vi.fn(); diff --git a/tests/unit/calculator-model.test.ts b/tests/unit/calculator-model.test.ts new file mode 100644 index 0000000..2129294 --- /dev/null +++ b/tests/unit/calculator-model.test.ts @@ -0,0 +1,201 @@ +import { describe, expect, it } from "vitest"; + +import { + CalculatorModel, + type CalculatorOperator, +} from "../../src/applications/built-in/calculator-model"; + +function enter(model: CalculatorModel, value: string): void { + for (const character of value) { + if (character === ".") { + model.inputDecimal(); + } else { + model.inputDigit(character); + } + } +} + +function calculate(left: string, operator: CalculatorOperator, right: string): CalculatorModel { + const model = new CalculatorModel(); + enter(model, left); + model.chooseOperator(operator); + enter(model, right); + model.equals(); + return model; +} + +describe("CalculatorModel", () => { + it("starts at zero and accepts multi-digit input", () => { + const model = new CalculatorModel(); + + expect(model.display).toBe("0"); + expect(model.hasError).toBe(false); + expect(model.pendingOperation).toBeNull(); + + enter(model, "1205"); + expect(model.display).toBe("1205"); + }); + + it("accepts one decimal point and normalizes leading decimals", () => { + const model = new CalculatorModel(); + + enter(model, ".125.5"); + + expect(model.display).toBe("0.1255"); + }); + + it.each([ + ["addition", "add", "12", "5", "17"], + ["subtraction", "subtract", "12", "5", "7"], + ["multiplication", "multiply", "12", "5", "60"], + ["division", "divide", "12", "5", "2.4"], + ] as const)("performs %s", (_name, operator, left, right, expected) => { + expect(calculate(left, operator, right).display).toBe(expected); + }); + + it("evaluates chained operations immediately from left to right", () => { + const model = new CalculatorModel(); + enter(model, "12"); + model.chooseOperator("add"); + enter(model, "5"); + model.chooseOperator("multiply"); + enter(model, "2"); + model.equals(); + + expect(model.display).toBe("34"); + }); + + it("produces negative results", () => { + expect(calculate("5", "subtract", "12").display).toBe("-7"); + }); + + it("clears all calculation state", () => { + const model = calculate("9", "add", "4"); + + model.clear(); + model.inputDigit("2"); + model.equals(); + + expect(model.display).toBe("2"); + expect(model.hasError).toBe(false); + }); + + it("backspaces only the current input", () => { + const model = new CalculatorModel(); + enter(model, "123"); + + model.backspace(); + expect(model.display).toBe("12"); + model.backspace(); + model.backspace(); + expect(model.display).toBe("0"); + }); + + it("replaces a pending operator deterministically", () => { + const model = new CalculatorModel(); + enter(model, "8"); + model.chooseOperator("add"); + model.chooseOperator("multiply"); + enter(model, "3"); + model.equals(); + + expect(model.display).toBe("24"); + }); + + it.each([ + ["add", "12"], + ["subtract", "12"], + ["multiply", "12"], + ["divide", "12"], + ] as const)("exposes the stored operand and pending %s operation", (operator, operand) => { + const model = new CalculatorModel(); + enter(model, operand); + + model.chooseOperator(operator); + + expect(model.pendingOperation).toEqual({ operand, operator }); + }); + + it("projects operator replacement without evaluating prematurely", () => { + const model = new CalculatorModel(); + enter(model, "12"); + model.chooseOperator("add"); + + model.chooseOperator("multiply"); + + expect(model.display).toBe("12"); + expect(model.pendingOperation).toEqual({ operand: "12", operator: "multiply" }); + }); + + it("clears the pending projection on clear, equals, and errors", () => { + const model = new CalculatorModel(); + enter(model, "12"); + model.chooseOperator("add"); + model.clear(); + expect(model.pendingOperation).toBeNull(); + + enter(model, "12"); + model.chooseOperator("add"); + enter(model, "5"); + model.equals(); + expect(model.pendingOperation).toBeNull(); + + model.clear(); + enter(model, "9"); + model.chooseOperator("divide"); + enter(model, "0"); + model.equals(); + expect(model.pendingOperation).toBeNull(); + }); + + it("repeats the last equals operation", () => { + const model = calculate("2", "add", "3"); + + model.equals(); + expect(model.display).toBe("8"); + model.equals(); + expect(model.display).toBe("11"); + }); + + it("enters an error state on division by zero and recovers with numeric input", () => { + const model = calculate("9", "divide", "0"); + + expect(model.display).toBe("ERROR"); + expect(model.hasError).toBe(true); + + model.inputDigit("4"); + expect(model.display).toBe("4"); + expect(model.hasError).toBe(false); + }); + + it("recovers from an error through clear", () => { + const model = calculate("1", "divide", "0"); + + model.clear(); + + expect(model.display).toBe("0"); + expect(model.hasError).toBe(false); + }); + + it("caps direct input and formats large results without overflowing the display", () => { + const model = new CalculatorModel(); + enter(model, "123456789012345"); + expect(model.display).toBe("123456789012"); + + model.chooseOperator("multiply"); + enter(model, "999999999999"); + model.equals(); + + expect(model.display.length).toBeLessThanOrEqual(16); + expect(model.display).toMatch(/e\+/); + }); + + it("clears temporary state when disposed", () => { + const model = calculate("7", "multiply", "6"); + + model.dispose(); + + expect(model.display).toBe("0"); + expect(model.hasError).toBe(false); + }); +}); diff --git a/tests/unit/clock-model.test.ts b/tests/unit/clock-model.test.ts new file mode 100644 index 0000000..33c8fb0 --- /dev/null +++ b/tests/unit/clock-model.test.ts @@ -0,0 +1,108 @@ +import { describe, expect, it, vi } from "vitest"; + +import { ClockModel } from "../../src/applications/built-in/clock-model"; +import { FakeClock } from "../helpers/fake-clock"; + +describe("ClockModel", () => { + it("formats the injected time deterministically", () => { + const timestamp = new Date(2042, 6, 9, 4, 5, 6).getTime(); + const model = new ClockModel(new FakeClock(timestamp)); + + expect(model.snapshot).toEqual({ + iso: new Date(timestamp).toISOString(), + time: "04:05:06", + date: "2042.07.09", + }); + }); + + it("aligns updates to second boundaries and keeps one scheduled tick", () => { + const timestamp = new Date(2042, 6, 9, 4, 5, 6, 250).getTime(); + const clock = new FakeClock(timestamp); + const model = new ClockModel(clock); + const listener = vi.fn(); + + const unsubscribe = model.subscribe(listener); + expect(clock.pendingTaskCount).toBe(1); + + clock.advanceBy(749); + expect(listener).not.toHaveBeenCalled(); + clock.advanceBy(1); + expect(listener).toHaveBeenLastCalledWith( + expect.objectContaining({ time: "04:05:07", date: "2042.07.09" }), + ); + expect(clock.pendingTaskCount).toBe(1); + + clock.advanceBy(2_000); + expect(listener).toHaveBeenCalledTimes(3); + expect(listener).toHaveBeenLastCalledWith( + expect.objectContaining({ time: "04:05:09", date: "2042.07.09" }), + ); + expect(clock.pendingTaskCount).toBe(1); + unsubscribe(); + expect(clock.pendingTaskCount).toBe(0); + }); + + it("updates the local date when the injected time crosses midnight", () => { + const timestamp = new Date(2042, 11, 31, 23, 59, 59).getTime(); + const clock = new FakeClock(timestamp); + const model = new ClockModel(clock); + const listener = vi.fn(); + const unsubscribe = model.subscribe(listener); + + clock.advanceBy(1_000); + + expect(model.snapshot).toMatchObject({ time: "00:00:00", date: "2043.01.01" }); + expect(listener).toHaveBeenLastCalledWith(model.snapshot); + unsubscribe(); + }); + + it("shares one scheduled tick across subscribers and cancels it after the last unsubscribe", () => { + const clock = new FakeClock(); + const model = new ClockModel(clock); + + const unsubscribeFirst = model.subscribe(() => undefined); + const unsubscribeSecond = model.subscribe(() => undefined); + expect(clock.pendingTaskCount).toBe(1); + + unsubscribeFirst(); + expect(clock.pendingTaskCount).toBe(1); + unsubscribeSecond(); + expect(clock.pendingTaskCount).toBe(0); + }); + + it("does not accumulate timers across dispose and reopen cycles", () => { + const clock = new FakeClock(); + const firstListener = vi.fn(); + const firstModel = new ClockModel(clock); + firstModel.subscribe(firstListener); + expect(clock.pendingTaskCount).toBe(1); + + firstModel.dispose(); + expect(clock.pendingTaskCount).toBe(0); + clock.advanceBy(2_000); + expect(firstListener).not.toHaveBeenCalled(); + + const secondListener = vi.fn(); + const secondModel = new ClockModel(clock); + secondModel.subscribe(secondListener); + expect(clock.pendingTaskCount).toBe(1); + clock.advanceBy(1_000); + expect(secondListener).toHaveBeenCalledTimes(1); + expect(clock.pendingTaskCount).toBe(1); + + secondModel.dispose(); + expect(clock.pendingTaskCount).toBe(0); + }); + + it("rejects subscriptions after disposal without scheduling work", () => { + const clock = new FakeClock(); + const model = new ClockModel(clock); + + model.dispose(); + + expect(() => model.subscribe(() => undefined)).toThrow( + "Cannot subscribe to a disposed Clock model.", + ); + expect(clock.pendingTaskCount).toBe(0); + }); +}); diff --git a/tests/unit/context-menu-model.test.ts b/tests/unit/context-menu-model.test.ts new file mode 100644 index 0000000..91f3278 --- /dev/null +++ b/tests/unit/context-menu-model.test.ts @@ -0,0 +1,42 @@ +import { describe, expect, it } from "vitest"; + +import { clampOverlayPosition } from "../../src/shell/desktop/context-menu-model"; + +describe("clampOverlayPosition", () => { + it("preserves an anchor that already fits inside the viewport", () => { + expect( + clampOverlayPosition( + { x: 120, y: 80 }, + { width: 200, height: 120 }, + { width: 800, height: 600 }, + ), + ).toEqual({ x: 120, y: 80 }); + }); + + it("keeps the overlay inside every viewport edge", () => { + expect( + clampOverlayPosition( + { x: 790, y: 590 }, + { width: 220, height: 160 }, + { width: 800, height: 600 }, + ), + ).toEqual({ x: 572, y: 432 }); + expect( + clampOverlayPosition( + { x: -40, y: -20 }, + { width: 220, height: 160 }, + { width: 800, height: 600 }, + ), + ).toEqual({ x: 8, y: 8 }); + }); + + it("uses the margin when the overlay is larger than the viewport", () => { + expect( + clampOverlayPosition( + { x: 100, y: 100 }, + { width: 500, height: 400 }, + { width: 320, height: 240 }, + ), + ).toEqual({ x: 8, y: 8 }); + }); +}); diff --git a/tests/unit/notepad-model.test.ts b/tests/unit/notepad-model.test.ts new file mode 100644 index 0000000..b0fc569 --- /dev/null +++ b/tests/unit/notepad-model.test.ts @@ -0,0 +1,26 @@ +import { describe, expect, it } from "vitest"; + +import { NotepadModel } from "../../src/applications/built-in/notepad-model"; + +describe("NotepadModel", () => { + it("starts blank and retains multiline edits for the running instance", () => { + const model = new NotepadModel(); + + expect(model.text).toBe(""); + + model.setText("First line\nSecond line"); + expect(model.text).toBe("First line\nSecond line"); + + model.setText("Revised text"); + expect(model.text).toBe("Revised text"); + }); + + it("clears its temporary text when disposed", () => { + const model = new NotepadModel(); + model.setText("Temporary session text"); + + model.dispose(); + + expect(model.text).toBe(""); + }); +});