PM: merge M1.9b settings dialog

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
danny 2026-10-16 21:13:28 +02:00
commit 033b80f6cf
17 changed files with 1751 additions and 36 deletions

View file

@ -62,7 +62,7 @@ claude mcp add lutra -- lutra mcp
## Status ## Status
**Pre-alpha (2026-10-16): M1 in progress.** You can open a folder, browse it in the project tree with live updates from disk, and edit and save files in tabs (plain text for now), with every command in a palette (`Mod+Shift+P`); unsaved text survives a crash and is offered back on the next open; syntax highlighting and PHP features come next. The MVP (M1–M3) is estimated at about 20 agent hours after calibrating on the first cycle (2.5 h done). [**ROADMAP.md**](ROADMAP.md) has the stage and what's next, **Pre-alpha (2026-10-16): M1 done.** You can open a folder, browse it in the project tree with live updates from disk, and edit and save files in tabs (plain text for now), with every command in a palette (`Mod+Shift+P`) and settings and the light or dark theme in a settings dialog (`Mod+,`); unsaved text survives a crash and is offered back on the next open; syntax highlighting and PHP features come next. With M1 done, about 13 agent hours remain to the MVP (M2 and M3, estimated after calibrating on the first cycle). [**ROADMAP.md**](ROADMAP.md) has the stage and what's next,
[`docs/target-app-parity.md`](docs/target-app-parity.md) the parity assessment and [`docs/gaps.md`](docs/gaps.md) the ranked work list. [`docs/target-app-parity.md`](docs/target-app-parity.md) the parity assessment and [`docs/gaps.md`](docs/gaps.md) the ranked work list.
**First target (MVP, M1–M3):** open a project, project tree, tabs, editor with highlighting, find in files, **First target (MVP, M1–M3):** open a project, project tree, tabs, editor with highlighting, find in files,

View file

