diff --git a/docs/UI-SPEC.md b/docs/UI-SPEC.md index 1aa24af..0dc6c5f 100644 --- a/docs/UI-SPEC.md +++ b/docs/UI-SPEC.md @@ -21,7 +21,7 @@ Anti-goals: gradients-everywhere SaaS look, rounded-blob cards, decorative glow. | `--color-text` | `#E7F0EA` | primary text | | `--color-text-dim` | `#8AA394` | secondary text, **dimmed up-to-date rows** | | `--color-warn` | `#F5B94A` | held-back, warnings | -| `--color-danger` | `#F0574F` | impossible, failures, force actions | +| `--color-danger` | `#F26A63` | impossible, failures, force actions. `#F0574F` until 1.4.0, which read at 3.92:1 on its own badge tint over a selected row | | `--color-info` | `#5BC0DE` | pinned, informational chips | Type: **Inter** (UI), **JetBrains Mono** (package names, versions, console, status line — both OFL-licensed, bundled). Base 14 px, mono data 13 px. Radius 6 px; borders 1 px; shadows minimal. Motion: 120–160 ms ease-out; live-activity pulse on the status-line engine badge during execution; `prefers-reduced-motion` respected. @@ -236,9 +236,16 @@ guarded neither. Nothing looked wrong — the sidebar was disabled and the panel until the plan finished and dropped the user on a tab they never chose. The shortcuts now also refuse while the legal gate is on screen, which matters once About can re-open it. -**The window is bounded at 1600×1100 and cannot be maximized or go fullscreen.** The layout is a -fixed sidebar plus one scrolling column; stretched across a 4K panel it is a column of text beside -a metre of empty surface. Still resizable, and `minWidth`/`minHeight` are unchanged. +**The window maximizes and snaps; the content column does not stretch.** Until 1.4.0 the window +was bounded at 1600×1100 and could not be maximized, because the layout — a fixed sidebar plus one +scrolling column — stretched across a 4K panel is a column of text beside a metre of empty surface. +That answered the right worry with the wrong control: the column now stops at `max-w-content` +(87.5rem) and centres in what is left, and the window is the user's to size. Fullscreen stays off. + +**The window opens at a size that fits.** 1180×760 is taller than the work area of a 1920×1080 panel +at 150 % and of a 1366×768 laptop, so the status line and the plan panel's Confirm opened under the +taskbar. The window is created hidden and `src-tauri/src/window.rs` shrinks it to the monitor's work +area — never below `minWidth`/`minHeight`, 900×560 — centres it there, then shows it. ## 6. Component inventory (prefix `Pd`) diff --git a/src-tauri/capabilities/default.json b/src-tauri/capabilities/default.json index 4aca030..b5b9699 100644 --- a/src-tauri/capabilities/default.json +++ b/src-tauri/capabilities/default.json @@ -1,10 +1,12 @@ { "$schema": "../gen/schemas/desktop-schema.json", "identifier": "default", - "description": "Minimal capability set for the shell. Permissions are added per feature, never broadened preemptively (docs/SECURITY.md §2). dialog:allow-open is Code Health's project-folder picker and the manual Browse… path; dialog:allow-save is Save report. BOTH ONLY ASK FOR A PATH — no fs permission is granted, so the webview cannot read or write a single file. Save report hands its path to a Rust command that writes the two files, because a general fs:allow-write-text-file would be a write-anywhere primitive in the webview of a tool that already runs subprocesses against the user's interpreters.", + "description": "Exactly what the webview calls, and nothing preemptive (docs/SECURITY.md §2); lib.rs pins the set with a test. core:default stood here until 1.4.0: it granted some sixty core commands nothing used and not the one the legal gate's Decline needs, so Decline did nothing in the installed app. core:event:allow-listen/unlisten carry plan-, scan-, health- and audit-progress; core:window:allow-close is Decline. dialog:allow-open is Code Health's project-folder picker and Import requirements; dialog:allow-save is Save report and Export. BOTH ONLY ASK FOR A PATH — no fs permission is granted, so the webview cannot read or write a single file. Save report hands its path to a Rust command that writes the two files, because a general fs:allow-write-text-file would be a write-anywhere primitive in the webview of a tool that already runs subprocesses against the user's interpreters.", "windows": ["main"], "permissions": [ - "core:default", + "core:event:allow-listen", + "core:event:allow-unlisten", + "core:window:allow-close", "dialog:allow-open", "dialog:allow-save" ] diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 48354f6..8a669f4 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -8,12 +8,8 @@ pub mod commands; pub mod state; +pub mod window; -/// Run the application. -/// -/// # Panics -/// Panics if Tauri cannot build the app context. That means a malformed `tauri.conf.json`, which -/// is a build-time mistake rather than a runtime condition, so there is nothing to recover to. /// Commands that are **declared** in ARCHITECTURE §7 and `COMMANDS` but not yet implemented, each /// with the slice that owes it. /// @@ -78,6 +74,11 @@ fn startup_failed(e: &pipdock_core::PdError, log: &std::path::Path) { .show(); } +/// Run the application. +/// +/// # Panics +/// Panics if Tauri cannot build the app context. That means a malformed `tauri.conf.json`, which +/// is a build-time mistake rather than a runtime condition, so there is nothing to recover to. #[cfg_attr(mobile, tauri::mobile_entry_point)] #[allow( clippy::expect_used, @@ -120,6 +121,19 @@ pub fn run() { // Already open: the one startup step that can fail for a reason the user can act on // ran before Tauri, where its failure can reach the user. app.manage(state); + // Created hidden (`visible: false`) so the first frame is drawn at a size that fits + // the monitor, not at one that hangs below a laptop's taskbar (U21, UI-SPEC §5). + if let Some(window) = app.get_webview_window("main") { + let config = app.config().app.windows.iter().find(|w| w.label == "main"); + if let Some(config) = config + && let Err(e) = window::place(&window, config) + { + tracing::warn!(target: "pipdock::app", error = %e, "could not fit the window"); + } + if let Err(e) = window.show() { + tracing::error!(target: "pipdock::app", error = %e, "could not show the window"); + } + } Ok(()) }) .invoke_handler(tauri::generate_handler![ @@ -173,6 +187,87 @@ pub fn run() { #[cfg(test)] mod tests { + /// Every permission the webview holds, across every file in `capabilities/`. + fn granted() -> Vec<(String, serde_json::Value)> { + let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("capabilities"); + let mut out = Vec::new(); + for entry in std::fs::read_dir(&dir).expect("capabilities/ exists") { + let path = entry.expect("a readable entry").path(); + let doc: serde_json::Value = + serde_json::from_str(&std::fs::read_to_string(&path).expect("readable")) + .expect("a capability is JSON"); + assert_eq!( + doc["windows"], + serde_json::json!(["main"]), + "{} must apply to the main window only", + path.display() + ); + for p in doc["permissions"].as_array().expect("a permissions array") { + let id = p + .as_str() + .or_else(|| p["identifier"].as_str()) + .expect("a permission names itself"); + out.push((id.to_owned(), p.clone())); + } + } + out + } + + #[test] + fn the_webview_is_granted_exactly_what_it_calls() { + // `core:default` granted some sixty core commands nothing called, and not the one the + // legal gate's Decline does — `core:window:allow-close` — so Decline did nothing in the + // installed app while its component test, which mocks `getCurrentWindow().close()`, + // passed. A grant is a contract no frontend test can see, so the set is pinned here: + // widening it is a decision this test makes visible, and losing one a regression it + // catches before a user does. + let mut ids: Vec = granted().into_iter().map(|(id, _)| id).collect(); + ids.sort(); + assert_eq!( + ids, + [ + // Copy full log, Copy recent log, About's addresses — write, never read. + "clipboard-manager:allow-write-text", + // plan-, scan-, health- and audit-progress. + "core:event:allow-listen", + "core:event:allow-unlisten", + // Decline on the legal gate. + "core:window:allow-close", + // Code Health's folder, Import requirements; Save report, Export. + "dialog:allow-open", + "dialog:allow-save", + // Scoped; see the next test. + "opener:allow-open-url", + ] + ); + } + + #[test] + fn the_opener_reaches_four_hosts_and_no_more() { + // SECURITY §4: an unscoped opener is a launch-anything primitive. + let opener = granted() + .into_iter() + .find(|(id, _)| id == "opener:allow-open-url") + .map(|(_, p)| p) + .expect("the opener is granted"); + let mut urls: Vec<&str> = opener["allow"] + .as_array() + .expect("the opener is scoped") + .iter() + .map(|a| a["url"].as_str().expect("each scope is a URL")) + .collect(); + urls.sort_unstable(); + assert_eq!( + urls, + [ + "https://docs.astral.sh/*", + "https://github.com/*", + "https://osv.dev/*", + "https://poli0981.dev/*", + ] + ); + } + /// The handler list, read out of this file's own source. /// /// `generate_handler!` is a macro, so there is no runtime list to inspect and no way to ask diff --git a/src-tauri/src/window.rs b/src-tauri/src/window.rs new file mode 100644 index 0000000..56f37d6 --- /dev/null +++ b/src-tauri/src/window.rs @@ -0,0 +1,197 @@ +//! Where the main window opens — UI-SPEC §5. +//! +//! Until 1.4.0 the window was capped at 1600×1100 and refused to maximize. That answered the wrong +//! problem: the layout reads badly stretched across a 4K panel, and the answer to that is a content +//! column with a maximum width (`max-w-content` in `App.tsx`), not a window the user cannot fill or +//! snap. And the cap never touched the opposite case, which is the one that hid controls: +//! `tauri.conf.json` asks for 1180×760 logical pixels, taller than the work area of a 1920×1080 +//! panel at 150 % (about 688 under the taskbar) and of a 1366×768 laptop at 100 % — so the status +//! line and the plan panel's Confirm opened below the taskbar. +//! +//! So the window is created hidden (`visible: false`), fitted here to the work area of the monitor +//! it opened on, centred in it, and only then shown. + +/// Logical pixels kept clear between the window and each edge of the work area. +const MARGIN: f64 = 16.0; + +/// A rectangle in physical pixels. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Rect { + pub x: i32, + pub y: i32, + pub width: u32, + pub height: u32, +} + +/// Where the window goes: its outer position, and the inner size to ask for. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Placement { + pub x: i32, + pub y: i32, + pub inner_width: u32, + pub inner_height: u32, +} + +/// Logical to physical, rounded. The inputs are window sizes from a config file and a monitor's +/// scale factor, so the result is small and positive; anything else saturates. +#[allow( + clippy::cast_possible_truncation, + clippy::cast_sign_loss, + reason = "a window dimension times a scale factor; `as` saturates, which is the wanted clamp" +)] +fn physical(logical: f64, scale: f64) -> u32 { + (logical * scale).round() as u32 +} + +/// The configured inner size, shrunk to fit `work` but never below the configured minimum, with +/// the outer rectangle centred in `work`. +/// +/// `frame` is what the decorations add to the inner size — title bar and borders — in physical +/// pixels; `wanted` and `min` are logical, as `tauri.conf.json` states them. A work area smaller +/// than the minimum gets the minimum, pinned to the work area's top-left rather than centred off +/// its edge, because a title bar above the screen cannot be dragged back. +#[must_use] +pub fn fit( + work: Rect, + scale: f64, + frame: (u32, u32), + wanted: (f64, f64), + min: (f64, f64), +) -> Placement { + let margin = physical(MARGIN, scale); + let room_w = work.width.saturating_sub(frame.0 + 2 * margin); + let room_h = work.height.saturating_sub(frame.1 + 2 * margin); + let inner_width = physical(wanted.0, scale) + .min(room_w) + .max(physical(min.0, scale)); + let inner_height = physical(wanted.1, scale) + .min(room_h) + .max(physical(min.1, scale)); + let centre = |start: i32, room: u32, outer: u32| { + start.saturating_add(i32::try_from(room.saturating_sub(outer) / 2).unwrap_or(0)) + }; + Placement { + x: centre(work.x, work.width, inner_width + frame.0), + y: centre(work.y, work.height, inner_height + frame.1), + inner_width, + inner_height, + } +} + +/// Fit `window` to its monitor's work area, per `config`. +/// +/// # Errors +/// Whatever Tauri reports for a window it cannot query or move. The caller shows the window +/// regardless: at the configured size is better than not at all. +pub fn place( + window: &tauri::WebviewWindow, + config: &tauri::utils::config::WindowConfig, +) -> tauri::Result<()> { + let monitor = match window.current_monitor()? { + Some(monitor) => monitor, + None => match window.primary_monitor()? { + Some(monitor) => monitor, + None => return Ok(()), + }, + }; + let area = monitor.work_area(); + let outer = window.outer_size()?; + let inner = window.inner_size()?; + let placement = fit( + Rect { + x: area.position.x, + y: area.position.y, + width: area.size.width, + height: area.size.height, + }, + monitor.scale_factor(), + ( + outer.width.saturating_sub(inner.width), + outer.height.saturating_sub(inner.height), + ), + (config.width, config.height), + ( + config.min_width.unwrap_or(0.0), + config.min_height.unwrap_or(0.0), + ), + ); + window.set_size(tauri::PhysicalSize::new( + placement.inner_width, + placement.inner_height, + ))?; + window.set_position(tauri::PhysicalPosition::new(placement.x, placement.y))?; + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + const WANTED: (f64, f64) = (1180.0, 760.0); + const MIN: (f64, f64) = (900.0, 560.0); + /// A Windows 11 title bar and resize borders at 100 %. + const FRAME: (u32, u32) = (16, 39); + + fn work(width: u32, height: u32) -> Rect { + Rect { + x: 0, + y: 0, + width, + height, + } + } + + #[test] + fn a_large_monitor_gets_the_configured_size_centred() { + let p = fit(work(1920, 1032), 1.0, FRAME, WANTED, MIN); + assert_eq!((p.inner_width, p.inner_height), (1180, 760)); + assert_eq!((p.x, p.y), ((1920 - 1196) / 2, (1032 - 799) / 2)); + } + + #[test] + fn a_scaled_laptop_panel_gets_a_window_that_fits_under_its_taskbar() { + // 1920×1080 at 150 %: the work area is 1032 physical pixels tall, and 760 logical is 1140. + let frame = (24, 59); + let p = fit(work(1920, 1032), 1.5, frame, WANTED, MIN); + assert_eq!(p.inner_width, 1770, "the width fits, so it is untouched"); + assert!(p.inner_height + frame.1 <= 1032, "{p:?}"); + assert!(p.y >= 0, "{p:?}"); + } + + #[test] + fn a_small_laptop_keeps_the_whole_window_on_screen() { + let p = fit(work(1366, 728), 1.0, FRAME, WANTED, MIN); + assert!(p.inner_height + FRAME.1 <= 728, "{p:?}"); + assert!(p.inner_height >= 560, "never below the minimum"); + assert!(p.y >= 0); + } + + #[test] + fn a_work_area_below_the_minimum_gets_the_minimum_at_its_corner() { + let p = fit(work(800, 600), 1.0, FRAME, WANTED, MIN); + assert_eq!((p.inner_width, p.inner_height), (900, 560)); + assert_eq!( + (p.x, p.y), + (0, 0), + "never centred off the top of the screen" + ); + } + + #[test] + fn a_second_monitor_is_measured_from_its_own_origin() { + let p = fit( + Rect { + x: -1920, + y: 120, + width: 1920, + height: 1040, + }, + 1.0, + FRAME, + WANTED, + MIN, + ); + assert!(p.x >= -1920 && p.x + 1196 <= 0, "{p:?}"); + assert!(p.y >= 120, "{p:?}"); + } +} diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index ab1cb49..67a9e1d 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -17,16 +17,16 @@ "height": 760, "minWidth": 900, "minHeight": 560, - "maxWidth": 1600, - "maxHeight": 1100, "resizable": true, - "maximizable": false, + "center": true, + "visible": false, "fullscreen": false, "theme": "Dark" } ], "security": { - "csp": "default-src 'self'; img-src 'self' data:; style-src 'self' 'unsafe-inline'; font-src 'self'; connect-src 'self' ipc: http://ipc.localhost" + "csp": "default-src 'self'; img-src 'self' data:; style-src 'self'; font-src 'self'; connect-src 'self' ipc: http://ipc.localhost; object-src 'none'; base-uri 'none'; form-action 'none'", + "devCsp": "default-src 'self'; img-src 'self' data:; style-src 'self' 'unsafe-inline'; font-src 'self'; connect-src 'self' ipc: http://ipc.localhost; object-src 'none'; base-uri 'none'; form-action 'none'" } }, "bundle": { diff --git a/ui/index.html b/ui/index.html index 082edc1..3404476 100644 --- a/ui/index.html +++ b/ui/index.html @@ -3,9 +3,15 @@ + PipDock diff --git a/ui/src/App.test.tsx b/ui/src/App.test.tsx index c7b40c0..3e5e62b 100644 --- a/ui/src/App.test.tsx +++ b/ui/src/App.test.tsx @@ -14,11 +14,13 @@ * user can get there at all, and in how many clicks. */ -import { fireEvent, render, screen, within } from '@testing-library/react' +import { fireEvent, render, screen, waitFor, within } from '@testing-library/react' import { beforeEach, describe, expect, it, vi } from 'vitest' import { App } from '@/App' -import type { DepsGraph, Dist } from '@/ipc' +import { NAV_KEYS } from '@/components/nav' +import type { DepsGraph, Dist, EnvRow } from '@/ipc' +import { joinRows } from '@/screens/rows' import { useDepsStore, useEnvStore, useLegalStore, useUiStore } from '@/stores' import graphFixture from '@/test/fixtures/deps_graph.json' import listFixture from '@/test/fixtures/pkg_list.json' @@ -57,16 +59,19 @@ const DISTS = listFixture as Dist[] const ENV_HASH = 'abc123' const INTERPRETER = String.raw`C:\proj\.venv\Scripts\python.exe` -const ROW = { +// Typed, so a seed the app could never produce fails to compile. This one said `source: 'venv'`, +// which is not an `EnvSource`, and lacked `hiddenUserSite`; `as never` below hid both (U10). +const ROW: EnvRow = { interpreter: INTERPRETER, - source: 'venv' as const, + source: 'venv-scan', envHash: ENV_HASH, env: { interpreter: INTERPRETER, prefix: String.raw`C:\proj\.venv`, pythonVersion: '3.12.10', externallyManaged: false, - source: 'venv' as const, + hiddenUserSite: null, + source: 'venv-scan', }, } @@ -86,7 +91,7 @@ beforeEach(() => { // Past the gate, and it takes both halves. The store field is what the first render reads; the // command is what the mount effect overwrites it with. - legalConsentGet.mockReset().mockResolvedValue({ current: true, recorded: true }) + legalConsentGet.mockReset().mockResolvedValue({ current: true, docsHash: 'a1b2c3d4e5f60718' }) useLegalStore.setState({ accepted: true, review: false }) useUiStore.setState({ nav: 'installed' }) useDepsStore.setState({ @@ -96,21 +101,17 @@ beforeEach(() => { focus: null, error: null, }) + // The rows `joinRows` builds, not a hand-made shape: the old seed had `pinned`, `state` and a + // `null` latest, none of which a `PackageRow` has. useEnvStore.setState({ rows: [ROW], selected: INTERPRETER, - packages: DISTS.map((d) => ({ - name: d.name, - version: d.version, - latest: null, - sizeBytes: d.sizeBytes ?? null, - pinned: null, - state: 'unknown' as const, - })), + dists: DISTS, + packages: joinRows(DISTS, [], []).rows, listing: 'ready', outdatedStatus: 'ready', selection: new Set(), - } as never) + }) }) /** A package row by name, in the virtualized table. */ @@ -180,3 +181,24 @@ describe('the dependency view, reached the way a user reaches it', () => { } }) }) + +describe('the keyboard', () => { + it('selects a tab by the physical digit, whatever the layout types', () => { + // U49: on AZERTY, Ctrl+3 reports `"`. Parsing `e.key` made every tab shortcut a no-op there. + render() + expect(NAV_KEYS[2]).not.toBe(useUiStore.getState().nav) + fireEvent.keyDown(window, { key: '"', code: 'Digit3', ctrlKey: true }) + expect(useUiStore.getState().nav).toBe(NAV_KEYS[2]) + }) + + it('puts the cursor in the search field when `/` opens Search', async () => { + // U12: PdSearch focused its field, then the shell's own effect — parents run after children + // — moved focus to the heading, so the first keystroke after `/` went nowhere. + render() + fireEvent.keyDown(window, { key: '/', code: 'Slash' }) + expect(useUiStore.getState().nav).toBe('search') + await waitFor(() => { + expect(screen.getByRole('searchbox')).toHaveFocus() + }) + }) +}) diff --git a/ui/src/App.tsx b/ui/src/App.tsx index 444c72d..1c8862f 100644 --- a/ui/src/App.tsx +++ b/ui/src/App.tsx @@ -1,6 +1,7 @@ import { useEffect, useRef, useState } from 'react' import { useTranslation } from 'react-i18next' +import { isBrowserShortcut } from '@/components/browserKeys' import { NAV_KEYS } from '@/components/nav' import { PdLegalGate } from '@/components/PdLegalGate' import { PdOfflineBanner } from '@/components/PdOfflineBanner' @@ -83,21 +84,45 @@ export function App() { void checkConsent() }, [checkConsent]) - // Settings are the app's, not the Settings screen's: the status line names the engine and the - // PEP 668 chip reads the override. Loaded only when Settings mounted, so both showed the - // defaults — "pip", and no chip — until someone happened to open Settings (U13). + // Settings are the app's, not the Settings screen's: the status line names the engine, the + // PEP 668 chip reads the override, and the language is the user's. Loaded only when Settings + // mounted, so all three showed the defaults until someone opened Settings (U13) — and loaded + // before the legal gate rather than after it, so the gate is in the language they chose (U3). const loadSettings = useSettingsStore((s) => s.load) useEffect(() => { - if (accepted === true) void loadSettings() - }, [accepted, loadSettings]) + void loadSettings() + }, [loadSettings]) + + // U20: a release build has no reload, print or find to offer — see `browserKeys`. Capture phase + // and above the gate's early return, so no screen and no modal can let one through. + useEffect(() => { + if (!import.meta.env.PROD) return undefined + const swallow = (e: KeyboardEvent) => { + if (isBrowserShortcut(e)) e.preventDefault() + } + window.addEventListener('keydown', swallow, { capture: true }) + return () => { + window.removeEventListener('keydown', swallow, { capture: true }) + } + }, []) // UI-SPEC §8's "full keyboard traversal": after Ctrl+3 the focus was still on whatever the user // last clicked, so the next Tab resumed in the old screen and a screen reader announced nothing. // Moving it to the new screen's heading is the smallest thing that makes the shortcut complete. // `key={nav}` on
forces a remount, so this fires on every change rather than only the // first — and the heading takes `tabIndex={-1}` from the CSS-free `[tabindex]` below. + // + // A screen that names its own first stop with `data-autofocus` gets that instead. Search's field + // is UI-SPEC §5's first click, and PdSearch focused it — then this effect, which runs after its + // children's, moved focus to the heading on every arrival (U12). useEffect(() => { - const heading = mainRef.current?.querySelector('h1') + const main = mainRef.current + const own = main?.querySelector('[data-autofocus]') + if (own !== null && own !== undefined) { + own.focus() + return + } + const heading = main?.querySelector('h1') if (heading === null || heading === undefined) return heading.setAttribute('tabindex', '-1') heading.focus() @@ -141,13 +166,21 @@ export function App() { target?.tagName === 'INPUT' || target?.tagName === 'TEXTAREA' || target?.isContentEditable if (e.key === '/' && !e.ctrlKey && !e.altKey && !e.metaKey && typing !== true) { e.preventDefault() - setNav('search') + // Already on Search, `nav` does not change and the focus effect above does not run, so + // `/` did nothing at all from the very screen it names. + if (nav === 'search') { + mainRef.current?.querySelector('[data-autofocus]')?.focus() + } else { + setNav('search') + } return } if (!e.ctrlKey || e.altKey || e.metaKey) return - const index = Number.parseInt(e.key, 10) - 1 - const key = NAV_KEYS[index] + // By physical key (U49): `e.key` is what the layout types, and on AZERTY Ctrl+1 reports `&`, + // so the tab shortcuts did nothing for every French keyboard. + const digit = /^(?:Digit|Numpad)([1-9])$/.exec(e.code)?.[1] + const key = digit === undefined ? undefined : NAV_KEYS[Number(digit) - 1] if (key !== undefined) { e.preventDefault() setNav(key) @@ -157,7 +190,7 @@ export function App() { return () => { window.removeEventListener('keydown', onKey) } - }, [setNav, guardOpen, planPhase, accepted, review]) + }, [nav, setNav, guardOpen, planPhase, accepted, review]) // Nothing is usable before the documents are accepted, so the gate replaces the shell rather // than overlaying a working app (UI-SPEC §4). @@ -184,7 +217,12 @@ export function App() { {/* Each screen owns its own scroll container. A virtualizer needs a scroll element it can observe, and nesting one inside an already-scrolling
gives two scrollbars and an outer one whose content is already the virtualizer's full height. */} -
+ {/* `mx-auto max-w-content`: the window maximizes, the column does not (UI-SPEC §5). */} +
{PANEL_PHASES.has(planPhase) ? ( { diff --git a/ui/src/components/PdBadge.tsx b/ui/src/components/PdBadge.tsx index 65a875f..61a2c7f 100644 --- a/ui/src/components/PdBadge.tsx +++ b/ui/src/components/PdBadge.tsx @@ -9,15 +9,9 @@ * (`pipdock/no-jsx-literals`), which is the rule that keeps I18N §1 honest. */ -export type BadgeTone = 'warn' | 'info' | 'danger' | 'accent' | 'dim' +import { BADGE_TONES as TONES, type BadgeTone } from '@/components/badgeTones' -const TONES: Record = { - warn: 'bg-warn/20 text-warn', - info: 'bg-info/20 text-info', - danger: 'bg-danger/20 text-danger', - accent: 'bg-accent/20 text-accent', - dim: 'border border-border text-text-dim', -} +export type { BadgeTone } interface PdBadgeProps { tone: BadgeTone diff --git a/ui/src/components/PdConflictRow.tsx b/ui/src/components/PdConflictRow.tsx index 0239bff..bda093d 100644 --- a/ui/src/components/PdConflictRow.tsx +++ b/ui/src/components/PdConflictRow.tsx @@ -146,7 +146,8 @@ export function PdConflictRow({ setConfirmingForce(false) onChoose('force-latest') }} - className="rounded-pd bg-danger/20 px-2 py-0.5 text-data text-danger" + // Outlined, not filled: a fill inside the confirm's own danger tint read at 4.03:1. + className="rounded-pd border border-danger px-2 py-0.5 text-data text-danger" > {t('plan.decision.force-latest')} diff --git a/ui/src/components/PdErrorRow.test.tsx b/ui/src/components/PdErrorRow.test.tsx new file mode 100644 index 0000000..8ff9653 --- /dev/null +++ b/ui/src/components/PdErrorRow.test.tsx @@ -0,0 +1,70 @@ +/** + * What *Report bug* puts in the issue — U31. + * + * The row asked `report_bug_url` for its link with no environment, so every prefilled issue said + * nothing about the Python or the engine version — the first two questions anyone answering it + * would ask. Passing the environment costs a subprocess (`pip --version`), so it is asked for when + * the user reports, not once per row mounted: a summary of a failed batch can mount dozens. + */ + +import { fireEvent, render, screen, waitFor } from '@testing-library/react' +import { beforeEach, describe, expect, it, vi } from 'vitest' + +import { PdErrorRow } from '@/components/PdErrorRow' +import * as ipc from '@/ipc' +import type { EnvRow, PyEnv } from '@/ipc' +import { useEnvStore } from '@/stores' +import { resetStore } from '@/test/stores' + +vi.mock('@/ipc', async () => { + const { ipcMock } = await import('@/test/ipc') + return ipcMock() +}) +vi.mock('@tauri-apps/plugin-opener', () => ({ openUrl: vi.fn().mockResolvedValue(undefined) })) +const { openUrl } = await import('@tauri-apps/plugin-opener') + +const ENV: PyEnv = { + interpreter: 'C:/work/.venv/Scripts/python.exe', + prefix: 'C:/work/.venv', + pythonVersion: '3.12.4', + externallyManaged: false, + hiddenUserSite: null, + source: 'venv-scan', +} + +const ROW: EnvRow = { + interpreter: ENV.interpreter, + source: 'venv-scan', + envHash: 'hash-work', + env: ENV, +} + +describe('Report bug', () => { + beforeEach(() => { + vi.clearAllMocks() + resetStore(useEnvStore) + useEnvStore.setState({ rows: [ROW], selected: ENV.interpreter }) + vi.mocked(ipc.reportBugUrl).mockResolvedValue({ + url: 'https://github.com/poli0981/pipdock/issues/new', + log: '[log excerpt]', + }) + }) + + it('does not spawn anything to render the row', async () => { + render() + await screen.findByText('Report bug') + // One call, without the environment: deciding whether there is a log to offer is free. + expect(ipc.reportBugUrl).toHaveBeenCalledTimes(1) + expect(ipc.reportBugUrl).toHaveBeenCalledWith(undefined, 'PD-NET-001') + }) + + it('asks again with the environment when the user reports', async () => { + render() + fireEvent.click(await screen.findByText('Report bug')) + + await waitFor(() => { + expect(openUrl).toHaveBeenCalledTimes(1) + }) + expect(ipc.reportBugUrl).toHaveBeenLastCalledWith(ENV, 'PD-NET-001') + }) +}) diff --git a/ui/src/components/PdErrorRow.tsx b/ui/src/components/PdErrorRow.tsx index 7c2d9c1..3c29941 100644 --- a/ui/src/components/PdErrorRow.tsx +++ b/ui/src/components/PdErrorRow.tsx @@ -21,7 +21,7 @@ import { useTranslation } from 'react-i18next' import { useOpenExternal } from '@/components/useOpenExternal' import { reportBugUrl, type BugReportLink, type PdError } from '@/ipc' -import { useUiStore } from '@/stores' +import { useEnvStore, useUiStore } from '@/stores' export function PdErrorRow({ error, counted = true }: { error: PdError; counted?: boolean }) { const { t } = useTranslation() @@ -31,6 +31,8 @@ export function PdErrorRow({ error, counted = true }: { error: PdError; counted? const [copied, setCopied] = useState(false) const addErrorRow = useUiStore((s) => s.addErrorRow) const removeErrorRow = useUiStore((s) => s.removeErrorRow) + // The selected environment, for the Python and engine versions in the issue (U31). + const env = useEnvStore((s) => s.rows.find((r) => r.interpreter === s.selected)?.env) // Registers while mounted, so `⚠ n` means "problems currently on screen" rather than a tally // that only grows. `counted={false}` is for a sheet that renders one row per failed package — @@ -108,7 +110,18 @@ export function PdErrorRow({ error, counted = true }: { error: PdError; counted? - - + remove. One cell holding all three, at the width the header reserves for them. */} + + + + + ) } diff --git a/ui/src/components/PdPackageTable.tsx b/ui/src/components/PdPackageTable.tsx index 7b782e9..74c16e0 100644 --- a/ui/src/components/PdPackageTable.tsx +++ b/ui/src/components/PdPackageTable.tsx @@ -17,6 +17,7 @@ import { useRef } from 'react' import { useTranslation } from 'react-i18next' import { PdPackageRow, ROW_HEIGHT } from '@/components/PdPackageRow' +import { COLUMNS } from '@/components/packageColumns' import type { LoadState, PackageRow } from '@/screens/rows' interface PdPackageTableProps { @@ -77,7 +78,10 @@ export function PdPackageTable({ role="grid" aria-label={t('packages.tableLabel')} aria-rowcount={rows.length + 1} - className="flex min-h-0 flex-1 flex-col" + // Focusable but not a tab stop: the rows are (Sonar S6852, the ARIA grid pattern). + tabIndex={-1} + // `@container`: the columns size against the table's width, not the window's (U22). + className="@container flex min-h-0 flex-1 flex-col" onKeyDown={(e) => { // Ctrl+A selects all (UI-SPEC §8). Guarded against text inputs: none exist on these // screens yet, but Search lands in S4 and this is the cheap moment to get it right. @@ -89,32 +93,36 @@ export function PdPackageTable({ } }} > + {/* The same `COLUMNS` as every row, so the two cannot drift (U23). Outside the scroller, so + it stays put — and given the scroller's gutter, so a scrollbar appearing does not push + every cell left of its heading: `overflow-hidden` plus a stable gutter reserves the same + width a scrollbar would take. */}
{/* Aligns with the row checkbox, which has no header of its own. */} -
-
+
{virtualizer.getVirtualItems().map((item) => { const row = rows[item.index] diff --git a/ui/src/components/PdUninstallDialog.tsx b/ui/src/components/PdUninstallDialog.tsx index 75d55bc..d27b84b 100644 --- a/ui/src/components/PdUninstallDialog.tsx +++ b/ui/src/components/PdUninstallDialog.tsx @@ -88,7 +88,7 @@ export function PdUninstallDialog({ onConfirm(true) }} data-action="force" - className="rounded-pd border border-danger bg-danger/20 px-3 py-1 text-data text-danger disabled:opacity-40" + className="rounded-pd border border-danger bg-danger/15 px-3 py-1 text-data text-danger disabled:opacity-40" > {t('uninstall.force', { count: report.removing.length })} diff --git a/ui/src/components/badgeTones.ts b/ui/src/components/badgeTones.ts new file mode 100644 index 0000000..61cfc45 --- /dev/null +++ b/ui/src/components/badgeTones.ts @@ -0,0 +1,21 @@ +/** + * `PdBadge`'s tones, in a module of their own so `tokens.test.ts` can sweep them. + * + * A badge is text on a tint of its own colour, and the tint lowers the contrast the plain token + * has: danger on a 20 % danger tint over a selected row measured 3.92:1, under WCAG AA's 4.5, and + * no test looked at it because the token test checked tokens on plain surfaces only (U46). The + * test now composites each tint here over every surface. Danger takes a lighter tint for that + * reason, and the token itself moved from #F0574F to #F26A63. + * + * Tailwind finds these by scanning source text, so every class is written out whole. + */ + +export type BadgeTone = 'warn' | 'info' | 'danger' | 'accent' | 'dim' + +export const BADGE_TONES: Readonly> = { + warn: 'bg-warn/20 text-warn', + info: 'bg-info/20 text-info', + danger: 'bg-danger/15 text-danger', + accent: 'bg-accent/20 text-accent', + dim: 'border border-border text-text-dim', +} diff --git a/ui/src/components/browserKeys.test.ts b/ui/src/components/browserKeys.test.ts new file mode 100644 index 0000000..9f2e8d3 --- /dev/null +++ b/ui/src/components/browserKeys.test.ts @@ -0,0 +1,49 @@ +import { describe, expect, it } from 'vitest' + +import { isBrowserShortcut } from '@/components/browserKeys' + +const press = (key: string, code: string, mods: Partial> = {}) => + isBrowserShortcut({ + key, + code, + ctrlKey: mods.ctrl === true, + shiftKey: mods.shift === true, + altKey: mods.alt === true, + metaKey: false, + }) + +describe('the browser shortcuts a release build swallows', () => { + it.each([ + ['F5', 'F5', {}], + ['r', 'KeyR', { ctrl: true }], + ['R', 'KeyR', { ctrl: true, shift: true }], + ['p', 'KeyP', { ctrl: true }], + ['f', 'KeyF', { ctrl: true }], + ['F3', 'F3', {}], + ['ArrowLeft', 'ArrowLeft', { alt: true }], + ['BrowserBack', 'BrowserBack', {}], + ] as const)('%s (%s) is the browser’s', (key, code, mods) => { + expect(press(key, code, mods)).toBe(true) + }) + + it('finds Ctrl+R by its physical key, whatever the layout calls it', () => { + // A layout where KeyR types something else still reloads the page. + expect(press('к', 'KeyR', { ctrl: true })).toBe(true) + }) + + it.each([ + ['k', 'KeyK', { ctrl: true }], + ['a', 'KeyA', { ctrl: true }], + ['c', 'KeyC', { ctrl: true }], + ['v', 'KeyV', { ctrl: true }], + ['1', 'Digit1', { ctrl: true }], + ['/', 'Slash', {}], + ['r', 'KeyR', {}], + ['ArrowLeft', 'ArrowLeft', {}], + ['r', 'KeyR', { ctrl: true, alt: true }], + ] as const)('%s (%s) is left to the app', (key, code, mods) => { + // Ctrl+K, Ctrl+A, Ctrl+1..9 and `/` are PipDock's own (UI-SPEC §8); copy and paste are the + // user's; a bare R is typing; Ctrl+Alt is AltGr on many layouts. + expect(press(key, code, mods)).toBe(false) + }) +}) diff --git a/ui/src/components/browserKeys.ts b/ui/src/components/browserKeys.ts new file mode 100644 index 0000000..ac578e2 --- /dev/null +++ b/ui/src/components/browserKeys.ts @@ -0,0 +1,35 @@ +/** + * The browser's own shortcuts, which a release build has no use for — U20. + * + * WebView2 is a browser, and it kept a browser's keys: F5 and Ctrl+R reloaded the app — dropping a + * preview mid-decision along with everything the stores had not persisted — Ctrl+P printed the + * package table, Ctrl+F opened a find bar over a virtualized table whose off-screen rows do not + * exist in the DOM, and Alt+← navigated "back" from a single-page app. None of them is a PipDock + * feature, and each looked like one. + * + * Development keeps them: a reload is how a developer recovers from a bad hot update. + */ + +type Keys = Pick + +/** Physical keys whose Ctrl chord is the browser's: reload, print, find, find-next, source, save. */ +const CTRL_CODES: ReadonlySet = new Set(['KeyR', 'KeyP', 'KeyF', 'KeyG', 'KeyU', 'KeyS']) + +/** Keys that are the browser's on their own. */ +const BARE_KEYS: ReadonlySet = new Set([ + 'F3', + 'F5', + 'BrowserBack', + 'BrowserForward', + 'BrowserRefresh', +]) + +export function isBrowserShortcut(e: Keys): boolean { + if (BARE_KEYS.has(e.key)) return true + if (e.altKey && !e.ctrlKey && !e.metaKey && (e.key === 'ArrowLeft' || e.key === 'ArrowRight')) { + return true + } + if (!e.ctrlKey || e.altKey || e.metaKey) return false + // By physical key, like the app's own shortcuts: on AZERTY, Ctrl+R is still `KeyR`. + return CTRL_CODES.has(e.code) +} diff --git a/ui/src/components/packageColumns.ts b/ui/src/components/packageColumns.ts new file mode 100644 index 0000000..aba6eab --- /dev/null +++ b/ui/src/components/packageColumns.ts @@ -0,0 +1,23 @@ +/** + * The package table's column widths — one definition for the header and for every row (U23). + * + * The header used to be a hand-written mirror of the row, and it had drifted: one 2rem slot stood + * above three action buttons, so every fixed column's heading sat about 76px to the right of its + * cells. And the fixed widths summed to more than the table has at the 900px minimum window, with + * the name column — `min-w-0 flex-1` — absorbing the whole deficit, so at that width it rendered + * no names at all (U22). Narrow tables therefore drop Size first and tighten the rest, by + * container query against the table's own width rather than the window's: the plan panel and a + * future split view change the one without the other. + * + * Tailwind finds these by scanning source text, so every class is written out whole. + */ +export const COLUMNS = { + row: 'flex items-center gap-2 px-3 @4xl:gap-3', + checkbox: 'w-[13px] shrink-0', + name: 'min-w-0 flex-1 truncate', + version: 'w-24 shrink-0 @4xl:w-28', + latest: 'w-24 shrink-0 @4xl:w-28', + size: 'hidden w-24 shrink-0 text-right @3xl:block', + status: 'flex w-36 min-w-0 shrink-0 items-center gap-1 overflow-hidden @4xl:w-40', + actions: 'flex w-[6.5rem] shrink-0 items-center justify-end gap-1', +} as const diff --git a/ui/src/i18n.ts b/ui/src/i18n.ts index 51c1335..e991792 100644 --- a/ui/src/i18n.ts +++ b/ui/src/i18n.ts @@ -81,6 +81,12 @@ void i18n.use(initReactI18next).init({ }, }) +// The document's language follows the UI's, so a screen reader pronounces Vietnamese copy as +// Vietnamese: index.html ships `lang="en"`, and nothing changed it when the language did. +i18n.on('languageChanged', (lng) => { + if (typeof document !== 'undefined') document.documentElement.lang = resolveLocale(lng) +}) + if (import.meta.env.DEV) { i18n.addResourceBundle( PSEUDO_LOCALE, diff --git a/ui/src/ipc/errors.ts b/ui/src/ipc/errors.ts new file mode 100644 index 0000000..321682b --- /dev/null +++ b/ui/src/ipc/errors.ts @@ -0,0 +1,19 @@ +/** + * The one test for "is this a `PdError`", in a module with no Tauri import. + * + * Both stores route every rejection through it, so the `@/ipc` mock has to use the same predicate + * rather than a lookalike — it used one, which accepted `{ code: 1, message: null }`, and every + * error test agreed with itself (U10). Living here lets the mock import the real thing without + * importing `@tauri-apps/api`, which has no host to talk to under jsdom. + */ + +import type { PdError } from '@/ipc' + +export function isPdError(value: unknown): value is PdError { + return ( + typeof value === 'object' && + value !== null && + typeof (value as PdError).code === 'string' && + typeof (value as PdError).message === 'string' + ) +} diff --git a/ui/src/ipc/index.ts b/ui/src/ipc/index.ts index 8c4bbba..06f44b2 100644 --- a/ui/src/ipc/index.ts +++ b/ui/src/ipc/index.ts @@ -127,14 +127,8 @@ export interface PdError { * *usually* a `PdError` — but a panic or a serialization failure arrives as something else. * Narrowing here means no screen has to guess. */ -export function isPdError(value: unknown): value is PdError { - return ( - typeof value === 'object' && - value !== null && - typeof (value as PdError).code === 'string' && - typeof (value as PdError).message === 'string' - ) -} +// In a module of its own so the test mock can import the real predicate without Tauri. +export { isPdError } from '@/ipc/errors' /** What the shell reports about itself. */ export interface AppInfo { diff --git a/ui/src/screens/PdEnvironments.tsx b/ui/src/screens/PdEnvironments.tsx index 8a327b8..7d47021 100644 --- a/ui/src/screens/PdEnvironments.tsx +++ b/ui/src/screens/PdEnvironments.tsx @@ -55,7 +55,7 @@ function Row({ row }: { row: EnvRow }) { {row.interpreter} {managed ? ( - + {t('env.managed')} ) : null} diff --git a/ui/src/screens/PdPins.test.tsx b/ui/src/screens/PdPins.test.tsx index 871f6f4..637f6dc 100644 --- a/ui/src/screens/PdPins.test.tsx +++ b/ui/src/screens/PdPins.test.tsx @@ -41,8 +41,15 @@ function withEnv(pins: Pin[] = PINS) { interpreter: INTERPRETER, envHash: 'envhash01', source: 'manual', - env: { interpreter: INTERPRETER, pythonVersion: '3.12.4', externallyManaged: false }, - } as never, + env: { + interpreter: INTERPRETER, + prefix: 'C:/proj/.venv', + pythonVersion: '3.12.4', + externallyManaged: false, + hiddenUserSite: null, + source: 'manual', + }, + }, ], pins, }) diff --git a/ui/src/screens/PdSearch.tsx b/ui/src/screens/PdSearch.tsx index d3ba82a..3d795f9 100644 --- a/ui/src/screens/PdSearch.tsx +++ b/ui/src/screens/PdSearch.tsx @@ -54,7 +54,9 @@ export function PdSearch() { const envRow = rows.find((r) => r.interpreter === envSelected) // UI-SPEC §5: the Search flow's first click is spent arriving here, so the field must already - // have focus — "Search (autofocus) → result [Add] → Install → Confirm" is 4, not 5. + // have focus — "Search (autofocus) → result [Add] → Install → Confirm" is 4, not 5. In the app + // the shell does this, by `data-autofocus`, because its own focus effect runs after this one and + // used to move focus to the heading; this stays for the screen rendered on its own. useEffect(() => { field.current?.focus() }, []) @@ -85,6 +87,7 @@ export function PdSearch() { { diff --git a/ui/src/screens/PdSecurity.test.tsx b/ui/src/screens/PdSecurity.test.tsx index d4ced78..a23294d 100644 --- a/ui/src/screens/PdSecurity.test.tsx +++ b/ui/src/screens/PdSecurity.test.tsx @@ -53,6 +53,14 @@ beforeEach(() => { }) describe('PdSecurity', () => { + it('scrolls, rather than clipping a report taller than the window', () => { + // U2: the shell's
clips, so a screen that does not scroll itself cannot be scrolled at + // all — and Security's root was a bare
. + render() + const heading = screen.getByRole('heading', { name: 'Security' }) + expect(heading.closest('.overflow-auto')).not.toBeNull() + }) + it('says nothing has run when nothing has', () => { render() diff --git a/ui/src/screens/PdSecurity.tsx b/ui/src/screens/PdSecurity.tsx index c7b68b8..7acd070 100644 --- a/ui/src/screens/PdSecurity.tsx +++ b/ui/src/screens/PdSecurity.tsx @@ -61,114 +61,120 @@ export function PdSecurity() { const shown = row === undefined ? null : freshAudit({ report, reportFor }, row.envHash) return ( -
-

- {t('nav.security')} -

+ // One scroll container for the report, with the console drawer pinned under it, as Health + // does. The root was a bare
inside a
that clips, so a report taller than the + // window could not be scrolled to at all (U2). +
+
+

+ {t('nav.security')} +

-
- - - {/* Only while a run is going. An audit is 18-68 s — long enough that a user needs a way - out, which is the measurement that changed P4's answer for Code Health. */} - {running ? ( +
- ) : null} - {shown === null ? null : ( + {/* Only while a run is going. An audit is 18-68 s — long enough that a user needs a way + out, which is the measurement that changed P4's answer for Code Health. */} + {running ? ( + + ) : null} + + {shown === null ? null : ( + + )} + +
+ + {/* One live region for the whole screen. Two would serialize against each other + unpredictably — the pair P6 folded for exactly this reason. */} +

+ {running ? t('security.running') : saved === null ? '' : t('security.saved', { files: saved.join(', ') })} +

+ + {/* A run that failed outright — as opposed to a tool problem inside a report, below. */} + {error === null ? null : ( +
+ +
)} - -
- - {/* One live region for the whole screen. Two would serialize against each other - unpredictably — the pair P6 folded for exactly this reason. */} -

- {running ? t('security.running') : saved === null ? '' : t('security.saved', { files: saved.join(', ') })} -

- - {/* A run that failed outright — as opposed to a tool problem inside a report, below. */} - {error === null ? null : ( -
- -
- )} - - {/* pip-audit failed but the report still came back, so the advisories (if any) stay on - screen beneath this. `⚠ n` counts these rows, per UI-SPEC §3. */} - {(shown?.problems ?? []).map((problem) => ( -
- -
- ))} - - {/* **Nothing here while a run is going.** `shown` is null then — the report is cleared before - the command so a second run cannot paint the last one's findings under a new timestamp — - and rendering the un-run empty state on that basis said *No audit has run for this - environment* while one was running. That is P4's "no issues found before anything had - run", inverted: a true-looking sentence derived from a state the screen had not loaded. - The live region above, the disabled Run and the Cancel beside it already say what is - happening, so the body says nothing rather than something false. Found by clicking Run - against a deliberately slow bridge; no test asserted on it, because every test that - renders this screen renders it settled. */} - {shown !== null ? ( -
- {shown.cancelled ? ( - // A cancel is a state, not an error, so it is said plainly and the partial result is - // kept rather than thrown away. -

{t('security.cancelled')}

- ) : null} -

- {t('security.checkedAt', { at: shown.ranAt, version: shown.toolVersion })} -

-
- + {/* pip-audit failed but the report still came back, so the advisories (if any) stay on + screen beneath this. `⚠ n` counts these rows, per UI-SPEC §3. */} + {(shown?.problems ?? []).map((problem) => ( +
+
-
- ) : running ? null : ( - - )} + ))} + + {/* **Nothing here while a run is going.** `shown` is null then — the report is cleared before + the command so a second run cannot paint the last one's findings under a new timestamp — + and rendering the un-run empty state on that basis said *No audit has run for this + environment* while one was running. That is P4's "no issues found before anything had + run", inverted: a true-looking sentence derived from a state the screen had not loaded. + The live region above, the disabled Run and the Cancel beside it already say what is + happening, so the body says nothing rather than something false. Found by clicking Run + against a deliberately slow bridge; no test asserted on it, because every test that + renders this screen renders it settled. */} + {shown !== null ? ( +
+ {shown.cancelled ? ( + // A cancel is a state, not an error, so it is said plainly and the partial result is + // kept rather than thrown away. +

{t('security.cancelled')}

+ ) : null} +

+ {t('security.checkedAt', { at: shown.ranAt, version: shown.toolVersion })} +

+
+ +
+
+ ) : running ? null : ( + + )} + +
-
+
) } diff --git a/ui/src/screens/PdSettings.tsx b/ui/src/screens/PdSettings.tsx index 5d78075..ff2a42c 100644 --- a/ui/src/screens/PdSettings.tsx +++ b/ui/src/screens/PdSettings.tsx @@ -22,7 +22,7 @@ import { useSettingsStore } from '@/stores' const ENGINES = ['pip', 'uv'] as const export function PdSettings() { - const { t, i18n } = useTranslation() + const { t } = useTranslation() const { engine, allowExternallyManaged, @@ -87,9 +87,8 @@ export function PdSettings() { name="locale" checked={locale === code} onChange={() => { - setLocale(code) - // I18N §2: applied live, not on restart. - void i18n.changeLanguage(code) + // I18N §2: applied live — and stored, so it is still the language tomorrow. + void setLocale(code) }} className="accent-[var(--color-accent)]" /> diff --git a/ui/src/stores/index.ts b/ui/src/stores/index.ts index d73eed3..1b8d407 100644 --- a/ui/src/stores/index.ts +++ b/ui/src/stores/index.ts @@ -16,7 +16,12 @@ import { create } from 'zustand' import type { NavKey } from '@/components/nav' -import { FALLBACK_LOCALE, type Locale } from '@/i18n' +import i18n, { + FALLBACK_LOCALE, + resolveLocale, + SUPPORTED_LOCALES, + type Locale, +} from '@/i18n' import { envProbe, envScan, @@ -61,8 +66,14 @@ export function asPdError(e: unknown): PdError { } interface SettingsState { - /** Active UI language. */ + /** Active UI language — the choice when there is one, else what the OS resolved to. */ locale: Locale + /** + * The user's explicit choice, as stored. `null` is "follow the OS", which is what a fresh + * install has, and it is kept distinct from `locale` so that saving another setting cannot pin + * the language the OS happened to resolve to (U3). + */ + localeChoice: Locale | null /** Configured engine. First run pre-selects uv when it is on PATH (ARCHITECTURE §3). */ engine: EngineId /** @@ -77,11 +88,16 @@ interface SettingsState { error: PdError | null load: () => Promise save: (patch: Partial) => Promise - setLocale: (locale: Locale) => void + /** Choose a language: applied live (I18N §2) and stored, so it survives a restart. */ + setLocale: (locale: Locale) => Promise } +const isLocale = (value: string | null | undefined): value is Locale => + value != null && (SUPPORTED_LOCALES as readonly string[]).includes(value) + export const useSettingsStore = create((set, get) => ({ locale: FALLBACK_LOCALE, + localeChoice: null, engine: 'pip', allowExternallyManaged: false, // Mirrors `graph::PIN_SUGGEST_THRESHOLD`. Only on screen until `load` resolves, which is what @@ -93,27 +109,31 @@ export const useSettingsStore = create((set, get) => ({ load: async () => { try { const s = await settingsGet() + const choice = isLocale(s.locale) ? s.locale : null set({ engine: s.engine, allowExternallyManaged: s.allowExternallyManaged, pinSuggestThreshold: s.pinSuggestThreshold, + localeChoice: choice, + locale: choice ?? resolveLocale(i18n.language), loading: false, error: null, }) + if (choice !== null && i18n.language !== choice) await i18n.changeLanguage(choice) } catch (e) { set({ loading: false, error: asPdError(e) }) } }, save: async (patch) => { - const { engine, allowExternallyManaged, pinSuggestThreshold } = get() + const { engine, allowExternallyManaged, pinSuggestThreshold, localeChoice } = get() const next: Settings = { engine, allowExternallyManaged, pinSuggestThreshold, - // The store holds the *resolved* locale; `null` on the wire means "follow the OS", and only - // an explicit choice in Settings should overwrite that. - locale: null, + // The choice, never the resolved language: `null` on the wire means "follow the OS". This + // was a literal `null`, so every save erased a choice that nothing had stored anyway. + locale: localeChoice, ...patch, } try { @@ -122,6 +142,7 @@ export const useSettingsStore = create((set, get) => ({ engine: saved.engine, allowExternallyManaged: saved.allowExternallyManaged, pinSuggestThreshold: saved.pinSuggestThreshold, + localeChoice: isLocale(saved.locale) ? saved.locale : null, error: null, }) } catch (e) { @@ -129,7 +150,11 @@ export const useSettingsStore = create((set, get) => ({ } }, - setLocale: (locale) => set({ locale }), + setLocale: async (locale) => { + set({ locale, localeChoice: locale }) + await i18n.changeLanguage(locale) + await get().save({ locale }) + }, })) interface EnvState { diff --git a/ui/src/stores/settings.test.ts b/ui/src/stores/settings.test.ts new file mode 100644 index 0000000..1633a9b --- /dev/null +++ b/ui/src/stores/settings.test.ts @@ -0,0 +1,83 @@ +/** + * The language a user chose is still their language after a restart — U3. + * + * The locale radio applied a language live and stored nothing: `save` sent `locale: null` every + * time, so choosing Vietnamese lasted until the window closed, and saving any other setting + * afterwards would have erased a choice even if one had been written. `load` ignored the stored + * value as well, and the radio started on English whatever the OS was. + */ + +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +import i18n from '@/i18n' +import * as ipc from '@/ipc' +import type { Settings } from '@/ipc' +import { useSettingsStore } from '@/stores' +import { resetStore } from '@/test/stores' + +vi.mock('@/ipc', async () => { + const { ipcMock } = await import('@/test/ipc') + return ipcMock() +}) + +const STORED: Settings = { + engine: 'pip', + locale: null, + allowExternallyManaged: false, + pinSuggestThreshold: 5, +} + +describe('the locale', () => { + beforeEach(async () => { + vi.clearAllMocks() + resetStore(useSettingsStore) + vi.mocked(ipc.settingsSet).mockImplementation((s: Settings) => Promise.resolve(s)) + await i18n.changeLanguage('en') + }) + afterEach(async () => { + await i18n.changeLanguage('en') + }) + + it('applies the stored choice when settings load', async () => { + vi.mocked(ipc.settingsGet).mockResolvedValue({ ...STORED, locale: 'vi' }) + await useSettingsStore.getState().load() + expect(useSettingsStore.getState().locale).toBe('vi') + expect(i18n.language).toBe('vi') + }) + + it('follows the language already in use when nothing was chosen', async () => { + vi.mocked(ipc.settingsGet).mockResolvedValue(STORED) + await useSettingsStore.getState().load() + expect(useSettingsStore.getState().locale).toBe('en') + expect(useSettingsStore.getState().localeChoice).toBeNull() + }) + + it('stores a choice when one is made', async () => { + vi.mocked(ipc.settingsGet).mockResolvedValue(STORED) + await useSettingsStore.getState().load() + await useSettingsStore.getState().setLocale('vi') + + expect(i18n.language).toBe('vi') + expect(ipc.settingsSet).toHaveBeenLastCalledWith(expect.objectContaining({ locale: 'vi' })) + }) + + it('keeps the choice when another setting is saved', async () => { + // The second half of the bug: `save` wrote `locale: null` with every other change. + vi.mocked(ipc.settingsGet).mockResolvedValue({ ...STORED, locale: 'vi' }) + await useSettingsStore.getState().load() + await useSettingsStore.getState().save({ engine: 'uv' }) + + expect(ipc.settingsSet).toHaveBeenLastCalledWith( + expect.objectContaining({ engine: 'uv', locale: 'vi' }), + ) + }) + + it('does not invent a choice for someone who never made one', async () => { + // `null` means "follow the OS". Writing the resolved language back would pin it. + vi.mocked(ipc.settingsGet).mockResolvedValue(STORED) + await useSettingsStore.getState().load() + await useSettingsStore.getState().save({ engine: 'uv' }) + + expect(ipc.settingsSet).toHaveBeenLastCalledWith(expect.objectContaining({ locale: null })) + }) +}) diff --git a/ui/src/styles.css b/ui/src/styles.css index dd3b17c..9bd91c2 100644 --- a/ui/src/styles.css +++ b/ui/src/styles.css @@ -52,7 +52,7 @@ --color-text: #e7f0ea; --color-text-dim: #8aa394; --color-warn: #f5b94a; - --color-danger: #f0574f; + --color-danger: #f26a63; --color-info: #5bc0de; --font-sans: 'Inter', system-ui, sans-serif; @@ -63,6 +63,10 @@ --radius-pd: 6px; + /* The content column's widest. The window may be maximized (UI-SPEC §5); the column is what + stops a table from stretching across a 4K panel. */ + --container-content: 87.5rem; + /* UI-SPEC §2: motion is 120–160 ms ease-out. */ --ease-pd: cubic-bezier(0.16, 1, 0.3, 1); } diff --git a/ui/src/test/ipc.ts b/ui/src/test/ipc.ts index 4c276f7..d2575e3 100644 --- a/ui/src/test/ipc.ts +++ b/ui/src/test/ipc.ts @@ -24,6 +24,8 @@ import { vi } from 'vitest' +import { isPdError } from '@/ipc/errors' + /** The wrappers a test can drive. Add one when a test needs it, not before. */ export interface IpcMock { pkgList: ReturnType @@ -92,6 +94,9 @@ export function ipcMock(): IpcMock { database: { bytes: 0, path: 'C:/data/index.db', exists: false }, snapshots: { bytes: 0, path: 'C:/data/snapshots', exists: false }, tools: { bytes: 0, path: 'C:/data/tools', exists: false }, + // The fourth target since the Security tab. Missing here, so any test reading it got + // `undefined` from a shape the app never sends. + audit: { bytes: 0, path: 'C:/data/audit', exists: false }, snapshotCount: 0, }), cacheClear: vi.fn().mockResolvedValue(0), @@ -149,8 +154,8 @@ export function ipcMock(): IpcMock { }), settingsSet: vi.fn(), // Real, not a spy: the stores decide whether a rejection carries a catalog code by asking it, - // and a stub that always answered one way would make every error test agree with itself. - isPdError: (value: unknown): boolean => - typeof value === 'object' && value !== null && 'code' in value && 'message' in value, + // and a stub that always answered one way would make every error test agree with itself. And + // the real one, not a lookalike — the lookalike accepted `{ code: 1, message: null }`. + isPdError, } } diff --git a/ui/src/tokens.test.ts b/ui/src/tokens.test.ts index 15a38c7..61f784f 100644 --- a/ui/src/tokens.test.ts +++ b/ui/src/tokens.test.ts @@ -8,6 +8,29 @@ import { surfaceTokens, } from './tokens' +import { BADGE_TONES } from '@/components/badgeTones' + +/** Tailwind colour names, as `BADGE_TONES` spells them, to the tokens they compile to. */ +const TOKEN_OF: Record = { + warn: 'warn', + info: 'info', + danger: 'danger', + accent: 'accent', + 'text-dim': 'textDim', +} + +/** `fg` laid at `alpha` over `bg` — what `bg-danger/15` composites to on a surface. */ +function tint(fg: string, bg: string, alpha: number): string { + const channel = (i: number) => + Math.round( + Number.parseInt(fg.slice(1 + 2 * i, 3 + 2 * i), 16) * alpha + + Number.parseInt(bg.slice(1 + 2 * i, 3 + 2 * i), 16) * (1 - alpha), + ) + .toString(16) + .padStart(2, '0') + return `#${channel(0)}${channel(1)}${channel(2)}` +} + /** * UI-SPEC §8: "all text tokens meet WCAG AA on their surfaces (verified in the design-token * test)". This is that test — TESTING L3 lists it as a build-time gate, so a token tweak that @@ -37,6 +60,24 @@ describe('design tokens', () => { expect(contrastRatio(colors.accentDim, colors.bg)).toBeGreaterThanOrEqual(AA_NORMAL) }) + it.each(Object.entries(BADGE_TONES))('the %s badge reads at AA on every surface', (tone, classes) => { + // U46: the token test checked tokens on plain surfaces, and a badge is its text on a tint of + // its own colour — danger read 3.92:1 on a selected row with nothing to say so. + const text = TOKEN_OF[/text-([a-z-]+)/.exec(classes)?.[1] ?? ''] + expect(text, `${tone} names a text token`).toBeDefined() + const fill = /bg-([a-z-]+)\/(\d+)/.exec(classes) + for (const surface of surfaceTokens) { + const under = + fill === null + ? colors[surface] + : tint(colors[TOKEN_OF[fill[1] ?? ''] ?? 'bg'], colors[surface], Number(fill[2]) / 100) + expect( + contrastRatio(colors[text ?? 'text'], under), + `${tone} on ${surface}`, + ).toBeGreaterThanOrEqual(AA_NORMAL) + } + }) + it('every foreground token clears AA large on every surface', () => { for (const fg of foregroundTokens) { for (const surface of surfaceTokens) { diff --git a/ui/src/tokens.ts b/ui/src/tokens.ts index 7f203b2..2138d56 100644 --- a/ui/src/tokens.ts +++ b/ui/src/tokens.ts @@ -16,7 +16,7 @@ export const colors = { text: '#E7F0EA', textDim: '#8AA394', warn: '#F5B94A', - danger: '#F0574F', + danger: '#F26A63', info: '#5BC0DE', } as const