@ -1,20 +1,20 @@
# Lutra Roadmap # Lutra Roadmap
**Stage: pre-alpha (M1 in progress)** · next: the rest of M1 (settings dialog), then M2 syntax and search; alpha when the six core workflows work end to end (see [docs/roadmap.md › Alpha gate](docs/roadmap.md#alpha-gate)) **Stage: pre-alpha (M1 done)** · next: M2 syntax and search; alpha when the six core workflows work end to end (see [docs/roadmap.md › Alpha gate](docs/roadmap.md#alpha-gate))
> **Last reviewed:** 2026-10-15 · **Last updated:** 2026-10-16 · **Change:** minor (M1.8: command palette and keymap) · **Target:** JetBrains PhpStorm 2026.x, described from public documentation only > **Last reviewed:** 2026-10-15 · **Last updated:** 2026-10-16 · **Change:** minor (M1.9b: settings dialog; M1 done) · **Target:** JetBrains PhpStorm 2026.x, described from public documentation only
Lutra is a clean-room, open-source PHP IDE with a Rust core and a Tauri + Vue interface, targeting the PhpStorm workflow. Agents can drive all of it over MCP, the `lutra` CLI and a JSON control channel. This page is the summary; the evidence is in [`docs/target-app-parity.md`](docs/target-app-parity.md) and the work list in [`docs/gaps.md`](docs/gaps.md). Lutra is a clean-room, open-source PHP IDE with a Rust core and a Tauri + Vue interface, targeting the PhpStorm workflow. Agents can drive all of it over MCP, the `lutra` CLI and a JSON control channel. This page is the summary; the evidence is in [`docs/target-app-parity.md`](docs/target-app-parity.md) and the work list in [`docs/gaps.md`](docs/gaps.md).
**Why pre-alpha:** M0 built the foundation (workspace, quality gate, command registry with panic guard, control channel, a themed window). M1 so far lets you open a folder, browse it in the project tree and edit and save files in tabs, but as plain text: no PHP feature (highlighting, completion, navigation) exists yet. M1–M3 deliver the MVP. **Why pre-alpha:** M0 built the foundation (workspace, quality gate, command registry with panic guard, control channel, a themed window). M1 lets you open a folder, browse it in the project tree, edit and save files in tabs, get unsaved text back after a crash, run every command from a palette and change settings and the theme in a settings dialog, but as plain text: no PHP feature (highlighting, completion, navigation) exists yet. M1–M3 deliver the MVP.
## Headline numbers ## Headline numbers
| | Value | Kind | | | Value | Kind |
|---|---|---| |---|---|---|
| **Feature breadth** (PhpStorm's actions, tool windows, languages, integrations exist) | **<1%** (project tool window, editor tabs; no inventory to count against yet) | estimated | | **Feature breadth** (PhpStorm's actions, tool windows, languages, integrations exist) | **<1%** (project tool window, editor tabs; no inventory to count against yet) | estimated |
| **Feature depth** (weighted by use, scored by behaviour) | **~1.6%** (Editor core 9% × weight 12, Project view 8% × weight 6, Settings 4% × weight 1, of 101) | estimated | | **Feature depth** (weighted by use, scored by behaviour) | **~1.6%** (Editor core 9% × weight 12, Project view 8% × weight 6, Settings 7% × weight 1, of 101) | estimated |
| **To MVP (M3)** | **~20 h** (M1 ~6 h of which 2.5 h done, M2 ~5 h, M3 ~8 h); was ~190 h before calibration | estimated (×0.1 from cycle C1) | | **To MVP (M3)** | **~13 h left** (M1 done: C1 2.5 h measured, C2 time in the cycle review; M2 ~5 h, M3 ~8 h); was ~190 h before calibration | estimated (×0.1 from cycle C1) |
| **To full parity** | **~330 h** if cycle C1's speed holds (range 300–3,300 h; deep areas such as type inference and inspections have no data yet) | estimated | | **To full parity** | **~330 h** if cycle C1's speed holds (range 300–3,300 h; deep areas such as type inference and inspections have no data yet) | estimated |
Hours are agent wall-clock hours for one agent. M0 took about 2 h of active agent time (measured from the session, excluding toolchain installation and waiting for owner decisions). Later milestones are estimated far more conservatively per line of code, because editor, language and UI work need integration, debugging and visual checks that the foundation did not. Estimates are recalibrated after each cycle from task start times and commit timestamps. Cycle C1 (M1.1–M1.6) took 2.5 h of agent time for 37 h estimated (factor 0.07); M1–M3 hours are scaled by ×0.1 since then, and the per-area hours below are the raw first estimates (multiply by ~0.1 for the calibrated value). PhpStorm is **not** inspected: the clean-room rule in [`AGENTS.md`](AGENTS.md) forbids it, so everything is measured from our code against public documentation. Hours are agent wall-clock hours for one agent. M0 took about 2 h of active agent time (measured from the session, excluding toolchain installation and waiting for owner decisions). Later milestones are estimated far more conservatively per line of code, because editor, language and UI work need integration, debugging and visual checks that the foundation did not. Estimates are recalibrated after each cycle from task start times and commit timestamps. Cycle C1 (M1.1–M1.6) took 2.5 h of agent time for 37 h estimated (factor 0.07); M1–M3 hours are scaled by ×0.1 since then, and the per-area hours below are the raw first estimates (multiply by ~0.1 for the calibrated value). PhpStorm is **not** inspected: the clean-room rule in [`AGENTS.md`](AGENTS.md) forbids it, so everything is measured from our code against public documentation.
@ -60,7 +60,7 @@ Stability 8%: no-panic lints, the engine guard, a fuzzed control protocol and a
| HTTP client | 0% | ~60 | | HTTP client | 0% | ~60 |
| Web languages (JS/TS, Vue, CSS, Twig, Blade) | 0% | ~200 | | Web languages (JS/TS, Vue, CSS, Twig, Blade) | 0% | ~200 |
| Docker and remote | 0% | ~120 | | Docker and remote | 0% | ~120 |
| Settings, keymaps, themes | 4% (est.) | ~60 | | Settings, keymaps, themes | 7% (est.) | ~60 |
| Plug-ins and ecosystem | 0% | ~120 | | Plug-ins and ecosystem | 0% | ~120 |
| AI features | 0% | ~60 | | AI features | 0% | ~60 |
@ -68,15 +68,15 @@ All hours estimated. Weights, evidence and the missing items per area: [target-a
## Upcoming ## Upcoming
1. **M1 editor and project (~6 h, 2.5 h done):** open folder, project tree, tabs, editor, save and recovery, command palette, settings, themes. 1. **M2 syntax and search (~5 h):** highlighting, file structure, find in files, go to file/class/symbol.
2. **M2 syntax and search (~5 h):** highlighting, file structure, find in files, go to file/class/symbol. 2. **M3 language server, terminal and CLI (~8 h):** completion, diagnostics, go to definition via Phpactor; terminal; `lutra` CLI and MCP. **MVP.**
3. **M3 language server, terminal and CLI (~8 h):** completion, diagnostics, go to definition via Phpactor; terminal; `lutra` CLI and MCP. **MVP.** 3. **Then:** Git (M4), debugger, tests and Composer (M5), own indexer and frameworks (M6).
4. **Then:** Git (M4), debugger, tests and Composer (M5), own indexer and frameworks (M6).
## Progress log ## Progress log
| Date | What landed | | Date | What landed |
|---|---| |---|---|
| 2026-10-16 | M1.9b, M1 done: a settings dialog (`Mod+,`) built from the engine's settings, with search, a control per type, reset to default and inline errors; changes apply at once and follow edits from agents live; the theme picker switches at once and the editor font size applies to the editor. |
| 2026-10-16 | M1.8: a command palette (`Mod+Shift+P`) finds every command by fuzzy match, recent ones first, with shortcuts shown and unavailable ones dimmed; one global keymap serves engine and UI commands (`Mod+1` toggles the project tree); agents can trigger UI commands over the control channel. | | 2026-10-16 | M1.8: a command palette (`Mod+Shift+P`) finds every command by fuzzy match, recent ones first, with shortcuts shown and unavailable ones dimmed; one global keymap serves engine and UI commands (`Mod+1` toggles the project tree); agents can trigger UI commands over the control channel. |
| 2026-10-16 | M1.12: errors and notices reach the user as toasts instead of stderr: a corrupt settings file or recovery entry, a folder that cannot be opened (also with unsaved changes when switching projects), stopped file watching and failed commands without their own UI. Info toasts go away after 5 s, warnings and errors stay. | | 2026-10-16 | M1.12: errors and notices reach the user as toasts instead of stderr: a corrupt settings file or recovery entry, a folder that cannot be opened (also with unsaved changes when switching projects), stopped file watching and failed commands without their own UI. Info toasts go away after 5 s, warnings and errors stay. |
| 2026-10-16 | M1.7: unsaved text survives a crash. Dirty buffers are journaled about a second after the last edit; the next open offers them in a restore dialog (restore all, selected, or discard), with line endings and BOM kept. | | 2026-10-16 | M1.7: unsaved text survives a crash. Dirty buffers are journaled about a second after the last edit; the next open offers them in a restore dialog (restore all, selected, or discard), with line endings and BOM kept. |
@ -91,6 +91,7 @@ All hours estimated. Weights, evidence and the missing items per area: [target-a
| Date | Change | Summary | | Date | Change | Summary |
|---|---|---| |---|---|---|
| 2026-10-16 | minor | M1.9b: M1 done, stage line, Settings row 7% (est.), progress log |
| 2026-10-16 | minor | M1.8: progress log, agent automation note (scores unchanged) | | 2026-10-16 | minor | M1.8: progress log, agent automation note (scores unchanged) |
| 2026-10-16 | minor | M1.12: progress log (headline unchanged) | | 2026-10-16 | minor | M1.12: progress log (headline unchanged) |
| 2026-10-16 | minor | M1.7: Stability 8%, Editor core 9%, feature depth ~1.6% (with Settings 4% from M1.10) | | 2026-10-16 | minor | M1.7: Stability 8%, Editor core 9%, feature depth ~1.6% (with Settings 4% from M1.10) |

View file

@ -1,6 +1,6 @@
# Architecture # Architecture
> **Status:** M0 decisions recorded, M1 workspace, desktop bridge, tabs and editor, message catalog, engine construction, settings, themes, the recovery journal, notifications, UI commands, the palette and the app icon documented · **Last updated:** 2026-10-16 > **Status:** M0 decisions recorded, M1 workspace, desktop bridge, tabs and editor, message catalog, engine construction, settings, themes, the recovery journal, notifications, UI commands, the palette, the settings dialog and the app icon documented · **Last updated:** 2026-10-16
## Overview ## Overview
@ -140,7 +140,7 @@ Watched directories: the VFS watcher is non-recursive, so `project.children` wat
- First frame: the desktop reads `appearance.theme` before creating the window and passes `theme::init_script(setting)`, which installs `<style id="lt-theme">`. For `system` the CSS is the dark theme plus the light one inside `@media (prefers-color-scheme: light)`, so the first frame follows the OS without a round trip; the native window background is set from the resolved theme (`Window::theme()` for system). - First frame: the desktop reads `appearance.theme` before creating the window and passes `theme::init_script(setting)`, which installs `<style id="lt-theme">`. For `system` the CSS is the dark theme plus the light one inside `@media (prefers-color-scheme: light)`, so the first frame follows the OS without a round trip; the native window background is set from the resolved theme (`Window::theme()` for system).
- Live switch: `ui/src/theme.ts` (`startTheme`, called by `App.vue`) reports `matchMedia("(prefers-color-scheme: dark)")` now and on every change, applies the result and every `themeChanged`: tokens go onto `:root`'s inline style (which wins over the injected style element), `color-scheme` is set, and `data-theme` holds the id. No reload. - Live switch: `ui/src/theme.ts` (`startTheme`, called by `App.vue`) reports `matchMedia("(prefers-color-scheme: dark)")` now and on every change, applies the result and every `themeChanged`: tokens go onto `:root`'s inline style (which wins over the injected style element), `color-scheme` is set, and `data-theme` holds the id. No reload.
- Accessibility: `ui/tests/theme/contrast.test.ts` checks every text/background pair the components draw with against WCAG AA (4.5:1 text, 3:1 cursor and modified dot) in both themes. It reads `ui/tests/theme/themes.json`, which the Rust test `theme::tests::ui_snapshot_is_current` keeps equal to the Rust definition (`LUTRA_UPDATE_SNAPSHOTS=1` rewrites it). `ui/tests/theme/theme.test.ts` fails on a `var(--lt-x)` the themes lack and on a fallback for a token they define. - Accessibility: `ui/tests/theme/contrast.test.ts` checks every text/background pair the components draw with against WCAG AA (4.5:1 text, 3:1 cursor and modified dot) in both themes. It reads `ui/tests/theme/themes.json`, which the Rust test `theme::tests::ui_snapshot_is_current` keeps equal to the Rust definition (`LUTRA_UPDATE_SNAPSHOTS=1` rewrites it). `ui/tests/theme/theme.test.ts` fails on a `var(--lt-x)` the themes lack and on a fallback for a token they define.
- Not themed yet: the native title bar follows the OS, not the Lutra theme; spacing and size tokens (`--lt-space-*`, `--lt-radius`, `--lt-row-height`…) are still CSS fallbacks in components; `editor.fontSize` does not drive `--lt-font-size-editor` yet. - Not themed yet: the native title bar follows the OS, not the Lutra theme; spacing and size tokens (`--lt-space-*`, `--lt-radius`, `--lt-row-height`…) are still CSS fallbacks in components. `editor.fontSize` drives `--lt-font-size-editor` since M1.9b (see Settings dialog).
### Recovery journal (M1.7) ### Recovery journal (M1.7)
@ -170,7 +170,7 @@ Watched directories: the VFS watcher is non-recursive, so `project.children` wat
- the palette provides `palette.open`; - the palette provides `palette.open`;
- the main layout provides `view.toggleProjectTree`; - the main layout provides `view.toggleProjectTree`;
- the editor area provides `file.save`, `file.saveAll` and `buffer.close` with the active buffer as context (they replace the editor-only keymap of M1.6). - the editor area provides `file.save`, `file.saveAll` and `buffer.close` with the active buffer as context (they replace the editor-only keymap of M1.6).
- A UI command without a handler is disabled. `settings.open` stays disabled until the settings dialog (M1.9b) provides it. - A UI command without a handler is disabled. The settings dialog provides `settings.open` (M1.9b).
- An engine command without a handler runs through `run(id, {})`. - An engine command without a handler runs through `run(id, {})`.
- **Enabled state:** a handler's `enabled` decides, else the engine's. The list is refreshed on `projectOpened`/`projectClosed` and whenever the palette opens. - **Enabled state:** a handler's `enabled` decides, else the engine's. The list is refreshed on `projectOpened`/`projectClosed` and whenever the palette opens.
- **Keyboard:** one window `keydown` listener in the capture phase (works while CodeMirror or an input has focus). A matching shortcut is always swallowed; a disabled command does nothing. A failure raises `notification.command.failed`. - **Keyboard:** one window `keydown` listener in the capture phase (works while CodeMirror or an input has focus). A matching shortcut is always swallowed; a disabled command does nothing. A failure raises `notification.command.failed`.
@ -182,6 +182,18 @@ Watched directories: the VFS watcher is non-recursive, so `project.children` wat
- **Rows:** disabled rows are dimmed with `aria-disabled`. - **Rows:** disabled rows are dimmed with `aria-disabled`.
- **Accessibility:** combobox with listbox and `aria-activedescendant`. - **Accessibility:** combobox with listbox and `aria-activedescendant`.
### Settings dialog (M1.9b)
- **Store:** `ui/src/stores/settings.ts` (Pinia `settings`, started by `App.vue`) loads `settings.list` and `settings.get`, reads both defensively (unknown types and malformed entries dropped, values must be scalars), changes values through `settings.set`/`settings.reset` and keeps a refused change's message per key. `settingsChanged` reloads the named keys with `settings.get {keys}` and drops their errors, so changes from the control channel or an agent show at once.
- **Text:** labels, descriptions and section names come from the catalog keys the engine sends (`settings.<key>.label`, `.description`, `settings.section.<id>`); enum values use `settings.<key>.value.<value in camelCase>`. A key the catalog lacks shows the setting key (or the raw value). These keys are in the catalog test's runtime list.
- **Font size:** `theme.ts` has `setTokenOverride(name, value)`: a value above the theme's that `applyTheme` keeps across theme switches. The store sets `--lt-font-size-editor` to `editor.fontSize` px; the editor reads only that token.
- **Dialog:** `ui/src/components/settings/SettingsDialog.vue` (mounted in `App.vue`) provides `settings.open` (`Mod+,`, palette, `uiCommand`). Sections on the left, the chosen section's settings on the right; enum → select, int → number field (min/max, applied when committed; text that is no whole number in range is refused in place with `settings.error.intRange`), bool → switch. The theme picker is the `appearance.theme` select; the engine answers with `themeChanged`.
- **Search** matches label, description, key and section name (every word, ignoring case); while it has text every match shows, grouped by section, and sections without matches are dimmed.
- **Reset to default** per setting, enabled while the value differs from the default.
- **Errors** show under the control (`role="alert"`, `aria-invalid`) and keep the typed text until the value changes.
- **Keyboard:** Escape or a click outside closes; Tab and Shift+Tab wrap inside the dialog, focus that leaves it is pulled back to the search field, and focus returns to where it was on close.
- No OK/Apply/Cancel: every change applies at once, as agents change settings through the same commands.
## Decisions (M0) ## Decisions (M0)
| Question | Decision | Why | | Question | Decision | Why |
@ -199,6 +211,7 @@ Watched directories: the VFS watcher is non-recursive, so `project.children` wat
| Date | Change | Summary | | Date | Change | Summary |
|---|---|---| |---|---|---|
| 2026-10-16 | minor | M1.9b: settings dialog (store, search, controls by type, reset, live updates, font-size token override) |
| 2026-10-16 | minor | M1.14: app icon from the owner's master, multi-size ICO, placeholder as fallback | | 2026-10-16 | minor | M1.14: app icon from the owner's master, multi-size ICO, placeholder as fallback |
| 2026-10-16 | minor | M1.8: UI commands (`ui.registerCommands`, `uiCommand`, `ui` in listCommands), global keymap, command palette | | 2026-10-16 | minor | M1.8: UI commands (`ui.registerCommands`, `uiCommand`, `ui` in listCommands), global keymap, command palette |
| 2026-10-16 | minor | M1.12: notifications (host emission, early-event replay, toast store and stack, deferred engine_ready) | | 2026-10-16 | minor | M1.12: notifications (host emission, early-event replay, toast store and stack, deferred engine_ready) |

View file

@ -1,6 +1,6 @@
# Gaps # Gaps
> **Status:** M0 closed G1; G2 under way (text buffer, engine buffers, tabs and editor in the app, recovery journal); G3 project tree works in the app, settings backend and theme switching landed; G14 English UI catalog in place · **Last updated:** 2026-10-16 > **Status:** M0 closed G1; G2 under way (text buffer, engine buffers, tabs and editor in the app, recovery journal); G3 M1 part done (project tree, palette, settings dialog, themes); G14 English UI catalog in place · **Last updated:** 2026-10-16
Every known shortfall, ranked. This is the work list: unless the owner gives a task, take the highest open gap. Hours are agent wall-clock hours for one agent, all estimated. Every known shortfall, ranked. This is the work list: unless the owner gives a task, take the highest open gap. Hours are agent wall-clock hours for one agent, all estimated.
@ -9,7 +9,7 @@ Every known shortfall, ranked. This is the work list: unless the owner gives a t
| 2026-10-16 | minor | G3: command palette, global keymap, UI commands (M1.8) | | 2026-10-16 | minor | G3: command palette, global keymap, UI commands (M1.8) |
| G1 | ~~Foundation: workspace, quality gate, command registry, guard, control channel~~ closed 2026-10-14 | M0 | done (~2 h measured) | | G1 | ~~Foundation: workspace, quality gate, command registry, guard, control channel~~ closed 2026-10-14 | M0 | done (~2 h measured) |
| G2 | Editor core: ~~engine buffers, save~~ (M1.3), ~~editor UI with tabs, undo, multi-caret~~ (M1.6, CodeMirror basics), ~~recovery journal~~ (M1.7), tab management (preview, pin, split, close others, reopen), conflict UI for files changed on disk, autosave option | M1 | ~16 h | | G2 | Editor core: ~~engine buffers, save~~ (M1.3), ~~editor UI with tabs, undo, multi-caret~~ (M1.6, CodeMirror basics), ~~recovery journal~~ (M1.7), tab management (preview, pin, split, close others, reopen), conflict UI for files changed on disk, autosave option | M1 | ~16 h |
| G3 | Project model: ~~VFS~~ (M1.2: listing, ignore rules, native file watching with polling fallback, safe file IO), ~~project tree wiring~~ (M1.5 UI, M1.3 engine, M1.4 bridge: folder picker, live tree), tree toolbar and options, ~~showing truncated listings~~ (M1.13), ~~error notifications for the folder picker~~ (M1.12), ~~tabs~~ (M1.6), ~~command palette~~ (M1.8: commands only, global keymap, UI commands over the control channel); settings (backend: M1.9a; dialog: M1.9b), ~~theme switching~~ (M1.10: light/dark, live, system mode; picker comes with the dialog) | M1 | ~24 h | | G3 | Project model: ~~VFS~~ (M1.2: listing, ignore rules, native file watching with polling fallback, safe file IO), ~~project tree wiring~~ (M1.5 UI, M1.3 engine, M1.4 bridge: folder picker, live tree), tree toolbar and options, ~~showing truncated listings~~ (M1.13), ~~error notifications for the folder picker~~ (M1.12), ~~tabs~~ (M1.6), ~~command palette~~ (M1.8: commands only, global keymap, UI commands over the control channel); ~~settings~~ (backend: M1.9a; dialog with search: M1.9b), ~~theme switching~~ (M1.10: light/dark, live, system mode; picker in the dialog, M1.9b) | M1 | ~24 h |
| G4 | Syntax and structure: tree-sitter PHP, Lezer highlighting, file structure | M2 | ~15 h | | G4 | Syntax and structure: tree-sitter PHP, Lezer highlighting, file structure | M2 | ~15 h |
| G5 | Search and navigation: find in files, go to file/class/symbol, first index | M2 | ~35 h | | G5 | Search and navigation: find in files, go to file/class/symbol, first index | M2 | ~35 h |
| G6 | Language server: completion, diagnostics, definition, hover, rename via Phpactor | M3 | ~45 h | | G6 | Language server: completion, diagnostics, definition, hover, rename via Phpactor | M3 | ~45 h |
@ -40,6 +40,7 @@ Known smaller items from M0:
| Date | Change | Summary | | Date | Change | Summary |
|---|---|---| |---|---|---|
| 2026-10-16 | minor | G3: settings dialog, theme picker (M1.9b) |
| 2026-10-16 | minor | G2/G3: re-open focuses the tab, open buffers' folders watched, truncated listings shown (M1.13) | | 2026-10-16 | minor | G2/G3: re-open focuses the tab, open buffers' folders watched, truncated listings shown (M1.13) |
| 2026-10-15 | minor | G14 note: English message catalog (M1.11) | | 2026-10-15 | minor | G14 note: English message catalog (M1.11) |
| 2026-10-15 | minor | G2 shrunk: tabs and editor (M1.6) | | 2026-10-15 | minor | G2 shrunk: tabs and editor (M1.6) |

View file

@ -4,7 +4,7 @@
| Language | Code | Status | Translated | | Language | Code | Status | Translated |
|---|---|---|---:| |---|---|---|---:|
| English | `en` | source catalog (`ui/src/i18n/en.json`) | 100% of UI strings (46 keys, measured by the catalog test) | | English | `en` | source catalog (`ui/src/i18n/en.json`) | 100% of UI strings (80 keys, measured by the catalog test) |
| German | `de` | planned (G14) | 0% | | German | `de` | planned (G14) | 0% |
All interface strings go through the message catalog: `t(key, params?)` from `ui/src/i18n`, flat dotted keys grouped by area (`app.*`, `project.*`, `editor.*`, `common.*`), `{name}` placeholders. Lint (`vue/no-bare-strings-in-template`, error) rejects bare text in templates; a Vitest scan checks that every key passed to `t` exists in `en.json` and that the catalog has no unused keys. All interface strings go through the message catalog: `t(key, params?)` from `ui/src/i18n`, flat dotted keys grouped by area (`app.*`, `project.*`, `editor.*`, `common.*`), `{name}` placeholders. Lint (`vue/no-bare-strings-in-template`, error) rejects bare text in templates; a Vitest scan checks that every key passed to `t` exists in `en.json` and that the catalog has no unused keys.
@ -16,7 +16,7 @@ All interface strings go through the message catalog: `t(key, params?)` from `ui
- [x] Every UI string in `ui/src` from the catalog: templates, `title` and `aria-label` attributes, notices, frontend error texts (M1.11) - [x] Every UI string in `ui/src` from the catalog: templates, `title` and `aria-label` attributes, notices, frontend error texts (M1.11)
- [x] Notification texts: engine and host notifications carry a `messageKey` with params; all 12 notification message keys are in the catalog (M1.7, M1.12), `message` is only the English fallback - [x] Notification texts: engine and host notifications carry a `messageKey` with params; all 12 notification message keys are in the catalog (M1.7, M1.12), `message` is only the English fallback
- [ ] Engine messages: `EngineError.message` and other texts the engine sends are English only; they need message keys and params (G14) - [ ] Engine messages: `EngineError.message` and other texts the engine sends are English only; they need message keys and params (G14)
- [ ] Setting labels and descriptions from `settings.list` (`labelKey`, `descriptionKey`) in the catalog (M1.9b) - [x] Setting labels, descriptions, section names and enum value names from `settings.list` in the catalog (M1.9b)
- [ ] Language switch through `ui.language`; the catalog becomes reactive (G14) - [ ] Language switch through `ui.language`; the catalog becomes reactive (G14)
- [ ] Plural forms and number/date formatting per locale (G14) - [ ] Plural forms and number/date formatting per locale (G14)
- [ ] German catalog (G14) - [ ] German catalog (G14)
@ -26,6 +26,7 @@ All interface strings go through the message catalog: `t(key, params?)` from `ui
| Date | Change | Summary | | Date | Change | Summary |
|---|---|---| |---|---|---|
| 2026-10-16 | minor | M1.9b: settings keys, key count 80 |
| 2026-10-16 | minor | M1.12: notification keys, key count 46 | | 2026-10-16 | minor | M1.12: notification keys, key count 46 |
| 2026-10-15 | minor | M1.11: English catalog, lint rule, checklist; engine-message gap | | 2026-10-15 | minor | M1.11: English catalog, lint rule, checklist; engine-message gap |
| 2026-10-13 | major | Baseline | | 2026-10-13 | major | Baseline |

View file

@ -1,13 +1,13 @@
# Milestones # Milestones
> **Status:** M0 done, M1 in progress · **Last updated:** 2026-10-16 > **Status:** M0 done, M1 done · **Last updated:** 2026-10-16
Hours are agent wall-clock hours for one agent; M0 and M1 so far are measured, the rest estimated. Since cycle C1 (factor 0.07) M1–M3 are scaled ×0.1; M4–M6 keep their first raw estimates (multiply by ~0.1 for the calibrated value). Hours are agent wall-clock hours for one agent; M0 and M1 so far are measured, the rest estimated. Since cycle C1 (factor 0.07) M1–M3 are scaled ×0.1; M4–M6 keep their first raw estimates (multiply by ~0.1 for the calibrated value).
| Milestone | Goal | State | Hours | | Milestone | Goal | State | Hours |
|---|---|---|---:| |---|---|---|---:|
| M0 | Foundation: workspace, lints, quality gate, command registry, control channel, empty window | done 2026-10-14 (CI workflow written, not yet run: hosted on Forgejo, runners unknown) | ~2 (measured) | | M0 | Foundation: workspace, lints, quality gate, command registry, control channel, empty window | done 2026-10-14 (CI workflow written, not yet run: hosted on Forgejo, runners unknown) | ~2 (measured) |
| M1 | Editor and project: open folder, tree, tabs, editor, save, recovery, palette, settings, themes | in progress (M1.1 text, M1.2 VFS, M1.5 tree UI, M1.3 engine workspace, M1.4 desktop bridge, M1.6 tabs and editor, M1.11 message catalog, M1.9a settings backend, M1.10 themes, M1.7 recovery journal, M1.12 notifications, M1.13 C1 follow-ups, M1.8 command palette and keymap) | ~6 (2.5 measured for M1.1–M1.6) | | M1 | Editor and project: open folder, tree, tabs, editor, save, recovery, palette, settings, themes | done 2026-10-16 (M1.1 text, M1.2 VFS, M1.5 tree UI, M1.3 engine workspace, M1.4 desktop bridge, M1.6 tabs and editor, M1.11 message catalog, M1.9a settings backend, M1.10 themes, M1.7 recovery journal, M1.12 notifications, M1.13 C1 follow-ups, M1.8 command palette and keymap, M1.14 app icon, M1.9b settings dialog; C2 live checks pending, gaming mode) | ~6 (2.5 measured for M1.1–M1.6) |
| M2 | Syntax and search: highlighting, structure, find in files, go to file/class/symbol | not started | ~5 | | M2 | Syntax and search: highlighting, structure, find in files, go to file/class/symbol | not started | ~5 |
| M3 | LSP, terminal, CLI: completion, diagnostics, go to definition, hover, rename; terminal; `lutra` CLI and MCP — **MVP** | not started | ~8 | | M3 | LSP, terminal, CLI: completion, diagnostics, go to definition, hover, rename; terminal; `lutra` CLI and MCP — **MVP** | not started | ~8 |
| M4 | Git: status, diff, commit, branches, log, blame, conflicts | not started | ~150 | | M4 | Git: status, diff, commit, branches, log, blame, conflicts | not started | ~150 |
@ -31,6 +31,7 @@ By the raw estimates the alpha gate needs M1–M4 plus cross-platform verificati
| Date | Change | Summary | | Date | Change | Summary |
|---|---|---| |---|---|---|
| 2026-10-16 | minor | M1.9b settings dialog; M1 done |
| 2026-10-16 | minor | M1.8 command palette, global keymap, UI commands | | 2026-10-16 | minor | M1.8 command palette, global keymap, UI commands |
| 2026-10-16 | minor | M1.12 notifications | | 2026-10-16 | minor | M1.12 notifications |
| 2026-10-16 | minor | M1.13 C1 follow-ups | | 2026-10-16 | minor | M1.13 C1 follow-ups |

View file

@ -1,6 +1,6 @@
# Target-app parity # Target-app parity
> **Status:** M1 in progress (text buffer, VFS, engine workspace, project tree, tabs and a plain-text editor in the app), no PHP feature ships · **Last updated:** 2026-10-16 · **Target:** PhpStorm 2026.x > **Status:** M1 done (text buffer, VFS, engine workspace, project tree, tabs and a plain-text editor, recovery, palette, settings and themes in the app), no PHP feature ships · **Last updated:** 2026-10-16 · **Target:** PhpStorm 2026.x
## How this is measured ## How this is measured
@ -31,7 +31,7 @@ Hours are the estimated agent wall-clock hours for one agent to reach behaviour
| HTTP client | 1 | 0% | everything | ~60 (est.) | — | | HTTP client | 1 | 0% | everything | ~60 (est.) | — |
| Web languages | 2 | 0% | everything | ~200 (est.) | — | | Web languages | 2 | 0% | everything | ~200 (est.) | — |
| Docker and remote | 1 | 0% | everything | ~120 (est.) | — | | Docker and remote | 1 | 0% | everything | ~120 (est.) | — |
| Settings, keymaps, themes | 1 | 4% (est.) | settings UI, keymaps (M1.8: one global keymap from the commands' default shortcuts, not editable), colour scheme editor, custom and imported themes, per-language colours (M1.9a: settings backend with 3 keys, persistence, `settings.*` commands, no UI yet; M1.10: light and dark themes with live switching and a system mode, chosen through the setting only) | ~60 (est.) | — | | Settings, keymaps, themes | 1 | 7% (est.) | nested settings tree, project-level settings, export/import, keymaps (M1.8: one global keymap from the commands' default shortcuts, not editable), colour scheme editor, custom and imported themes, per-language colours (M1.9a: settings backend with 3 keys, persistence, `settings.*` commands, no UI yet; M1.10: light and dark themes with live switching and a system mode; M1.9b: settings dialog with search, controls by type, reset, live updates, theme picker, editor font size) | ~60 (est.) | — |
| Plug-ins | 0.5 | 0% | everything | ~120 (est.) | — | | Plug-ins | 0.5 | 0% | everything | ~120 (est.) | — |
| AI features | 0.5 | 0% | everything | ~60 (est.) | — | | AI features | 0.5 | 0% | everything | ~60 (est.) | — |
@ -48,7 +48,7 @@ No PHP feature. The foundation, verified on Windows 11:
- Control channel: `app.ping`, `engine.execute`, `engine.listCommands`, `ui.screenshot`, with proptests and a TCP integration test (`crates/control`), and checked against the running app. - Control channel: `app.ping`, `engine.execute`, `engine.listCommands`, `ui.screenshot`, with proptests and a TCP integration test (`crates/control`), and checked against the running app.
- The desktop window opens themed from Rust tokens and shows the product name and version that the frontend gets from `app.about` over IPC. - The desktop window opens themed from Rust tokens and shows the product name and version that the frontend gets from `app.about` over IPC.
## What ships (M1, in progress) ## What ships (M1, done 2026-10-16)
The project tree is the first user-visible feature (Project view 8%, estimated); every other score stays 0%. The project tree is the first user-visible feature (Project view 8%, estimated); every other score stays 0%.
@ -57,11 +57,13 @@ The project tree is the first user-visible feature (Project view 8%, estimated);
` / ` ` / `
` detection with a keep-the-file's-ending save policy. 23 unit tests and 6 proptests (round-trips on emoji, ZWJ sequences, CJK and combining marks; random edit batches checked against a `String` model, never panicking). ` detection with a keep-the-file's-ending save policy. 23 unit tests and 6 proptests (round-trips on emoji, ZWJ sequences, CJK and combining marks; random edit batches checked against a `String` model, never panicking).
- M1.10 themes (2026-10-16): Lutra Dark and Lutra Light with the same tokens, including real editor, tab and notice tokens; `appearance.theme` switches live without a reload, `system` follows the OS preference, and the window starts in the stored theme. Both themes pass a WCAG AA contrast test for every text/background pair in use. Checked by engine, control-channel and Vitest DOM tests; not yet looked at in the running app (gaming mode). No theme picker yet (settings dialog, M1.9b). - M1.10 themes (2026-10-16): Lutra Dark and Lutra Light with the same tokens, including real editor, tab and notice tokens; `appearance.theme` switches live without a reload, `system` follows the OS preference, and the window starts in the stored theme. Both themes pass a WCAG AA contrast test for every text/background pair in use. Checked by engine, control-channel and Vitest DOM tests; not yet looked at in the running app (gaming mode). No theme picker yet (settings dialog, M1.9b).
- M1.9b settings dialog (2026-10-16): `settings.open` (`Mod+,`) opens a dialog built from `settings.list` with sections, a select/number/switch per type, catalog labels and descriptions, search over label, description, key and section, Reset to default, changes applied at once with inline errors and live updates on `settingsChanged`; the theme picker switches at once and `editor.fontSize` sizes the editor. Vitest: `ui/tests/settings/SettingsDialog.test.ts` (14). Live check pending (gaming mode).
## Revision history ## Revision history
| Date | Change | Summary | | Date | Change | Summary |
|---|---|---| |---|---|---|
| 2026-10-16 | minor | M1.9b: Settings row 4% → 7% (est.), settings dialog; M1 done |
| 2026-10-16 | minor | M1.8: Navigation and Settings/keymaps evidence (palette, global keymap), scores unchanged | | 2026-10-16 | minor | M1.8: Navigation and Settings/keymaps evidence (palette, global keymap), scores unchanged |
| 2026-10-16 | minor | M1.12: Project view evidence (picker errors as toasts), scores unchanged | | 2026-10-16 | minor | M1.12: Project view evidence (picker errors as toasts), scores unchanged |
| 2026-10-16 | minor | M1.13: Editor core and Project view evidence (focus on re-open, watched buffer folders, truncated note), scores unchanged | | 2026-10-16 | minor | M1.13: Editor core and Project view evidence (focus on re-open, watched buffer folders, truncated note), scores unchanged |

View file

@ -1,6 +1,6 @@
# UI parity checklist # UI parity checklist
> **Status:** main window layout (M1.5), project tree running against the engine (M1.4), editor tabs with a CodeMirror editor (M1.6), light and dark themes (M1.10), restore dialog for unsaved changes (M1.7), notification toasts (M1.12), command palette and global keymap (M1.8) · **Last updated:** 2026-10-16 > **Status:** main window layout (M1.5), project tree running against the engine (M1.4), editor tabs with a CodeMirror editor (M1.6), light and dark themes (M1.10), restore dialog for unsaved changes (M1.7), notification toasts (M1.12), command palette and global keymap (M1.8), settings dialog with search (M1.9b) · **Last updated:** 2026-10-16
- [ ] Main window: tool window stripes, editor area, status bar, navigation bar - [ ] Main window: tool window stripes, editor area, status bar, navigation bar
- M1.5 (2026-10-14): left tool window with header, hide button, collapsed stripe with a show button, resizable by pointer and keyboard; editor area placeholder; status bar. Missing: stripes with several tool windows, bottom/right docking, navigation bar, layout persistence. Not checked in the running app yet (needs M1.4). - M1.5 (2026-10-14): left tool window with header, hide button, collapsed stripe with a show button, resizable by pointer and keyboard; editor area placeholder; status bar. Missing: stripes with several tool windows, bottom/right docking, navigation bar, layout persistence. Not checked in the running app yet (needs M1.4).
@ -12,12 +12,13 @@
- [ ] Restore dialog for unsaved changes after a crash - [ ] Restore dialog for unsaved changes after a crash
- M1.7 (2026-10-16): modal dialog after a project opens when the recovery journal holds unsaved texts: files with the time they were journaled and a hint when the file changed on disk since; Restore All, Restore Selected (the others stay listed), Discard; Escape keeps the journal for the next open; restore failures listed. Catalog strings, `--lt-*` tokens, Vitest (10 tests). Live check pending (gaming mode). Missing: a diff against the disk version, local history. Behaviour notes: `plan/phpstorm/04-recovery.md`. - M1.7 (2026-10-16): modal dialog after a project opens when the recovery journal holds unsaved texts: files with the time they were journaled and a hint when the file changed on disk since; Restore All, Restore Selected (the others stay listed), Discard; Escape keeps the journal for the next open; restore failures listed. Catalog strings, `--lt-*` tokens, Vitest (10 tests). Live check pending (gaming mode). Missing: a diff against the disk version, local history. Behaviour notes: `plan/phpstorm/04-recovery.md`.
- [ ] Command palette / search everywhere - [ ] Command palette / search everywhere
- M1.8 (2026-10-16): command palette (`Mod+Shift+P`) over every user-facing command, engine and UI (commands with a menu path or default shortcut, plus UI commands): fuzzy ranking on the label and the id (prefix, word prefix, word starts, substring, in-order characters), recently run commands first, shortcuts shown, disabled commands dimmed and not runnable, arrow keys, Enter, Escape, focus returned on close; a failing command raises an error toast. One global keymap (`ui/src/commands/`) matches every command's default shortcut by key code; UI commands `palette.open`, `settings.open` (`Mod+,`, disabled until the settings dialog, M1.9b) and `view.toggleProjectTree` (`Mod+1`). Vitest (keymap, ranking, store, palette, App); live check pending (gaming mode). Missing: files, classes, symbols and text tabs (search everywhere), settings in the results, synonyms and abbreviations, inline toggles, assigning a shortcut from the palette, recent commands across restarts. Behaviour notes: `plan/phpstorm/05-palette.md`. - M1.8 (2026-10-16): command palette (`Mod+Shift+P`) over every user-facing command, engine and UI (commands with a menu path or default shortcut, plus UI commands): fuzzy ranking on the label and the id (prefix, word prefix, word starts, substring, in-order characters), recently run commands first, shortcuts shown, disabled commands dimmed and not runnable, arrow keys, Enter, Escape, focus returned on close; a failing command raises an error toast. One global keymap (`ui/src/commands/`) matches every command's default shortcut by key code; UI commands `palette.open`, `settings.open` (`Mod+,`, opens the settings dialog since M1.9b) and `view.toggleProjectTree` (`Mod+1`). Vitest (keymap, ranking, store, palette, App); live check pending (gaming mode). Missing: files, classes, symbols and text tabs (search everywhere), settings in the results, synonyms and abbreviations, inline toggles, assigning a shortcut from the palette, recent commands across restarts. Behaviour notes: `plan/phpstorm/05-palette.md`.
- [ ] Settings dialog with search - [ ] Settings dialog with search
- M1.9b (2026-10-16): dialog (`Mod+,`, palette, control channel) built from `settings.list`: sections on the left, controls by type (select, number with min/max, switch), labels and descriptions from the catalog, search over label, description, key and section with matches grouped by section, Reset to default per setting, changes applied at once with inline errors, live updates on `settingsChanged`, theme picker (`appearance.theme`, switches at once), editor font size applied to the editor; Escape closes, focus trapped, every control reachable by Tab. Vitest (14 tests); live check pending (gaming mode). Missing: a tree of nested categories, project-level settings and their marker, modified markers, highlighting matches, export/import, more settings (keymap, code style, inspections). Behaviour notes: `plan/phpstorm/06-settings.md`.
- [ ] Keymap editor (Lutra's own default keymap; no copied keymaps) - [ ] Keymap editor (Lutra's own default keymap; no copied keymaps)
- M1.8 (2026-10-16): the global keymap built from the default shortcuts of engine and UI commands; no user keymap and no editor yet. - M1.8 (2026-10-16): the global keymap built from the default shortcuts of engine and UI commands; no user keymap and no editor yet.
- [ ] Light and dark themes from theme tokens - [ ] Light and dark themes from theme tokens
- M1.10 (2026-10-16): Lutra Dark and Lutra Light from Rust tokens, switched live through `appearance.theme` (no reload), `system` follows the OS preference, the first frame uses the stored theme; the editor (selection, active line, cursor, gutter, matches), tabs and notices have their own tokens; WCAG AA contrast checked by Vitest for every text pair in both themes. Covered by Vitest DOM and control-channel tests; live check pending (gaming mode). Missing: a theme picker (settings dialog, M1.9b; command palette, M1.8), the native title bar following the theme, editor font size from `editor.fontSize`, colour scheme editor, high-contrast theme, design review of the values. - M1.10 (2026-10-16): Lutra Dark and Lutra Light from Rust tokens, switched live through `appearance.theme` (no reload), `system` follows the OS preference, the first frame uses the stored theme; the editor (selection, active line, cursor, gutter, matches), tabs and notices have their own tokens; WCAG AA contrast checked by Vitest for every text pair in both themes. Covered by Vitest DOM and control-channel tests; live check pending (gaming mode). M1.9b: theme picker in the settings dialog, editor font size from `editor.fontSize`. Missing: a theme command in the palette, the native title bar following the theme, colour scheme editor, high-contrast theme, design review of the values.
- [ ] Notifications and background task indicator - [ ] Notifications and background task indicator
- M1.12 (2026-10-16): toasts at the bottom right for engine and host notifications (corrupt settings and journal entries at startup, folder that cannot be opened, `unsaved_changes` when switching projects, file watching stopped, failed commands without their own UI): info dismissed after 5 s, warnings and errors stay until closed, close button and Escape, at most 5 visible with "+n more", `role="status"`/`role="alert"`; startup notifications are replayed when the page starts listening. Vitest (19 store and component tests); live check pending (gaming mode). Missing: a notification log / Notifications tool window, actions inside a toast, balloon grouping, "don't show again", background task indicator with progress. - M1.12 (2026-10-16): toasts at the bottom right for engine and host notifications (corrupt settings and journal entries at startup, folder that cannot be opened, `unsaved_changes` when switching projects, file watching stopped, failed commands without their own UI): info dismissed after 5 s, warnings and errors stay until closed, close button and Escape, at most 5 visible with "+n more", `role="status"`/`role="alert"`; startup notifications are replayed when the page starts listening. Vitest (19 store and component tests); live check pending (gaming mode). Missing: a notification log / Notifications tool window, actions inside a toast, balloon grouping, "don't show again", background task indicator with progress.
- [ ] Structure tool window - [ ] Structure tool window
@ -30,6 +31,7 @@
| Date | Change | Summary | | Date | Change | Summary |
|---|---|---| |---|---|---|
| 2026-10-16 | minor | Settings dialog partial; theme picker and editor font size (M1.9b) |
| 2026-10-16 | minor | Command palette and global keymap partial (M1.8) | | 2026-10-16 | minor | Command palette and global keymap partial (M1.8) |
| 2026-10-16 | minor | Notifications partial (M1.12) | | 2026-10-16 | minor | Notifications partial (M1.12) |
| 2026-10-16 | minor | Truncated listing note, re-open switches tab (M1.13) | | 2026-10-16 | minor | Truncated listing note, re-open switches tab (M1.13) |

View file

@ -2,11 +2,12 @@
/** /**
* Root component: mounts the main window layout with the editor area; the * Root component: mounts the main window layout with the editor area; the
* slogan shows while no tab is open, and the restore dialog for unsaved * slogan shows while no tab is open, and the restore dialog for unsaved
* texts from the recovery journal, the toast stack and the command * texts from the recovery journal, the toast stack, the command palette
* palette. Loads product information from the engine on mount, starts * and the settings dialog. Loads product information from the engine on
* showing notifications, following the theme (see `theme.ts`; a failed * mount, starts showing notifications, following the theme (see
* theme report raises an error toast) and the global keymap with the UI * `theme.ts`; a failed theme report raises an error toast) and the global
* commands (see `commands/store.ts`). * keymap with the UI commands (see `commands/store.ts`), and loads the settings so the
* editor font size applies from the start (see `stores/settings.ts`).
*/ */
import { onMounted, onUnmounted } from "vue"; import { onMounted, onUnmounted } from "vue";
import { useCommandsStore } from "./commands/store"; import { useCommandsStore } from "./commands/store";
@ -15,13 +16,16 @@ import EditorArea from "./components/editor/EditorArea.vue";
import MainLayout from "./components/layout/MainLayout.vue"; import MainLayout from "./components/layout/MainLayout.vue";
import NotificationStack from "./components/notifications/NotificationStack.vue"; import NotificationStack from "./components/notifications/NotificationStack.vue";
import RecoveryDialog from "./components/recovery/RecoveryDialog.vue"; import RecoveryDialog from "./components/recovery/RecoveryDialog.vue";
import SettingsDialog from "./components/settings/SettingsDialog.vue";
import { useAppStore } from "./stores/app"; import { useAppStore } from "./stores/app";
import { useNotificationsStore } from "./stores/notifications"; import { useNotificationsStore } from "./stores/notifications";
import { useSettingsStore } from "./stores/settings";
import { startTheme } from "./theme"; import { startTheme } from "./theme";
const app = useAppStore(); const app = useAppStore();
const notifications = useNotificationsStore(); const notifications = useNotificationsStore();
const commands = useCommandsStore(); const commands = useCommandsStore();
const settings = useSettingsStore();
/** Stops following the theme; set while mounted. */ /** Stops following the theme; set while mounted. */
let stopTheme: (() => void) | null = null; let stopTheme: (() => void) | null = null;
@ -30,6 +34,7 @@ onMounted(() => {
notifications.start(); notifications.start();
stopTheme = startTheme((error) => notifications.notifyError("theme.systemPreference", error)); stopTheme = startTheme((error) => notifications.notifyError("theme.systemPreference", error));
void commands.start(); void commands.start();
void settings.start();
void app.loadAbout(); void app.loadAbout();
}); });
@ -37,6 +42,7 @@ onUnmounted(() => {
stopTheme?.(); stopTheme?.();
stopTheme = null; stopTheme = null;
commands.stop(); commands.stop();
settings.stop();
notifications.stop(); notifications.stop();
}); });
</script> </script>
@ -51,6 +57,7 @@ onUnmounted(() => {
</MainLayout> </MainLayout>
<RecoveryDialog /> <RecoveryDialog />
<CommandPalette /> <CommandPalette />
<SettingsDialog />
<NotificationStack /> <NotificationStack />
</template> </template>

View file

@ -0,0 +1,730 @@
<script setup lang="ts">
/**
* The settings dialog (`settings.open`, `Mod+,`), built from the engine's
* `settings.list`: sections on the left, the settings of the chosen
* section on the right, each with its control by type (enum → select,
* int → number field with min/max, bool → switch), label and description
* from the catalog, and "Reset to default" when it differs from the
* default.
*
* - **Search:** the field filters by label, description, key and section
* name; while it has text, every match shows, grouped by section.
* - **Changes** apply at once through `settings.set` (a number when the
* field is committed: Enter, the spinner or leaving it). A refused value
* shows its error under the control and keeps the typed text.
* - **Live:** values follow `settingsChanged` through the settings store,
* so a change over the control channel shows while the dialog is open.
* - **Keyboard:** Escape closes, Tab and Shift+Tab stay inside the dialog,
* and the focus returns to where it was.
*/
import { X } from "@lucide/vue";
import { computed, nextTick, onBeforeUnmount, onMounted, reactive, ref } from "vue";
import { useCommandsStore } from "../../commands/store";
import { t } from "../../i18n";
import {
descriptionOf,
groupSections,
labelOf,
matchesQuery,
useSettingsStore,
valueLabel,
type SettingDef,
type SettingSection,
} from "../../stores/settings";
const commands = useCommandsStore();
const settings = useSettingsStore();
/** Whether the dialog is shown. */
const open = ref(false);
/** What the user typed into the search field. */
const query = ref("");
/** Id of the chosen section. */
const current = ref<string | null>(null);
/** Text typed into number fields, by key; shown while their value is refused. */
const drafts = reactive<Record<string, string>>({});
/** The dialog element. */
const dialog = ref<HTMLElement | null>(null);
/** The search field. */
const search = ref<HTMLInputElement | null>(null);
/** The element that had the focus before the dialog opened. */
let returnFocus: HTMLElement | null = null;
/** Withdraws the `settings.open` handler; set while mounted. */
let withdraw: (() => void) | null = null;
/** Every section. */
const sections = computed<SettingSection[]>(() => groupSections(settings.defs));
/** Whether the search field has text. */
const searching = computed(() => query.value.trim() !== "");
/** The sections shown on the right: the chosen one, or every match while searching. */
const shown = computed<SettingSection[]>(() => {
if (searching.value) {
return sections.value
.map((section) => ({ ...section, settings: section.settings.filter((def) => matchesQuery(def, query.value)) }))
.filter((section) => section.settings.length > 0);
}
const chosen = sections.value.find((section) => section.id === current.value) ?? sections.value[0];
return chosen ? [chosen] : [];
});
/** Ids of the sections that have matches. */
const matching = computed(() => new Set(shown.value.map((section) => section.id)));
/** The id of the section highlighted on the left. */
const activeSection = computed(() =>
searching.value ? (shown.value[0]?.id ?? null) : (current.value ?? sections.value[0]?.id ?? null),
);
/**
* DOM id of a setting's control.
*
* @param def - the setting.
*/
function controlId(def: SettingDef): string {
return `lt-setting-${def.key.replace(/[^A-Za-z0-9]/g, "-")}`;
}
/**
* The text of a number field: the refused draft while there is an error,
* else the value.
*
* @param def - the setting.
*/
function numberText(def: SettingDef): string {
const draft = drafts[def.key];
if (draft !== undefined && settings.errors[def.key] !== undefined) {
return draft;
}
const value = settings.values[def.key];
return typeof value === "number" ? String(value) : "";
}
/**
* The value of a select.
*
* @param def - the setting.
*/
function enumValue(def: SettingDef): string {
const value = settings.values[def.key];
return typeof value === "string" ? value : "";
}
/**
* Whether a switch is on.
*
* @param def - the setting.
*/
function boolValue(def: SettingDef): boolean {
return settings.values[def.key] === true;
}
/**
* Applies a select's choice.
*
* @param def - the setting.
* @param event - the change event.
*/
async function onSelect(def: SettingDef, event: Event): Promise<void> {
const target = event.target;
if (target instanceof HTMLSelectElement) {
await settings.set(def.key, target.value);
}
}
/**
* Applies a committed number field. Text that is no whole number in range
* is refused here with the catalog's message; the engine validates
* everything else.
*
* @param def - the setting.
* @param event - the change event.
*/
async function onNumber(def: SettingDef, event: Event): Promise<void> {
const target = event.target;
if (!(target instanceof HTMLInputElement)) {
return;
}
const text = target.value.trim();
drafts[def.key] = target.value;
const value = Number(text);
const inRange =
text !== "" &&
Number.isInteger(value) &&
(def.min === null || value >= def.min) &&
(def.max === null || value <= def.max);
if (!inRange) {
settings.setError(
def.key,
def.min !== null && def.max !== null
? t("settings.error.intRange", { min: def.min, max: def.max })
: t("settings.error.int"),
);
return;
}
if (await settings.set(def.key, value)) {
Reflect.deleteProperty(drafts, def.key);
}
}
/**
* Flips a switch.
*
* @param def - the setting.
*/
async function onToggle(def: SettingDef): Promise<void> {
await settings.set(def.key, !boolValue(def));
}
/**
* Resets a setting and drops its draft.
*
* @param def - the setting.
*/
async function onReset(def: SettingDef): Promise<void> {
if (await settings.reset(def.key)) {
Reflect.deleteProperty(drafts, def.key);
}
}
/**
* Chooses a section; clears the search so the section shows whole.
*
* @param id - the section id.
*/
function choose(id: string): void {
current.value = id;
query.value = "";
}
/** Opens the dialog (or focuses its search field) and reloads the settings. */
async function show(): Promise<void> {
if (!open.value) {
const active = document.activeElement;
returnFocus = active instanceof HTMLElement ? active : null;
query.value = "";
open.value = true;
}
await nextTick();
search.value?.focus();
await settings.load();
}
/** Closes the dialog and gives the focus back. */
function close(): void {
if (!open.value) {
return;
}
open.value = false;
for (const key of Object.keys(drafts)) {
Reflect.deleteProperty(drafts, key);
}
returnFocus?.focus();
returnFocus = null;
}
/** The elements Tab reaches inside the dialog, in order. */
function focusables(): HTMLElement[] {
const root = dialog.value;
if (!root) {
return [];
}
return [
...root.querySelectorAll<HTMLElement>(
"button:not([disabled]), input:not([disabled]), select:not([disabled]), [tabindex]:not([tabindex='-1'])",
),
];
}
/**
* Keyboard handling of the dialog: Escape closes, Tab wraps around.
*
* @param event - the key press.
*/
function onKeydown(event: KeyboardEvent): void {
if (event.key === "Escape") {
event.preventDefault();
event.stopPropagation();
close();
return;
}
if (event.key !== "Tab") {
return;
}
const list = focusables();
const first = list[0];
const last = list.at(-1);
if (!first || !last) {
event.preventDefault();
return;
}
const active = document.activeElement;
const inside = active instanceof HTMLElement && list.includes(active);
if (event.shiftKey && (active === first || !inside)) {
event.preventDefault();
last.focus();
} else if (!event.shiftKey && (active === last || !inside)) {
event.preventDefault();
first.focus();
}
}
/**
* Keeps the focus inside the dialog when something outside would get it,
* except for another modal dialog opened above it (the palette).
*
* @param event - a focus change anywhere in the document.
*/
function onFocusIn(event: FocusEvent): void {
const root = dialog.value;
const target = event.target;
if (!open.value || !root || !(target instanceof Element) || root.contains(target)) {
return;
}
if (target.closest("[aria-modal='true']")) {
return;
}
search.value?.focus();
}
onMounted(() => {
withdraw = commands.provide("settings.open", { run: show });
document.addEventListener("focusin", onFocusIn);
});
onBeforeUnmount(() => {
withdraw?.();
withdraw = null;
document.removeEventListener("focusin", onFocusIn);
});
defineExpose({ show, close });
</script>
<template>
<div
v-if="open"
class="settings"
data-test="settings"
@mousedown.self.prevent="close()"
>
<div
ref="dialog"
class="settings__dialog"
role="dialog"
aria-modal="true"
aria-labelledby="lt-settings-title"
data-test="settings-dialog"
@keydown="onKeydown"
>
<header class="settings__header">
<h2
id="lt-settings-title"
class="settings__title"
>
{{ t("settings.dialog.title") }}
</h2>
<input
ref="search"
v-model="query"
class="settings__search"
type="search"
:aria-label="t('settings.dialog.search')"
:placeholder="t('settings.dialog.search')"
spellcheck="false"
autocomplete="off"
data-test="settings-search"
>
<button
type="button"
class="settings__close"
:aria-label="t('common.close')"
:title="t('common.close')"
data-test="settings-close"
@click="close()"
>
<X
:size="16"
aria-hidden="true"
/>
</button>
</header>
<div class="settings__body">
<nav
class="settings__nav"
:aria-label="t('settings.dialog.sections')"
>
<ul class="settings__sections">
<li
v-for="section in sections"
:key="section.id"
>
<button
type="button"
class="settings__section"
:class="{
'settings__section--active': section.id === activeSection,
'settings__section--dim': searching && !matching.has(section.id),
}"
:aria-current="section.id === activeSection ? 'true' : undefined"
:data-section="section.id"
data-test="settings-section"
@click="choose(section.id)"
>
{{ section.label }}
</button>
</li>
</ul>
</nav>
<div
class="settings__pane"
data-test="settings-pane"
>
<p
v-if="settings.loadError"
class="settings__error"
role="alert"
data-test="settings-load-error"
>
{{ t("settings.dialog.loadFailed", { message: settings.loadError }) }}
</p>
<p
v-if="searching && shown.length === 0"
class="settings__empty"
role="status"
data-test="settings-empty"
>
{{ t("settings.dialog.noMatches") }}
</p>
<section
v-for="section in shown"
:key="section.id"
class="settings__group"
:aria-labelledby="`lt-settings-group-${section.id}`"
>
<h3
:id="`lt-settings-group-${section.id}`"
class="settings__group-title"
>
{{ section.label }}
</h3>
<div
v-for="def in section.settings"
:key="def.key"
class="settings__row"
:data-key="def.key"
data-test="settings-row"
>
<div class="settings__text">
<label
:for="controlId(def)"
class="settings__label"
>{{ labelOf(def) }}</label>
<p
:id="`${controlId(def)}-description`"
class="settings__description"
>
{{ descriptionOf(def) }}
</p>
<p
v-if="settings.errors[def.key]"
:id="`${controlId(def)}-error`"
class="settings__error"
role="alert"
data-test="settings-error"
>
{{ settings.errors[def.key] }}
</p>
</div>
<div class="settings__control">
<select
v-if="def.type === 'enum'"
:id="controlId(def)"
class="settings__input"
:value="enumValue(def)"
:aria-describedby="`${controlId(def)}-description`"
:aria-invalid="settings.errors[def.key] ? 'true' : undefined"
:aria-errormessage="settings.errors[def.key] ? `${controlId(def)}-error` : undefined"
data-test="settings-control"
@change="onSelect(def, $event)"
>
<option
v-for="option in def.enumValues"
:key="option"
:value="option"
>
{{ valueLabel(def, option) }}
</option>
</select>
<input
v-else-if="def.type === 'int'"
:id="controlId(def)"
class="settings__input settings__input--number"
type="number"
step="1"
:min="def.min ?? undefined"
:max="def.max ?? undefined"
:value="numberText(def)"
:aria-describedby="`${controlId(def)}-description`"
:aria-invalid="settings.errors[def.key] ? 'true' : undefined"
:aria-errormessage="settings.errors[def.key] ? `${controlId(def)}-error` : undefined"
data-test="settings-control"
@change="onNumber(def, $event)"
>
<button
v-else
:id="controlId(def)"
type="button"
role="switch"
class="settings__switch"
:class="{ 'settings__switch--on': boolValue(def) }"
:aria-checked="boolValue(def)"
:aria-describedby="`${controlId(def)}-description`"
data-test="settings-control"
@click="onToggle(def)"
>
<span class="settings__knob" />
</button>
<button
type="button"
class="settings__reset"
:disabled="settings.isDefault(def)"
:aria-label="t('settings.dialog.resetLabel', { name: labelOf(def) })"
data-test="settings-reset"
@click="onReset(def)"
>
{{ t("settings.dialog.reset") }}
</button>
</div>
</div>
</section>
</div>
</div>
</div>
</div>
</template>
<style scoped>
.settings {
position: fixed;
inset: 0;
display: flex;
align-items: center;
justify-content: center;
background: color-mix(in srgb, var(--lt-bg) 40%, transparent);
z-index: 30;
}
.settings__dialog {
width: min(760px, 92vw);
height: min(520px, 84vh);
display: flex;
flex-direction: column;
background: var(--lt-bg);
color: var(--lt-fg);
border: 1px solid var(--lt-border);
border-radius: 6px;
overflow: hidden;
}
.settings__header {
display: flex;
align-items: center;
gap: 12px;
padding: 8px 12px;
border-bottom: 1px solid var(--lt-border);
}
.settings__title {
margin: 0;
font-size: var(--lt-font-size-ui);
font-weight: 600;
}
.settings__search {
flex: 1;
min-width: 0;
padding: 4px 8px;
font: inherit;
color: var(--lt-fg);
background: var(--lt-editor-bg);
border: 1px solid var(--lt-border);
border-radius: 4px;
}
.settings__close {
display: flex;
padding: 4px;
color: var(--lt-fg);
background: none;
border: none;
border-radius: 4px;
cursor: pointer;
}
.settings__body {
flex: 1;
min-height: 0;
display: flex;
}
.settings__nav {
width: 180px;
flex-shrink: 0;
overflow-y: auto;
border-right: 1px solid var(--lt-border);
}
.settings__sections {
margin: 0;
padding: 4px 0;
list-style: none;
}
.settings__section {
width: 100%;
padding: 4px 12px;
font: inherit;
text-align: left;
color: var(--lt-fg);
background: none;
border: none;
cursor: pointer;
}
.settings__section--active {
background: var(--lt-editor-selection-bg);
color: var(--lt-fg);
}
.settings__section--dim {
opacity: 0.55;
}
.settings__pane {
flex: 1;
min-width: 0;
overflow-y: auto;
padding: 8px 16px 16px;
}
.settings__group-title {
margin: 8px 0;
font-size: var(--lt-font-size-ui);
font-weight: 600;
}
.settings__row {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 16px;
padding: 8px 0;
border-bottom: 1px solid var(--lt-border);
}
.settings__text {
min-width: 0;
}
.settings__label {
display: block;
}
.settings__description {
margin: 2px 0 0;
font-size: var(--lt-font-size-small);
color: var(--lt-fg-muted);
}
.settings__error {
margin: 4px 0 0;
font-size: var(--lt-font-size-small);
color: var(--lt-error);
}
.settings__empty {
color: var(--lt-fg-muted);
}
.settings__control {
display: flex;
align-items: center;
gap: 8px;
flex-shrink: 0;
}
.settings__input {
padding: 3px 6px;
font: inherit;
color: var(--lt-fg);
background: var(--lt-editor-bg);
border: 1px solid var(--lt-border);
border-radius: 4px;
}
.settings__input--number {
width: 6em;
}
.settings__input[aria-invalid="true"] {
border-color: var(--lt-error);
}
.settings__switch {
position: relative;
width: 32px;
height: 18px;
padding: 0;
background: var(--lt-editor-bg);
border: 1px solid var(--lt-border);
border-radius: 9px;
cursor: pointer;
}
.settings__switch--on {
background: var(--lt-accent);
}
.settings__knob {
position: absolute;
top: 2px;
left: 2px;
width: 12px;
height: 12px;
background: var(--lt-fg);
border-radius: 50%;
}
.settings__switch--on .settings__knob {
left: 16px;
background: var(--lt-bg);
}
.settings__reset {
padding: 3px 8px;
font: inherit;
font-size: var(--lt-font-size-small);
color: var(--lt-fg);
background: none;
border: 1px solid var(--lt-border);
border-radius: 4px;
cursor: pointer;
}
.settings__reset:disabled {
color: var(--lt-fg-muted);
cursor: default;
}
.settings__close:focus-visible,
.settings__section:focus-visible,
.settings__search:focus-visible,
.settings__input:focus-visible,
.settings__switch:focus-visible,
.settings__reset:focus-visible {
outline: 2px solid var(--lt-accent);
outline-offset: 1px;
}
</style>

View file

@ -56,6 +56,27 @@
"recovery.dialog.restoreSelected": "Restore Selected", "recovery.dialog.restoreSelected": "Restore Selected",
"recovery.dialog.savedAt": "Saved {time}", "recovery.dialog.savedAt": "Saved {time}",
"recovery.dialog.title": "Unsaved changes found", "recovery.dialog.title": "Unsaved changes found",
"settings.appearance.theme.description": "Colours of the whole window. System follows the light or dark preference of your operating system.",
"settings.appearance.theme.label": "Theme",
"settings.appearance.theme.value.lutraDark": "Lutra Dark",
"settings.appearance.theme.value.lutraLight": "Lutra Light",
"settings.appearance.theme.value.system": "Same as system",
"settings.dialog.loadFailed": "Settings could not be loaded: {message}",
"settings.dialog.noMatches": "No settings match your search",
"settings.dialog.reset": "Reset to default",
"settings.dialog.resetLabel": "Reset {name} to default",
"settings.dialog.search": "Search settings",
"settings.dialog.sections": "Settings sections",
"settings.dialog.title": "Settings",
"settings.editor.fontSize.description": "Size of the text in the editor, in pixels.",
"settings.editor.fontSize.label": "Editor font size",
"settings.error.int": "Enter a whole number",
"settings.error.intRange": "Enter a whole number from {min} to {max}",
"settings.section.appearance": "Appearance",
"settings.section.editor": "Editor",
"settings.ui.language.description": "Language of the interface. More languages follow.",
"settings.ui.language.label": "Language",
"settings.ui.language.value.en": "English",
"theme.lutraDark": "Lutra Dark", "theme.lutraDark": "Lutra Dark",
"theme.lutraLight": "Lutra Light" "theme.lutraLight": "Lutra Light"
} }

View file

@ -28,6 +28,11 @@ export type EngineEventPayload =
| { kind: "fileChangedOnDisk"; path: string; id: number; removed: boolean } | { kind: "fileChangedOnDisk"; path: string; id: number; removed: boolean }
| { kind: "watchFailed"; message: string } | { kind: "watchFailed"; message: string }
| { kind: "themeChanged"; id: string; dark: boolean; tokens: Record<string, string> } | { kind: "themeChanged"; id: string; dark: boolean; tokens: Record<string, string> }
| {
kind: "settingsChanged";
/** Keys whose effective value changed; unchecked, it comes from the engine. */
keys: unknown;
}
| { | {
kind: "recoveryAvailable"; kind: "recoveryAvailable";
entries: { path: string; savedAt: number; diskChanged: boolean }[]; entries: { path: string; savedAt: number; diskChanged: boolean }[];

425
ui/src/stores/settings.ts Normal file
View file

@ -0,0 +1,425 @@
/**
* Settings as the engine defines them (`settings.list`) with their
* effective values (`settings.get`), changed through `settings.set` and
* `settings.reset`.
*
* - **Live:** `settingsChanged` (from the dialog, the control channel or
* an agent) reloads the changed values, so every view shows the current
* ones.
* - **Errors:** a refused change keeps the error per key until the value
* changes or another change succeeds; the dialog shows it inline.
* - **Effects:** `editor.fontSize` drives `--lt-font-size-editor` (above
* the theme's value, see `setTokenOverride`). `appearance.theme` needs
* nothing here: the engine answers with `themeChanged`.
* - **Text:** labels, descriptions, section names and enum value names are
* catalog keys (`settings.<key>.label`, `settings.<key>.description`,
* `settings.section.<id>`, `settings.<key>.value.<value>`); the engine
* sends no English for settings. A key the catalog lacks shows as is.
*/
import { defineStore } from "pinia";
import { reactive, ref } from "vue";
import { hasMessage, t } from "../i18n";
import { onEngineEvent, run, type EngineEventPayload } from "../ipc";
import { setTokenOverride } from "../theme";
/** A setting value: settings are scalars. Values from the engine are unchecked. */
export type SettingValue = string | number | boolean | null;
/** Types of settings the dialog has a control for. */
export type SettingType = "enum" | "int" | "bool";
/** A setting as `settings.list` describes it. */
export interface SettingDef {
/** Dotted key, e.g. `editor.fontSize`. */
key: string;
/** Type, which decides the control. */
type: SettingType;
/** Default value. */
default: SettingValue;
/** Accepted values of an enum; empty otherwise. */
enumValues: string[];
/** Smallest value of an int, or null. */
min: number | null;
/** Largest value of an int, or null. */
max: number | null;
/** Catalog key of the label. */
labelKey: string;
/** Catalog key of the description. */
descriptionKey: string;
/** Section id; shown with `settings.section.<id>`. */
section: string;
}
/** A section of the dialog with its settings, in engine order. */
export interface SettingSection {
/** Section id. */
id: string;
/** Catalog text of `settings.section.<id>`, or the id. */
label: string;
/** Its settings. */
settings: SettingDef[];
}
/** Key of the editor font size setting. */
export const FONT_SIZE_KEY = "editor.fontSize";
/** Theme token the editor font size drives. */
export const FONT_SIZE_TOKEN = "--lt-font-size-editor";
/** Most settings read from `settings.list`; the rest are dropped. */
export const MAX_SETTINGS = 1000;
/** Most characters of a setting value shown in an error or a draft. */
const MAX_TEXT = 256;
/**
* A scalar from untrusted data; anything else counts as null.
*
* @param value - the data.
*/
function toScalar(value: unknown): SettingValue {
return typeof value === "string" || typeof value === "number" || typeof value === "boolean" ? value : null;
}
/**
* Reads one `settings.list` entry from untrusted data.
*
* @param raw - the entry.
* @returns the setting, or null if it is malformed or of an unknown type.
*/
function toSettingDef(raw: unknown): SettingDef | null {
if (typeof raw !== "object" || raw === null) {
return null;
}
const entry = raw as Record<string, unknown>;
const { key, type, labelKey, descriptionKey, section, enumValues, min, max } = entry;
if (
typeof key !== "string" ||
typeof labelKey !== "string" ||
typeof descriptionKey !== "string" ||
typeof section !== "string" ||
(type !== "enum" && type !== "int" && type !== "bool")
) {
return null;
}
const values = Array.isArray(enumValues)
? (enumValues as unknown[]).filter((v): v is string => typeof v === "string")
: [];
if (type === "enum" && values.length === 0) {
return null;
}
return {
key,
type,
default: toScalar(entry.default),
enumValues: values,
min: typeof min === "number" && Number.isFinite(min) ? min : null,
max: typeof max === "number" && Number.isFinite(max) ? max : null,
labelKey,
descriptionKey,
section,
};
}
/**
* Reads the `settings.list` result, keeping well-formed entries.
*
* @param raw - the result.
* @returns the settings, or null if the result is not a list.
*/
export function toSettingDefs(raw: unknown): SettingDef[] | null {
if (!Array.isArray(raw)) {
return null;
}
return (raw as unknown[])
.slice(0, MAX_SETTINGS)
.map(toSettingDef)
.filter((def): def is SettingDef => def !== null);
}
/**
* Catalog text of a key, or the fallback when the catalog lacks it.
*
* @param key - the catalog key.
* @param fallback - what to show instead.
*/
function textOr(key: string, fallback: string): string {
return hasMessage(key) ? t(key) : fallback;
}
/**
* The label of a setting.
*
* @param def - the setting.
*/
export function labelOf(def: SettingDef): string {
return textOr(def.labelKey, def.key);
}
/**
* The description of a setting; empty when the catalog lacks it.
*
* @param def - the setting.
*/
export function descriptionOf(def: SettingDef): string {
return textOr(def.descriptionKey, "");
}
/**
* The name of a section.
*
* @param id - the section id.
*/
export function sectionLabel(id: string): string {
return textOr(`settings.section.${id}`, id);
}
/**
* The name of an enum value: `settings.<key>.value.<value>` with the value
* in camel case (`lutra-dark` → `lutraDark`), or the value itself.
*
* @param def - the setting.
* @param value - one of its values.
*/
export function valueLabel(def: SettingDef, value: string): string {
const name = value.replace(/[-_.\s]+([A-Za-z0-9])/g, (_m, c: string) => c.toUpperCase());
return textOr(`settings.${def.key}.value.${name}`, value);
}
/**
* Whether a setting matches a search: every word of the query occurs in
* its label, description, key or section name (ignoring case).
*
* @param def - the setting.
* @param query - what the user typed.
*/
export function matchesQuery(def: SettingDef, query: string): boolean {
const words = query.toLowerCase().split(/\s+/).filter((w) => w !== "");
if (words.length === 0) {
return true;
}
const haystack = [labelOf(def), descriptionOf(def), def.key, sectionLabel(def.section)]
.join("\n")
.toLowerCase();
return words.every((word) => haystack.includes(word));
}
/**
* Groups settings into sections, in the order they first appear.
*
* @param defs - the settings.
*/
export function groupSections(defs: readonly SettingDef[]): SettingSection[] {
const sections: SettingSection[] = [];
for (const def of defs) {
let section = sections.find((s) => s.id === def.section);
if (!section) {
section = { id: def.section, label: sectionLabel(def.section), settings: [] };
sections.push(section);
}
section.settings.push(def);
}
return sections;
}
/**
* Whether two setting values are equal.
*
* @param a - one value.
* @param b - the other.
*/
function sameValue(a: SettingValue | undefined, b: SettingValue | undefined): boolean {
return a === b;
}
/**
* Shortens a text for display.
*
* @param text - the text.
*/
function clip(text: string): string {
return text.length > MAX_TEXT ? `${text.slice(0, MAX_TEXT)}…` : text;
}
/** Store of the settings, their values and refused changes. */
export const useSettingsStore = defineStore("settings", () => {
/** Settings as the engine lists them; empty until loaded. */
const defs = ref<SettingDef[]>([]);
/** Effective values by key. */
const values = reactive<Record<string, SettingValue>>({});
/** Error of the last refused change, by key. */
const errors = reactive<Record<string, string>>({});
/** Why loading failed, or null. */
const loadError = ref<string | null>(null);
/** Ends the engine event subscription; set while started. */
let unsubscribe: (() => void) | null = null;
/**
* Applies what a value change means outside the dialog: the editor font
* size token.
*
* @param key - the changed key.
*/
function applyEffect(key: string): void {
if (key !== FONT_SIZE_KEY) {
return;
}
const size = values[key];
setTokenOverride(
FONT_SIZE_TOKEN,
typeof size === "number" && Number.isInteger(size) && size > 0 ? `${String(size)}px` : null,
);
}
/**
* Stores values read from the engine and applies their effects.
*
* @param raw - `{values: {key: value}}` from `settings.get`; unchecked.
*/
function storeValues(raw: unknown): void {
if (typeof raw !== "object" || raw === null) {
return;
}
const read = (raw as { values?: unknown }).values;
if (typeof read !== "object" || read === null) {
return;
}
for (const [key, value] of Object.entries(read as Record<string, unknown>)) {
values[key] = toScalar(value);
applyEffect(key);
}
}
/**
* Reads values from the engine.
*
* @param keys - keys to read; every setting when absent.
* @returns whether it worked.
*/
async function fetchValues(keys?: string[]): Promise<boolean> {
const result = await run("settings.get", keys ? { keys } : {});
if (!result.ok) {
loadError.value = result.error.message;
return false;
}
storeValues(result.value);
return true;
}
/** Loads the settings and their values; a failure is kept in `loadError`. */
async function load(): Promise<void> {
const listed = await run("settings.list");
const list = listed.ok ? toSettingDefs(listed.value) : null;
if (!list) {
loadError.value = listed.ok ? t("common.error.unexpectedResult", { command: "settings.list" }) : listed.error.message;
return;
}
defs.value = list;
if (await fetchValues()) {
loadError.value = null;
}
}
/**
* Whether a setting has its default value.
*
* @param def - the setting.
*/
function isDefault(def: SettingDef): boolean {
return sameValue(values[def.key], def.default);
}
/**
* Stores the outcome of `settings.set` or `settings.reset`.
*
* @param key - the setting.
* @param result - the command's outcome.
* @returns whether the change was accepted.
*/
function settle(
key: string,
result: { ok: true; value: unknown } | { ok: false; error: { message: string } },
): boolean {
if (!result.ok) {
errors[key] = clip(result.error.message);
return false;
}
Reflect.deleteProperty(errors, key);
const value = (result.value as { value?: unknown } | null)?.value;
if (value !== undefined) {
values[key] = toScalar(value);
applyEffect(key);
}
return true;
}
/**
* Changes a setting through `settings.set`. A refused value keeps the
* engine's message as the key's error.
*
* @param key - the setting.
* @param value - the new value.
* @returns whether the engine accepted it.
*/
async function set(key: string, value: SettingValue): Promise<boolean> {
return settle(key, await run("settings.set", { key, value }));
}
/**
* Resets a setting to its default through `settings.reset`.
*
* @param key - the setting.
* @returns whether it worked.
*/
async function reset(key: string): Promise<boolean> {
return settle(key, await run("settings.reset", { key }));
}
/**
* Records an error found before asking the engine (a number field with
* text that is no whole number).
*
* @param key - the setting.
* @param message - the error text.
*/
function setError(key: string, message: string): void {
errors[key] = message;
}
/**
* Reloads the values a `settingsChanged` event names and drops their
* errors: the value changed after them.
*
* @param event - the engine event.
*/
function onEvent(event: EngineEventPayload): void {
if (event.kind !== "settingsChanged" || !Array.isArray(event.keys)) {
return;
}
const keys = (event.keys as unknown[]).filter((k): k is string => typeof k === "string");
if (keys.length === 0) {
return;
}
for (const key of keys) {
Reflect.deleteProperty(errors, key);
}
void fetchValues(keys);
}
/** Starts following `settingsChanged` and loads the settings. Starting twice is a no-op. */
async function start(): Promise<void> {
if (unsubscribe) {
return;
}
unsubscribe = onEngineEvent(onEvent);
await load();
}
/** Stops following `settingsChanged`. */
function stop(): void {
unsubscribe?.();
unsubscribe = null;
}
return { defs, values, errors, loadError, load, isDefault, set, reset, setError, start, stop };
});

View file

@ -47,9 +47,45 @@ export function toResolvedTheme(value: unknown): ResolvedTheme | null {
return { id, dark, tokens: clean }; return { id, dark, tokens: clean };
} }
/** Token values that settings put above the theme's (`--lt-font-size-editor`). */
const overrides = new Map<string, string>();
/** The last theme's value of every token, to restore when an override ends. */
const themeTokens = new Map<string, string>();
/**
* Puts a value above a theme token, now and for every theme applied later,
* so a setting such as `editor.fontSize` survives a theme switch. `null`
* ends the override and restores the theme's value, or the injected
* style's when no theme was applied yet.
*
* @param name - the token, `--lt-…`.
* @param value - the CSS value, or null.
* @param root - the element to theme; the document element by default.
*/
export function setTokenOverride(
name: string,
value: string | null,
root: HTMLElement = document.documentElement,
): void {
if (value === null) {
overrides.delete(name);
const base = themeTokens.get(name);
if (base === undefined) {
root.style.removeProperty(name);
} else {
root.style.setProperty(name, base);
}
return;
}
overrides.set(name, value);
root.style.setProperty(name, value);
}
/** /**
* Applies a theme: writes its tokens onto the root element's inline style * Applies a theme: writes its tokens onto the root element's inline style
* (which wins over the injected `<style id="lt-theme">`), sets * (which wins over the injected `<style id="lt-theme">`), keeping the
* values of {@link setTokenOverride}, sets
* `color-scheme` and records the id in `data-theme`. * `color-scheme` and records the id in `data-theme`.
* *
* @param theme - the theme. * @param theme - the theme.
@ -57,7 +93,8 @@ export function toResolvedTheme(value: unknown): ResolvedTheme | null {
*/ */
export function applyTheme(theme: ResolvedTheme, root: HTMLElement = document.documentElement): void { export function applyTheme(theme: ResolvedTheme, root: HTMLElement = document.documentElement): void {
for (const [name, value] of Object.entries(theme.tokens)) { for (const [name, value] of Object.entries(theme.tokens)) {
root.style.setProperty(name, value); themeTokens.set(name, value);
root.style.setProperty(name, overrides.get(name) ?? value);
} }
root.style.colorScheme = theme.dark ? "dark" : "light"; root.style.colorScheme = theme.dark ? "dark" : "light";
root.dataset.theme = theme.id; root.dataset.theme = theme.id;

View file

@ -40,7 +40,9 @@ const usedKeys = sourceFiles(SRC).flatMap((file) =>
/** /**
* Keys the source never passes to `t` literally because they arrive at * Keys the source never passes to `t` literally because they arrive at
* runtime: theme labels from `theme.list`, the `messageKey` of * runtime: theme labels from `theme.list`, the settings' `labelKey`,
* `descriptionKey`, section names and enum value names from
* `settings.list`, the `messageKey` of
* `notification` events (engine and desktop host), and the keys the * `notification` events (engine and desktop host), and the keys the
* notifications store passes through a constant. * notifications store passes through a constant.
*/ */
@ -57,6 +59,18 @@ const RUNTIME_KEYS = new Set([
"notification.settings.unavailable", "notification.settings.unavailable",
"notification.vfs.pumpFailed", "notification.vfs.pumpFailed",
"notification.watch.failed", "notification.watch.failed",
"settings.appearance.theme.description",
"settings.appearance.theme.label",
"settings.appearance.theme.value.lutraDark",
"settings.appearance.theme.value.lutraLight",
"settings.appearance.theme.value.system",
"settings.editor.fontSize.description",
"settings.editor.fontSize.label",
"settings.section.appearance",
"settings.section.editor",
"settings.ui.language.description",
"settings.ui.language.label",
"settings.ui.language.value.en",
"theme.lutraDark", "theme.lutraDark",
"theme.lutraLight", "theme.lutraLight",
]); ]);
@ -108,7 +122,7 @@ describe("en.json", () => {
it("uses flat dotted keys of known areas with string values", () => { it("uses flat dotted keys of known areas with string values", () => {
for (const [key, value] of Object.entries(en)) { for (const [key, value] of Object.entries(en)) {
expect(key).toMatch( expect(key).toMatch(
/^(app|command|project|editor|common|palette|theme|recovery|notification)\.[A-Za-z0-9]+(\.[A-Za-z0-9]+)*$/, /^(app|command|project|editor|common|palette|theme|recovery|notification|settings)\.[A-Za-z0-9]+(\.[A-Za-z0-9]+)*$/,
); );
expect(typeof value).toBe("string"); expect(typeof value).toBe("string");
expect(value.trim()).not.toBe(""); expect(value.trim()).not.toBe("");

View file

@ -0,0 +1,453 @@
/**
* Tests of the settings store and dialog: opening through `settings.open`
* (`Mod+,`), rendering from a mocked `settings.list` (sections, controls by
* type, catalog labels), search, changes through `settings.set`, inline
* errors (refused here and by the engine), reset, live updates on
* `settingsChanged`, the editor font size token, focus trap and Escape.
* The engine is a fake behind the mocked Tauri `invoke` and `listen`.
*/
import { flushPromises, mount, type VueWrapper } from "@vue/test-utils";
import { createPinia, setActivePinia, type Pinia } from "pinia";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { defineComponent, h } from "vue";
const invoke = vi.hoisted(() => vi.fn());
const listen = vi.hoisted(() => vi.fn());
vi.mock("@tauri-apps/api/core", () => ({ invoke }));
vi.mock("@tauri-apps/api/event", () => ({ listen }));
import { useCommandsStore } from "../../src/commands/store";
import SettingsDialog from "../../src/components/settings/SettingsDialog.vue";
import {
FONT_SIZE_TOKEN,
matchesQuery,
toSettingDefs,
useSettingsStore,
valueLabel,
type SettingDef,
} from "../../src/stores/settings";
import { applyTheme, setTokenOverride } from "../../src/theme";
/** What the fake engine's `settings.list` returns. */
const LIST = [
{
key: "appearance.theme",
type: "enum",
default: "system",
enumValues: ["lutra-dark", "lutra-light", "system"],
labelKey: "settings.appearance.theme.label",
descriptionKey: "settings.appearance.theme.description",
section: "appearance",
},
{
key: "editor.fontSize",
type: "int",
default: 14,
min: 8,
max: 48,
labelKey: "settings.editor.fontSize.label",
descriptionKey: "settings.editor.fontSize.description",
section: "editor",
},
{
key: "ui.language",
type: "enum",
default: "en",
enumValues: ["en"],
labelKey: "settings.ui.language.label",
descriptionKey: "settings.ui.language.description",
section: "appearance",
},
{
key: "editor.softWrap",
type: "bool",
default: false,
labelKey: "settings.editor.softWrap.label",
descriptionKey: "settings.editor.softWrap.description",
section: "editor",
},
];
/** The fake engine's values. */
let values: Record<string, unknown>;
/** Every `engine_execute` call, in order. */
let calls: { command: string; params: unknown }[];
/** Commands that fail, with their error. */
let failing: Map<string, { code: string; message: string }>;
/** The engine event callbacks, one per subscription. */
let listeners: ((payload: unknown) => void)[];
/** Pinia of the current test. */
let pinia: Pinia;
/** Mounted components, unmounted after each test. */
let mounted: VueWrapper[];
/**
* Sends an engine event to every subscriber.
*
* @param payload - the event.
*/
async function emit(payload: unknown): Promise<void> {
for (const listener of listeners) {
listener(payload);
}
await flushPromises();
}
/**
* An error as the shell rejects with: an `Error` carrying `code` and `message`.
*
* @param code - the error code.
* @param message - the message.
*/
function engineError(code: string, message: string): Error {
return Object.assign(new Error(message), { code, message });
}
/**
* The fake engine's answer to a command.
*
* @param command - the command id.
* @param params - its params.
*/
function answer(command: string, params: Record<string, unknown>): unknown {
const def = LIST.find((d) => d.key === params.key);
switch (command) {
case "settings.list":
return LIST;
case "settings.get": {
const keys = Array.isArray(params.keys) ? (params.keys as string[]) : Object.keys(values);
return { values: Object.fromEntries(keys.map((k) => [k, values[k]])) };
}
case "settings.set":
if (def?.type === "int" && (typeof params.value !== "number" || params.value < 8 || params.value > 48)) {
throw engineError("invalid_params", "editor.fontSize: expected an integer from 8 to 48");
}
values[params.key as string] = params.value;
return { value: params.value };
case "settings.reset":
values[params.key as string] = def?.default;
return { value: def?.default };
default:
return null;
}
}
/** A focusable button standing in for the editor. */
const Host = defineComponent({
setup: () => () => h("button", { id: "host-button" }, "host"),
});
/** Mounts the dialog next to a focusable button and starts the stores. */
async function mountDialog(): Promise<VueWrapper> {
const host = mount(Host, { attachTo: document.body });
const wrapper = mount(SettingsDialog, { attachTo: document.body, global: { plugins: [pinia] } });
mounted.push(host, wrapper);
await useCommandsStore(pinia).start();
await useSettingsStore(pinia).start();
await flushPromises();
return wrapper;
}
/**
* Presses a key on the focused element (or the body).
*
* @param init - key event properties.
*/
async function press(init: KeyboardEventInit): Promise<void> {
const target = document.activeElement ?? document.body;
target.dispatchEvent(new KeyboardEvent("keydown", { bubbles: true, cancelable: true, ...init }));
await flushPromises();
}
/**
* Opens the dialog with `Ctrl+,`.
*
* @param wrapper - the dialog.
*/
async function open(wrapper: VueWrapper): Promise<void> {
document.getElementById("host-button")?.focus();
await press({ key: ",", code: "Comma", ctrlKey: true });
await wrapper.vm.$nextTick();
}
/**
* The keys of the shown settings, in order.
*
* @param wrapper - the dialog.
*/
function rows(wrapper: VueWrapper): string[] {
return wrapper.findAll("[data-test=settings-row]").map((row) => row.attributes("data-key") ?? "");
}
/**
* A setting's row.
*
* @param wrapper - the dialog.
* @param key - the setting.
*/
function row(wrapper: VueWrapper, key: string) {
return wrapper.find(`[data-test=settings-row][data-key="${key}"]`);
}
beforeEach(() => {
pinia = createPinia();
setActivePinia(pinia);
values = { "appearance.theme": "system", "editor.fontSize": 14, "ui.language": "en", "editor.softWrap": false };
calls = [];
failing = new Map();
listeners = [];
mounted = [];
document.documentElement.removeAttribute("style");
listen.mockReset();
listen.mockImplementation((_name: string, callback: (event: { payload: unknown }) => void) => {
listeners.push((payload) => {
callback({ payload });
});
return Promise.resolve(() => undefined);
});
invoke.mockReset();
invoke.mockImplementation((cmd: string, args?: { command: string; params: Record<string, unknown> }) => {
if (cmd === "engine_list_commands") {
return Promise.resolve([]);
}
if (cmd === "engine_execute" && args) {
calls.push({ command: args.command, params: args.params });
const error = failing.get(args.command);
if (error) {
return Promise.reject(engineError(error.code, error.message));
}
try {
return Promise.resolve(answer(args.command, args.params));
} catch (reason: unknown) {
return Promise.reject(reason instanceof Error ? reason : new Error(String(reason)));
}
}
return Promise.resolve(null);
});
});
afterEach(() => {
useCommandsStore(pinia).stop();
useSettingsStore(pinia).stop();
for (const wrapper of mounted) {
wrapper.unmount();
}
setTokenOverride(FONT_SIZE_TOKEN, null);
});
describe("settings helpers", () => {
it("reads settings.list defensively", () => {
expect(toSettingDefs("nope")).toBeNull();
const defs = toSettingDefs([...LIST, null, { key: 1 }, { ...LIST[0], type: "color" }, { ...LIST[0], enumValues: [] }]);
expect(defs?.map((d) => d.key)).toEqual(["appearance.theme", "editor.fontSize", "ui.language", "editor.softWrap"]);
expect(defs?.[1]).toMatchObject({ min: 8, max: 48, enumValues: [] });
});
it("matches label, description, key and section, every word", () => {
const [theme, size] = toSettingDefs(LIST) as SettingDef[];
expect(matchesQuery(size as SettingDef, "font")).toBe(true);
expect(matchesQuery(size as SettingDef, "PIXELS")).toBe(true);
expect(matchesQuery(size as SettingDef, "editor.fontsize")).toBe(true);
expect(matchesQuery(theme as SettingDef, "appearance")).toBe(true);
expect(matchesQuery(theme as SettingDef, "colours system")).toBe(true);
expect(matchesQuery(theme as SettingDef, "colours font")).toBe(false);
});
it("names enum values from the catalog, else the value", () => {
const [theme] = toSettingDefs(LIST) as SettingDef[];
expect(valueLabel(theme as SettingDef, "lutra-dark")).toBe("Lutra Dark");
expect(valueLabel(theme as SettingDef, "system")).toBe("Same as system");
expect(valueLabel(theme as SettingDef, "solarized")).toBe("solarized");
});
});
describe("settings dialog", () => {
it("is disabled until mounted and opens with Mod+, built from settings.list", async () => {
expect(useCommandsStore(pinia).isEnabled("settings.open")).toBe(false);
const wrapper = await mountDialog();
expect(useCommandsStore(pinia).isEnabled("settings.open")).toBe(true);
expect(wrapper.find("[data-test=settings]").exists()).toBe(false);
await open(wrapper);
expect(wrapper.find("[role=dialog]").attributes("aria-modal")).toBe("true");
expect(document.activeElement).toBe(wrapper.find("[data-test=settings-search]").element);
expect(wrapper.findAll("[data-test=settings-section]").map((s) => s.text())).toEqual(["Appearance", "Editor"]);
expect(rows(wrapper)).toEqual(["appearance.theme", "ui.language"]);
const theme = row(wrapper, "appearance.theme");
expect(theme.find("label").text()).toBe("Theme");
expect(theme.find("select").findAll("option").map((o) => o.text())).toEqual([
"Lutra Dark",
"Lutra Light",
"Same as system",
]);
expect((theme.find("select").element as HTMLSelectElement).value).toBe("system");
expect(theme.find("[data-test=settings-reset]").attributes("disabled")).toBeDefined();
await wrapper.find("[data-section=editor]").trigger("click");
expect(rows(wrapper)).toEqual(["editor.fontSize", "editor.softWrap"]);
const size = row(wrapper, "editor.fontSize").find("input");
expect(size.attributes()).toMatchObject({ type: "number", min: "8", max: "48" });
expect((size.element as HTMLInputElement).value).toBe("14");
const wrap = row(wrapper, "editor.softWrap").find("[role=switch]");
expect(wrap.attributes("aria-checked")).toBe("false");
expect(row(wrapper, "editor.softWrap").find("label").text()).toBe("editor.softWrap");
});
it("filters by search across sections and says when nothing matches", async () => {
const wrapper = await mountDialog();
await open(wrapper);
await wrapper.find("[data-test=settings-search]").setValue("font");
expect(rows(wrapper)).toEqual(["editor.fontSize"]);
expect(wrapper.find("[data-section=appearance]").classes()).toContain("settings__section--dim");
await wrapper.find("[data-test=settings-search]").setValue("language interface");
expect(rows(wrapper)).toEqual(["ui.language"]);
await wrapper.find("[data-test=settings-search]").setValue("e");
expect(rows(wrapper)).toEqual(["appearance.theme", "ui.language", "editor.fontSize", "editor.softWrap"]);
await wrapper.find("[data-test=settings-search]").setValue("zebra");
expect(rows(wrapper)).toEqual([]);
expect(wrapper.find("[data-test=settings-empty]").text()).toBe("No settings match your search");
});
it("switches the theme at once through settings.set", async () => {
const wrapper = await mountDialog();
await open(wrapper);
await row(wrapper, "appearance.theme").find("select").setValue("lutra-light");
await flushPromises();
expect(calls.at(-1)).toEqual({ command: "settings.set", params: { key: "appearance.theme", value: "lutra-light" } });
expect(useSettingsStore(pinia).values["appearance.theme"]).toBe("lutra-light");
expect(row(wrapper, "appearance.theme").find("[data-test=settings-reset]").attributes("disabled")).toBeUndefined();
});
it("applies the font size to the editor token, above the theme", async () => {
const wrapper = await mountDialog();
const root = document.documentElement;
expect(root.style.getPropertyValue(FONT_SIZE_TOKEN)).toBe("14px");
await open(wrapper);
await wrapper.find("[data-section=editor]").trigger("click");
await row(wrapper, "editor.fontSize").find("input").setValue("18");
await flushPromises();
expect(calls.at(-1)).toEqual({ command: "settings.set", params: { key: "editor.fontSize", value: 18 } });
expect(root.style.getPropertyValue(FONT_SIZE_TOKEN)).toBe("18px");
applyTheme({ id: "lutra-light", dark: false, tokens: { [FONT_SIZE_TOKEN]: "14px", "--lt-bg": "#fff" } });
expect(root.style.getPropertyValue(FONT_SIZE_TOKEN)).toBe("18px");
expect(root.style.getPropertyValue("--lt-bg")).toBe("#fff");
setTokenOverride(FONT_SIZE_TOKEN, null);
expect(root.style.getPropertyValue(FONT_SIZE_TOKEN)).toBe("14px");
});
it("shows refused values inline and keeps the typed text", async () => {
const wrapper = await mountDialog();
await open(wrapper);
await wrapper.find("[data-section=editor]").trigger("click");
const input = () => row(wrapper, "editor.fontSize").find("input");
await input().setValue("99");
await flushPromises();
expect(calls.some((c) => c.command === "settings.set")).toBe(false);
expect(row(wrapper, "editor.fontSize").find("[data-test=settings-error]").text()).toBe(
"Enter a whole number from 8 to 48",
);
expect(input().attributes("aria-invalid")).toBe("true");
expect((input().element as HTMLInputElement).value).toBe("99");
failing.set("settings.set", { code: "failed", message: "disk full" });
await input().setValue("20");
await flushPromises();
expect(row(wrapper, "editor.fontSize").find("[data-test=settings-error]").text()).toBe("disk full");
expect(useSettingsStore(pinia).values["editor.fontSize"]).toBe(14);
failing.clear();
await input().setValue("20");
await flushPromises();
expect(row(wrapper, "editor.fontSize").find("[data-test=settings-error]").exists()).toBe(false);
expect((input().element as HTMLInputElement).value).toBe("20");
});
it("shows the engine's error for a value it refuses", async () => {
const wrapper = await mountDialog();
await open(wrapper);
await useSettingsStore(pinia).set("editor.fontSize", 2);
await wrapper.find("[data-section=editor]").trigger("click");
expect(row(wrapper, "editor.fontSize").find("[data-test=settings-error]").text()).toBe(
"editor.fontSize: expected an integer from 8 to 48",
);
});
it("resets a setting to its default", async () => {
values["editor.fontSize"] = 20;
const wrapper = await mountDialog();
await open(wrapper);
await wrapper.find("[data-section=editor]").trigger("click");
const reset = row(wrapper, "editor.fontSize").find("[data-test=settings-reset]");
expect(reset.attributes("aria-label")).toBe("Reset Editor font size to default");
await reset.trigger("click");
await flushPromises();
expect(calls.at(-1)).toEqual({ command: "settings.reset", params: { key: "editor.fontSize" } });
expect((row(wrapper, "editor.fontSize").find("input").element as HTMLInputElement).value).toBe("14");
expect(document.documentElement.style.getPropertyValue(FONT_SIZE_TOKEN)).toBe("14px");
});
it("follows settingsChanged from elsewhere while open", async () => {
const wrapper = await mountDialog();
await open(wrapper);
await wrapper.find("[data-section=editor]").trigger("click");
await row(wrapper, "editor.fontSize").find("input").setValue("99");
await flushPromises();
values["editor.fontSize"] = 22;
values["editor.softWrap"] = true;
await emit({ kind: "settingsChanged", keys: ["editor.fontSize", "editor.softWrap", 7] });
expect(calls.at(-1)).toEqual({ command: "settings.get", params: { keys: ["editor.fontSize", "editor.softWrap"] } });
expect((row(wrapper, "editor.fontSize").find("input").element as HTMLInputElement).value).toBe("22");
expect(row(wrapper, "editor.fontSize").find("[data-test=settings-error]").exists()).toBe(false);
expect(row(wrapper, "editor.softWrap").find("[role=switch]").attributes("aria-checked")).toBe("true");
expect(document.documentElement.style.getPropertyValue(FONT_SIZE_TOKEN)).toBe("22px");
await emit({ kind: "settingsChanged", keys: "nope" });
});
it("flips a switch", async () => {
const wrapper = await mountDialog();
await open(wrapper);
await wrapper.find("[data-section=editor]").trigger("click");
await row(wrapper, "editor.softWrap").find("[role=switch]").trigger("click");
await flushPromises();
expect(calls.at(-1)).toEqual({ command: "settings.set", params: { key: "editor.softWrap", value: true } });
expect(row(wrapper, "editor.softWrap").find("[role=switch]").attributes("aria-checked")).toBe("true");
});
it("traps the focus, closes with Escape and gives the focus back", async () => {
const wrapper = await mountDialog();
await open(wrapper);
const dialog = wrapper.find("[data-test=settings-dialog]").element as HTMLElement;
const reachable = [
...dialog.querySelectorAll<HTMLElement>("button:not([disabled]), input, select"),
];
const last = reachable.at(-1) as HTMLElement;
last.focus();
await press({ key: "Tab" });
expect(document.activeElement).toBe(reachable[0]);
await press({ key: "Tab", shiftKey: true });
expect(document.activeElement).toBe(last);
document.getElementById("host-button")?.focus();
expect(document.activeElement).toBe(wrapper.find("[data-test=settings-search]").element);
const above = document.createElement("div");
above.setAttribute("aria-modal", "true");
const field = document.createElement("input");
above.append(field);
document.body.append(above);
field.focus();
expect(document.activeElement).toBe(field);
above.remove();
(wrapper.find("[data-test=settings-search]").element as HTMLElement).focus();
await press({ key: "Escape" });
expect(wrapper.find("[data-test=settings]").exists()).toBe(false);
expect(document.activeElement?.id).toBe("host-button");
});
it("opens from a uiCommand event and shows a load failure", async () => {
const wrapper = await mountDialog();
failing.set("settings.list", { code: "internal", message: "boom" });
await emit({ kind: "uiCommand", id: "settings.open", params: {} });
expect(wrapper.find("[data-test=settings]").exists()).toBe(true);
expect(wrapper.find("[data-test=settings-load-error]").text()).toBe("Settings could not be loaded: boom");
await wrapper.find("[data-test=settings-close]").trigger("click");
expect(wrapper.find("[data-test=settings]").exists()).toBe(false);
});
});

View file

@ -2,7 +2,7 @@
* WCAG 2.1 contrast check of the built-in themes * WCAG 2.1 contrast check of the built-in themes
* (https://www.w3.org/TR/WCAG21/#contrast-minimum). Every token pair the * (https://www.w3.org/TR/WCAG21/#contrast-minimum). Every token pair the
* UI draws text with reaches AA: 4.5:1 for body text, 3:1 for non-text * UI draws text with reaches AA: 4.5:1 for body text, 3:1 for non-text
* marks (cursor, modified dot; WCAG 1.4.11). The themes come from * marks (cursor, modified dot, settings switch knob; WCAG 1.4.11). The themes come from
* `themes.json`, a snapshot that the Rust test `ui_snapshot_is_current` * `themes.json`, a snapshot that the Rust test `ui_snapshot_is_current`
* keeps equal to `lutra_engine::theme`. * keeps equal to `lutra_engine::theme`.
*/ */
@ -35,6 +35,8 @@ const PAIRS: [string, string, number][] = [
["editor-gutter-fg", "editor-gutter-bg", TEXT], ["editor-gutter-fg", "editor-gutter-bg", TEXT],
["editor-gutter-fg", "editor-active-line-bg", TEXT], ["editor-gutter-fg", "editor-active-line-bg", TEXT],
["editor-cursor", "editor-bg", LARGE], ["editor-cursor", "editor-bg", LARGE],
["bg", "accent", LARGE],
["fg", "editor-bg", LARGE],
["editor-cursor", "editor-active-line-bg", LARGE], ["editor-cursor", "editor-active-line-bg", LARGE],
["tab-modified", "bg", LARGE], ["tab-modified", "bg", LARGE],
["tab-modified", "tab-active-bg", LARGE], ["tab-modified", "tab-active-bg", LARGE],