From 68e86ab6eba66e5806ff1d1e3e7dc3ddabce7aec Mon Sep 17 00:00:00 2001 From: Knotty Wyvern Date: Thu, 15 Oct 2026 10:55:59 -0700 Subject: [PATCH] Add interface languages and improve themes and workspace controls for 0.1.36 --- README.md | 103 +- docs/completion.md | 2 +- docs/design-decisions.md | 20 + docs/development.md | 8 +- docs/guides/document-tools.md | 6 +- docs/guides/terminal.md | 3 + docs/guides/themes.md | 97 +- docs/installation.md | 23 +- docs/linux.md | 62 +- docs/menu-surfaces.json | 78 +- docs/plugin-names.md | 50 +- docs/plugins.md | 45 +- docs/product-scope.md | 10 +- docs/roadmap.md | 4 +- docs/ui-design.md | 7 + docs/user-guide.md | 9 +- package.json | 2 +- scripts/appearance.spec.ts | 10 +- scripts/appearanceLanguage.smoke.mjs | 125 + scripts/backgrounds.spec.ts | 4 +- scripts/buildPlugins.mjs | 4 +- scripts/customThemes.spec.ts | 118 +- scripts/externalPlugins.spec.ts | 40 + scripts/hostAppearance.smoke.mjs | 100 + scripts/i18n.spec.ts | 75 + scripts/menuConsistency.smoke.mjs | 47 +- scripts/menuSurfaceAudit.mjs | 2 +- scripts/pluginTranslation.spec.ts | 35 + scripts/workspaces.smoke.mjs | 30 +- src-tauri/Cargo.lock | 2 +- src-tauri/Cargo.toml | 4 +- src-tauri/build.rs | 2 + src-tauri/capabilities/default.json | 2 + .../autogenerated/workspace_forget.toml | 11 + .../autogenerated/workspace_read_many.toml | 11 + src-tauri/src/lib.rs | 2 + src-tauri/src/spelling.rs | 124 +- src-tauri/src/workspace.rs | 82 + src-tauri/tauri.conf.json | 2 +- src/lib/browser/Bookmarks.svelte | 1 + src/lib/browser/Browser.svelte | 85 +- src/lib/browser/Settings.svelte | 41 +- src/lib/browser/WebData.svelte | 25 +- src/lib/editor/EditorHost.svelte | 5 +- src/lib/editor/FindPanel.svelte | 27 +- src/lib/editor/LiveWriter.svelte | 7 +- src/lib/editor/WriterHost.svelte | 3 +- src/lib/editor/codeMenu.ts | 19 +- src/lib/editor/footnotes.ts | 7 +- src/lib/editor/headingFolding.ts | 5 +- src/lib/editor/imageControls.ts | 41 +- src/lib/editor/imagePreview.ts | 7 +- src/lib/editor/linkMenu.ts | 13 +- src/lib/editor/liveMarkdown.ts | 15 +- src/lib/editor/markdownMenu.ts | 49 +- src/lib/editor/noteTitle.ts | 7 +- src/lib/editor/readingMenu.ts | 9 +- src/lib/editor/spellingMenu.ts | 23 +- src/lib/editor/tableCellActions.ts | 35 +- src/lib/editor/tableControls.ts | 9 +- src/lib/editor/tableDragControls.ts | 7 +- src/lib/editor/tableSelectionControls.ts | 49 +- src/lib/editor/writerMenu.ts | 67 +- src/lib/i18n/index.ts | 40 + src/lib/i18n/messages.ts | 3464 +++++++++++++++++ src/lib/layout/BookmarksPane.svelte | 5 +- src/lib/layout/BrowserWindow.svelte | 5 +- src/lib/layout/EditorPane.svelte | 29 +- src/lib/layout/FileTree.svelte | 84 +- src/lib/layout/MarkdownView.svelte | 13 +- src/lib/layout/OutlinePane.svelte | 17 +- src/lib/layout/QuickOpen.svelte | 9 +- src/lib/layout/SearchPane.svelte | 7 +- src/lib/layout/SettingsDialog.svelte | 83 +- src/lib/layout/TabBar.svelte | 29 +- src/lib/layout/TemplateManager.svelte | 25 +- src/lib/layout/TextDialog.svelte | 3 +- src/lib/layout/TreeNode.svelte | 3 +- src/lib/layout/Workbench.svelte | 143 +- src/lib/layout/WorkspacePicker.svelte | 72 +- src/lib/plugins/PluginAccessMenu.svelte | 12 +- src/lib/plugins/PluginManager.svelte | 83 +- src/lib/plugins/PluginTools.svelte | 5 +- src/lib/plugins/access.ts | 2 +- src/lib/plugins/backgrounds.ts | 4 +- src/lib/plugins/external.ts | 1 + src/lib/plugins/externalSession.ts | 3 + src/lib/plugins/sdk.ts | 5 +- src/lib/plugins/translation.ts | 30 + src/lib/theme/AppearanceSettings.svelte | 91 +- src/lib/theme/ThemeSync.svelte | 4 +- src/lib/theme/appearance.ts | 81 +- src/lib/theme/customThemes.ts | 61 +- src/lib/theme/tokens.css | 18 +- src/lib/ui/WindowControls.svelte | 9 +- src/lib/ui/actionIcons.ts | 7 + src/lib/ui/menu.css | 2 +- src/lib/workspace/api.ts | 7 +- 98 files changed, 5499 insertions(+), 874 deletions(-) create mode 100644 scripts/appearanceLanguage.smoke.mjs create mode 100644 scripts/hostAppearance.smoke.mjs create mode 100644 scripts/i18n.spec.ts create mode 100644 scripts/pluginTranslation.spec.ts create mode 100644 src-tauri/permissions/autogenerated/workspace_forget.toml create mode 100644 src-tauri/permissions/autogenerated/workspace_read_many.toml create mode 100644 src/lib/i18n/index.ts create mode 100644 src/lib/i18n/messages.ts create mode 100644 src/lib/plugins/translation.ts diff --git a/README.md b/README.md index 4323178..73dab9c 100644 --- a/README.md +++ b/README.md @@ -6,20 +6,12 @@ RuneStone keeps a project's explanations and scripts together. Open an existing write Markdown, edit source files, and preview images without importing your documents into a service. Your files remain usable in other editors. Workspace metadata lives separately in `.runestone/`. -## What you can do - -- Write Markdown with live formatting, editable tables, images, and Mermaid diagrams. -- Switch between Writer, source editing, Read, and Split views. -- Find files, search a workspace, and resolve changes made by other tools. -- Use the bundled Browser to view web pages beside your documents. -- Install optional Terminal, Git, Project Management, Table formulas, and other plugin ZIPs. - -RuneStone is under development. Windows has local test installers, but no public download location is configured. -Linux and macOS builds remain unvalidated. Language servers, crash recovery, and restoring open tabs after restart remain planned. -Plugin features require their matching packages. See the [user guide](docs/user-guide.md) for current behavior and limits. - ## Install and start +Choose [Windows setup](#windows-installer) or [Linux setup](#linux-ubuntu-2404-lts-intelamd-64-bit). + +### Windows installer + If the maintainer supplied a Windows installer: 1. Open `RuneStone__x64-setup.exe`. @@ -30,7 +22,92 @@ If the maintainer supplied a Windows installer: The installer needs no developer tools. It downloads WebView2 if that runtime is missing. Keep workspace folders outside the application folder. -[Installation and updates](docs/installation.md) covers Windows setup and experimental Linux and macOS source setup. +[Installation and updates](docs/installation.md) covers Windows updates and experimental macOS source setup. + +### Linux: Ubuntu 24.04 LTS, Intel/AMD 64-bit + +This is an experimental source setup for an Ubuntu graphical desktop with Bash. +It installs the tools, downloads RuneStone, prepares its Browser, and opens the app. +Ubuntu 24.04 and clean-machine installation remain untested. +Ubuntu 26.04 has limited native and extracted-package checks in the [Linux validation record](docs/linux.md#release-package-validation-2026-10-15). + +The clone address below is the project's configured private network server. +You need access to that network and repository. +If it is unavailable, get a reachable RuneStone clone address from the maintainer before starting. +Replace only the address after `git clone`. + +1. Open Terminal from Ubuntu's applications menu, or press Ctrl+Alt+T. +2. Paste the complete block below into Terminal, then press Enter. + +Enter your Ubuntu password when `sudo` asks. Password characters do not appear as you type. +The block stops if a command fails. Keep the terminal open while RuneStone runs. +Downloads and the first Rust compilation can take an hour or more. +This setup creates `RuneStone` in your home folder. Use an empty destination for the first setup. +Node.js and Rust install for your account. The package command installs Linux libraries with administrator access. + +```bash +bash -o pipefail <<'RUNESTONE_SETUP' +sudo apt update || exit 1 +sudo apt install -y git curl wget file ca-certificates xz-utils \ + build-essential pkg-config libwebkit2gtk-4.1-dev libxdo-dev \ + libssl-dev libayatana-appindicator3-dev librsvg2-dev \ + libnss3 libnspr4 libasound2t64 libcups2t64 libgbm1 || exit 1 + +export NVM_DIR="$HOME/.nvm" +curl -fsSL https://raw.githubusercontent.com/nvm-sh/nvm/v0.40.8/install.sh | bash || exit 1 +. "$NVM_DIR/nvm.sh" --no-use || exit 1 +nvm install 24 || exit 1 +nvm alias default 24 || exit 1 +npm install --global pnpm@10.32.1 || exit 1 + +curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --profile minimal --default-toolchain stable || exit 1 +. "$HOME/.cargo/env" || exit 1 + +node --version || exit 1 +pnpm --version || exit 1 +rustc --version || exit 1 + +cd "$HOME" || exit 1 +git clone http://10.0.0.5:6610/kwyvern-gitea/RuneStone.git RuneStone || exit 1 +cd RuneStone || exit 1 +pnpm install --frozen-lockfile || exit 1 +npm ci --prefix browser-runtime || exit 1 +npm --prefix browser-runtime run package || exit 1 +pnpm browser:stage || exit 1 +pnpm tauri dev || exit 1 +RUNESTONE_SETUP +``` + +3. When RuneStone opens, use the folder button to open a workspace outside the source folder. + +Close the app and press Ctrl+C in Terminal to stop the source session. +This route does not add an application-menu shortcut or install a system package. +For later launches, paste: + +```bash +. "$HOME/.nvm/nvm.sh" +. "$HOME/.cargo/env" +cd "$HOME/RuneStone" +pnpm tauri dev +``` + +For an error, stop at the failed command and use [Linux setup help](docs/linux.md#setup-help). +The [Linux guide](docs/linux.md#5-build-and-test-a-package) also covers Debian and AppImage builds after desktop checks. +Other distributions need their own dependency and native checks. + +## What you can do + +- Write Markdown with live formatting, editable tables, images, and Mermaid diagrams. +- Switch between Writer, source editing, Read, and Split views. +- Find files, search a workspace, and resolve changes made by other tools. +- Use the bundled Browser to view web pages beside your documents. +- Install optional Terminal, Git, Project Management, Table Formulas, and other plugin ZIPs. +- Open CSV spreadsheets and PDFs with their optional viewer plugins. + +RuneStone is under development. Windows has local test installers, but no public download location is configured. +Linux has limited native checks. Linux installation and macOS remain unvalidated. +Language servers, crash recovery, and restoring open tabs after restart remain planned. +Plugin features require their matching packages. See the [user guide](docs/user-guide.md) for current behavior and limits. ## Find help diff --git a/docs/completion.md b/docs/completion.md index 339e01d..38a0685 100644 --- a/docs/completion.md +++ b/docs/completion.md @@ -54,4 +54,4 @@ Surface and provider APIs are available. Automatic context-source registration, External plugins retain RuneStone's existing full-application trust level. This API does not add a permission sandbox. -See [the implementation](../src/lib/completion/contracts.ts), [host tests](../scripts/completion.spec.ts), and the [plugin trial guide](../../RuneStone_LocalAutocomplete/docs/trial-guide.md). +See [the implementation](../src/lib/completion/contracts.ts), [host tests](../scripts/completion.spec.ts), and the [plugin trial guide](../../RuneStone_Local_Autocomplete/docs/trial-guide.md). diff --git a/docs/design-decisions.md b/docs/design-decisions.md index afb3ec7..5d3a5fe 100644 --- a/docs/design-decisions.md +++ b/docs/design-decisions.md @@ -188,6 +188,10 @@ Entry status describes the record. It does not move a Kanban card to Done or rep - Modal correction: Pass the nearest dialog as the menu parent. - Prevention: Check each background choice and the list-status choice with the real host menu API, in both themes and narrow layouts. - Modal prevention: Run the settings harness with showModal to catch blocked pointer and keyboard input. +- Language occurrence: The French code menu truncated its longer action label during the language-card review on 2026-10-15. +- Language cause: A global .action-label rule forced ellipsis and prevented the shared menu label from wrapping. +- Language correction: The shared menu label explicitly resets overflow, text overflow, and white space in menu.css. +- Language prevention: The shared menu check now includes a long translated action beside a shortcut at a viewport edge. - Check: The current host and PM check reports record the results. - Evidence: output/round4-pm-report.json, output/round4-editor-menu-report.json, and output/round4-overlay-report.json. - Modal evidence: RuneStone_BG_Slideshow/tests/artifacts/settings and the card review notes. @@ -540,3 +544,19 @@ Replaced by: [UI-024](#ui-024--assertive-functional-color-by-default) strengthen - Checks: editorSurfaces.smoke.mjs checks direct corrections, keyboard activation, replacement, undo, and narrow menus in both themes. - Limits: Browser checks mock Windows spelling results. Native dictionary behavior remains a user acceptance check. + +### UI-028 — Adjustable surface transparency and fixed custom palettes + +- Type: Rule change +- Date: 2026-10-15 +- Status: Implemented for user review +- Decision source: Cards 31d8931e-9d1b-4688-bb4f-03ee727b0f8f and 90906e18-4082-445e-a6fd-3cbda4d94226. +- Previous rule: Image surfaces and menus used fixed tint percentages. Theme templates contained separate light and dark palettes. +- New rule: Appearance controls surface transparency from 0% to 100% and can make surfaces opaque. The slider uses current theme tokens. Theme templates contain one fixed palette and the current interface, prose, heading, and code font stacks. +- Reason: Users need control over image visibility and compositing. A single palette matches the selected theme without a separate mode toggle. +- Scope: Host menus, image surfaces, compatible plugin surfaces, and custom theme import and export. +- Shared implementation: appearance.ts, customThemes.ts, and the surface-opacity tokens in tokens.css. +- Compatibility: Default surface and editor tints remain 82% and 90%. Schema 1 files remain importable. +- Evidence: scripts/appearanceLanguage.smoke.mjs, scripts/customThemes.spec.ts, and the affected cards retain checks and screenshots. +- Follow-up evidence: Cards 5a56a250-b46a-4319-8f25-5f6ac4362a32, 682ad51f-66a1-477d-b02e-c1acb1c14d4e, and 97fe6f6b-5780-436e-abd8-a8135efbbe87 cover the full range, themed slider, and missing font stacks. `scripts/hostAppearance.smoke.mjs` checks the exact controls and exports. +- Limits: Browser checks use desktop mocks. Native display and user acceptance remain open. diff --git a/docs/development.md b/docs/development.md index 7d17fa0..bb0d21c 100644 --- a/docs/development.md +++ b/docs/development.md @@ -47,8 +47,8 @@ The frontend uses port 1420, and Tauri loads `http://localhost:1420`. | Change or task | Action | | --- | --- | | Svelte, TypeScript, or CSS under `src/` | Save the source file. Vite updates the interface without a Rust rebuild. | -| Feature source under `plugins/` | Run `pnpm build:plugins`, then remove the old package and install the changed ZIP through Settings. | -| Table formulas source in `../RuneStone_TableFormulas/` | Install that checkout's dependencies, then run `pnpm build:plugins` in RuneStone. Reinstall the changed ZIP through Settings. | +| Plugin source in a sibling checkout | Run its documented checks and package command, then install the changed ZIP through Settings. | +| Table Formulas source in `../RuneStone_Table_Formulas/` | Install that checkout's dependencies, then run `pnpm build:plugins` in RuneStone. Reinstall the changed ZIP through Settings. | | Rust code under `src-tauri/src/` | Save the source file. Tauri rebuilds the changed Rust code and restarts the app. | | Rust dependencies or build settings | Allow Cargo to compile the affected dependencies. These changes can take longer. | | JavaScript dependencies after a pull or branch change | Stop development, run `pnpm install --frozen-lockfile`, then start `pnpm tauri dev` again. | @@ -138,8 +138,8 @@ detected shell profile and check shell prompt integration. A browser can show the interface, but real folder access, file writes, and terminals require the desktop host. Use `pnpm tauri dev` for manual tests of those features. -Run `pnpm build:plugins` before tests that use Terminal or Table formulas. -Clone [RuneStone_TableFormulas](https://git.knottywyvern.com/kwyvern-gitea/RuneStone_TableFormulas) beside RuneStone and install its dependencies first. +Run `pnpm build:plugins` before tests that use Terminal or Table Formulas. +Clone [RuneStone_Table_Formulas](https://git.knottywyvern.com/kwyvern-gitea/RuneStone_TableFormulas) beside RuneStone and install its dependencies first. Set `RUNESTONE_TABLE_FORMULAS_ROOT` if that checkout is elsewhere. These tests load the compiled packages through the production module loader. The browser tests use the real interface with mocked desktop communication. diff --git a/docs/guides/document-tools.md b/docs/guides/document-tools.md index ec3df9f..af9ecc3 100644 --- a/docs/guides/document-tools.md +++ b/docs/guides/document-tools.md @@ -53,11 +53,11 @@ original text without deleting the new note. Row and Column submenus insert, move, duplicate, and delete at the clicked cell. Column moves keep alignment. Sorting is stable and natural (2 before 10), leaves blanks last, and keeps the header fixed. Context-menu actions and table edge buttons have matching icons. -## Calculate with Table formulas +## Calculate with Table Formulas -Install and enable the optional Table formulas plugin before using these calculations. +Install and enable the optional Table Formulas plugin before using these calculations. -Table formulas start with `=`: for example, `=B2+C2`, `=AVERAGE(B2:C2)`, +Table Formulas start with `=`: for example, `=B2+C2`, `=AVERAGE(B2:C2)`, `=SUM(B2:B10)`, or `=ROUND(B2/3, 2)`. Columns use A, B, …, AA. Row 1 is the header, so the first data row is 2. References stay inside the current table. Arithmetic supports `+`, `-`, `*`, `/`, `^`, parentheses, and postfix `%`. diff --git a/docs/guides/terminal.md b/docs/guides/terminal.md index 3ecd9e2..f958831 100644 --- a/docs/guides/terminal.md +++ b/docs/guides/terminal.md @@ -23,6 +23,9 @@ persist locally. New terminals inherit the app environment, including PATH. ## Run scripts and navigate commands +Drag across terminal text to select it. Ctrl+C copies a selection. +Without a selection, Ctrl+C sends an interrupt to the shell. Ctrl+Shift+C also copies selected text. + More terminal actions clears scrollback, runs selected editor text, or saves and runs the active script. Supported runners include Python, JavaScript, PowerShell, Bash, Ruby, Windows batch files, and executables. Their runtimes diff --git a/docs/guides/themes.md b/docs/guides/themes.md index 5a9db50..8089af1 100644 --- a/docs/guides/themes.md +++ b/docs/guides/themes.md @@ -2,70 +2,85 @@ [User guide](../user-guide.md) · [Interface design](../ui-design.md) -Open Settings → Appearance to choose RuneStone, Claude, Sakura, or an installed custom theme. -RuneStone and Claude offer light and dark appearances. Sakura uses light only. -Claude uses local Lora and Poppins fonts, with Georgia and Arial fallbacks. It does not download fonts. +Open Settings → Appearance to choose a palette or install a custom theme. +RuneStone and Claude offer separate light and dark choices in the theme menu. +Sakura uses one light appearance. Harvest Moon, Crimson Pilot, and Silver Serpent each use one dark appearance. +Named palettes include their own typography and syntax colors. Fonts use local fallback stacks without downloads. + +## Adjust transparency + +Transparent surfaces controls the tint on menus, image-backed work areas, and compatible plugin surfaces. +The amount ranges from 0% to 100%. The default is 18%. +Turn the switch off for opaque surfaces. This keeps text and icons opaque and preserves the selected palette. +The setting applies across open windows and remains after restart. ## Create a theme -1. Choose Export theme template. -2. Edit the saved JSON file in a text editor. -3. Choose Install theme and select the file. +1. Select the appearance that you want as a starting point. +2. Choose Export theme template. +3. Edit the saved JSON file in a text editor. +4. Choose Install theme and select the file. -The file must be smaller than 64 KiB. Both `light` and `dark` need `bg`, `text`, and `accent` colors. -Use hexadecimal colors with 3, 4, 6, or 8 digits. The example supplies complete surface and text colors for both modes. +The export contains one `colors` palette, including the current surface, text, accent, status, and syntax colors. +Custom themes use this fixed palette. They do not contain separate light and dark sections. +The file must be smaller than 64 KiB. The palette requires `bg`, `text`, and `accent`. +Use hexadecimal colors with 3, 4, 6, or 8 digits. ```json { - "schema": 1, + "schema": 2, "id": "harbor", "name": "Harbor", - "light": { - "bg": "#f3f6f8", - "bg-elevated": "#ffffff", - "bg-active": "#dfe9ef", - "border": "#bccdd8", - "text": "#223344", - "text-dim": "#526778", - "text-strong": "#102536", - "accent": "#14658f", - "selection": "#b5d9ef" - }, - "dark": { - "bg": "#14232e", - "bg-elevated": "#1b2d3b", - "bg-active": "#294354", - "border": "#405b6d", - "text": "#e0eaf0", - "text-dim": "#a3bac8", - "text-strong": "#f5fafc", - "accent": "#81c8ed", - "selection": "#315d77" + "colors": { + "bg": "#141414", + "bg-elevated": "#1c1c1c", + "bg-active": "#2a2a2a", + "border": "#454545", + "text": "#e6e6e6", + "text-dim": "#b0b0b0", + "text-strong": "#ffffff", + "accent": "#00c8ff", + "selection": "#264f78" } } ``` -The ID starts with a lowercase letter and permits lowercase letters, numbers, and hyphens, up to 64 characters. -The visible name permits up to 80 characters. Reinstalling the same ID replaces that theme's colors. -Unknown color keys or invalid values stop installation with an error. +The ID starts with a lowercase letter. It permits lowercase letters, numbers, and hyphens, up to 64 characters. +The visible name permits up to 80 characters. Installing the same ID replaces that theme's colors. +Unknown keys and invalid colors stop installation with an error. +Older schema 1 themes remain importable. Import uses the palette for the current appearance and saves it as one fixed palette. ## Available colors | Keys | Use | | --- | --- | -| `bg`, `bg-elevated`, `bg-active`, `border` | Surfaces, selected controls, and boundaries | +| `bg`, `bg-elevated`, `bg-active`, `border` | Surfaces and boundaries | | `text`, `text-dim`, `text-strong` | Normal, secondary, and prominent text | | `accent`, `accent-2`, `selection` | Links, accents, and editor selection | -| `error`, `warn`, `warn-hot`, `ok`, `special` | Messages and syntax colors | +| `error`, `warn`, `warn-hot`, `ok`, `special` | Status and special content | +| `syntax-parameter`, `syntax-keyword`, `syntax-local`, `syntax-static`, `syntax-instance`, `syntax-global` | Code identifiers and keywords | +| `syntax-string`, `syntax-number`, `syntax-comment`, `syntax-type`, `syntax-function` | Code values, comments, types, and functions | -Omitted optional colors use the RuneStone defaults for that appearance. -The theme file contains color values, without scripts, style rules, or plugin code. +Optional colors use the base appearance when omitted. Export includes all supported keys to make these choices explicit. +Theme files can also contain an optional `fonts` object with `ui`, `prose`, `heading`, and `mono` font stacks. +Export includes all four current stacks. For example, `"fonts": { "ui": "Segoe UI, sans-serif", "mono": "Cascadia Mono, monospace" }`. +These names use fonts installed on the device. Theme files do not install font files. +Imports without `fonts` keep the selected theme's normal font stacks. +Theme files contain colors and font stacks without scripts, style rules, or plugin code. + +## Set a background + +Choose an image in Appearance. Its layout can fill the area, fit the complete image, or retain its original size. +Choose an alignment and set the overlay from -100% to 100%. +Negative values lighten the image. Positive values darken it. +Background images remain local. Project Management can retain a separate board image. +The optional Background Slideshow plugin can temporarily replace these images. ## Share or remove a theme With a custom theme selected, Export theme template saves its current definition. -Share that JSON file with another user, who can install it through Appearance. -Remove custom theme removes the selected definition and returns to RuneStone colors. -Themes stay in this device's application preferences and apply across workspaces. +Share the JSON file with another user, who can install it through Appearance. +Remove custom theme returns to RuneStone colors. Themes remain in this device's preferences across workspaces. -Check normal text, secondary text, links, focus indicators, and selections in both appearances before sharing a theme. +Check text, links, focus, selections, and image surfaces before sharing a theme. +Keep informative text and symbols opaque. Use the [functional color requirements](../ui-color.md) when choosing colors. diff --git a/docs/installation.md b/docs/installation.md index f538e32..d4cd98e 100644 --- a/docs/installation.md +++ b/docs/installation.md @@ -5,7 +5,7 @@ | Platform | Current route | | --- | --- | | Windows 10 or 11, Intel/AMD 64-bit | Supplied local test installer | -| Linux | Experimental source setup. Native build and installation checks remain unvalidated. | +| Linux | Complete Ubuntu source commands in the README. Limited native checks exist. Installation remains experimental. | | macOS | Experimental source setup. Native build and installation checks remain unvalidated. | No public download location is configured. Get a Windows installer from the maintainer who supplied your test release. @@ -35,21 +35,14 @@ You do not need to uninstall first. Setup preserves workspace files and settings ## Try the source on Linux -This route is for developers who can diagnose an experimental build. +Start with the [complete Ubuntu 24.04 terminal commands](../README.md#linux-ubuntu-2404-lts-intelamd-64-bit) in the README. +They install Git, Node.js 24, pnpm 10, Rust, and system libraries before downloading and launching RuneStone. +The commands also package and stage the built-in Browser, which the native host needs. -1. Install Node.js 24, pnpm 10, and stable Rust. -2. Install the [Tauri system packages for your distribution](https://v2.tauri.app/start/prerequisites/#linux). -3. Download or clone RuneStone into a Linux folder. -4. Open a terminal in that folder and run the commands below. - -```sh -pnpm install --frozen-lockfile -pnpm tauri dev -``` - -Run the app inside your graphical desktop session. Do not copy Windows dependency or build folders into the Linux checkout. -The [Linux readiness guide](linux.md) contains the Debian/Ubuntu package example, desktop checks, and experimental Debian/AppImage packaging steps. -No native Linux test result is recorded yet. +Run the app inside your graphical desktop session as your ordinary user. +Keep Linux dependencies and build output separate from Windows copies. +Linux remains experimental. The [validation record](linux.md#release-package-validation-2026-10-15) describes the completed Ubuntu 26.04 checks and remaining limits. +Ubuntu 24.04 and system-wide package installation remain untested. ## Try the source on macOS diff --git a/docs/linux.md b/docs/linux.md index f68b206..88a9056 100644 --- a/docs/linux.md +++ b/docs/linux.md @@ -1,6 +1,6 @@ # Linux readiness -[Developer guide](development.md) +[Complete Ubuntu setup commands](../README.md#linux-ubuntu-2404-lts-intelamd-64-bit) · [Developer guide](development.md) Linux support is experimental. Limited native validation is recorded below; the complete desktop and installer acceptance checks remain outstanding. @@ -25,24 +25,38 @@ An Intel/AMD build does not establish ARM support. ## 2. Prepare the Linux build environment -Install Node.js 24, pnpm 10, and stable Rust on the Linux box. -Use a separate Linux checkout. Do not copy Windows `node_modules` or `src-tauri/target` folders. +Use the [complete README setup](../README.md#linux-ubuntu-2404-lts-intelamd-64-bit) for a first Ubuntu 24.04 trial. +It includes every tool installation command, source download, Browser preparation, and native launch. +Close the app and press Ctrl+C before the checks below. +Do not copy Windows `node_modules` or `src-tauri/target` folders into Linux. -Install the system packages for your distribution from [Tauri's Linux prerequisites](https://v2.tauri.app/start/prerequisites/#linux). -For Ubuntu or Debian with WebKitGTK 4.1 available, use: +The commands use the project's configured private clone address. +Source access is required. No public source-download location is configured. +The first build needs internet access for tools and dependencies. -```sh -sudo apt update -sudo apt install build-essential pkg-config curl wget file \ - libwebkit2gtk-4.1-dev libxdo-dev libssl-dev \ - libayatana-appindicator3-dev librsvg2-dev -``` +### Command sources -These commands are an Ubuntu/Debian example, not instructions for every Linux distribution. -The first Rust build and package build need internet access for dependencies and packaging tools. +The setup instructions were checked against these primary sources on October 15, 2026: + +- [Tauri Linux prerequisites](https://v2.tauri.app/start/prerequisites/#linux): native development libraries and Rust installation. +- [Node.js downloads](https://nodejs.org/en/download) and [nvm installation](https://github.com/nvm-sh/nvm#install--update-script): Node.js 24 and its per-user installer. +- [pnpm 10 installation](https://pnpm.io/10.x/installation#using-npm): the npm installation method. +- [Rust installation](https://rust-lang.github.io/rustup/installation/index.html): the Rust toolchain and account environment. +- [Ubuntu 24.04 packages](https://packages.ubuntu.com/noble/): distribution package names, including the `t64` runtime libraries. + +Browser commands come from `browser-runtime/package.json` and its packaging and staging scripts in this repository. +The README commands were reviewed on Windows. They were not executed on a clean Ubuntu 24.04 system. ## 3. Check the source and open the app +Load the account tools and enter the source folder before these checks: + +```sh +. "$HOME/.nvm/nvm.sh" +. "$HOME/.cargo/env" +cd "$HOME/RuneStone" +``` + From the Linux checkout, install the project dependencies: ```sh @@ -72,8 +86,8 @@ work around sandbox failures with `--no-sandbox` or by running RuneStone as root Test the Browser on the intended distro, including its user-namespace policy. The native host uses WebKitGTK and the Browser uses Electron; both need testing. -The full test suite needs the Table formulas package. -Clone `RuneStone_TableFormulas` beside RuneStone and install its dependencies, as described in the [plugin guide](plugins.md). +The full test suite needs the Table Formulas package. +Clone `RuneStone_Table_Formulas` beside RuneStone and install its dependencies, as described in the [plugin guide](plugins.md). Then run these checks from RuneStone: ```sh @@ -155,6 +169,22 @@ Call a distribution supported only after its native tests and package checks pas Repeat the automated checks on a Linux runner before each Linux release. No Linux automation is configured yet. Add it when the build host and target distribution are known. +## Setup help + +| Problem | Action | +| --- | --- | +| `sudo` asks for a password | Type your Ubuntu account password, then press Enter. The terminal does not show the characters. | +| Git cannot reach `10.0.0.5` | Connect to the maintainer's network, or request a reachable clone address. | +| Git requests a username or password | Use repository credentials from the maintainer. Source access is separate from your Ubuntu account. | +| `destination path 'RuneStone' already exists` | Keep that folder. For an existing checkout, use the later-launch commands in the README. | +| `node`, `pnpm`, or `cargo` is not found | Use the later-launch block to load the account environment. Check that the earlier tool installation completed. | +| A system package cannot be found | Check your Ubuntu version with `cat /etc/os-release`. This command list targets Ubuntu 24.04. | +| The Browser runtime is missing | From the source folder, repeat `npm ci --prefix browser-runtime`, then its `package` command and `pnpm browser:stage`. | +| Electron reports a sandbox or user-namespace error | Keep the sandbox enabled. Report the error and Ubuntu version to the maintainer. Do not run RuneStone as root. | +| The first build stops | Keep the first error text and failed command. Report them with your Ubuntu version and available memory/disk space. | + +Use the [validation checks](#4-complete-the-desktop-checks) after the first launch. + ## Validation record: 2026-10-14 Validated on `desk`: Ubuntu 26.04.1 LTS, x86_64, four CPUs, 7.2 GiB reported RAM, @@ -194,7 +224,7 @@ not prevent these smoke checks. No sandbox, security, swap, or permission workar was used. Existing user settings and workspaces were not used. No installer or release package was produced, versions were unchanged, and nothing -was published. Remaining work includes supplying/building `RuneStone_TableFormulas` +was published. Remaining work includes supplying/building `RuneStone_Table_Formulas` and rerunning the full source suite, completing the desktop checks above, and validating Debian/AppImage installation and lifecycle behavior on the intended target distribution. These results do not establish full Linux support. diff --git a/docs/menu-surfaces.json b/docs/menu-surfaces.json index 1d1c89b..cb9a61f 100644 --- a/docs/menu-surfaces.json +++ b/docs/menu-surfaces.json @@ -1,15 +1,15 @@ { - "date": "2026-10-14", + "date": "2026-10-15", "scope": [ "RuneStone", - "RuneStone_ProjectManagement", + "RuneStone_Project_Management", "RuneStone_Terminal", - "RuneStone_BG_Slideshow", - "RuneStone_LocalAutocomplete", + "RuneStone_Background_Slideshow", + "RuneStone_Local_Autocomplete", "RuneStone_Git", - "RuneStone_PDFViewer", - "RuneStone_TableFormulas", - "RuneStone_CSVViewer" + "RuneStone_PDF_Viewer", + "RuneStone_Table_Formulas", + "RuneStone_CSV_Viewer" ], "limits": [ "Source patterns detect known menu construction routes. Browser evidence remains a separate check.", @@ -127,7 +127,7 @@ "RuneStone/src/lib/layout/WorkspacePicker.svelte": { "counts": { "picker": 1, - "localPopup": 7 + "localPopup": 8 }, "design": "Shared rich picker; paths retain a detail row", "check": "scripts/workspaces.smoke.mjs" @@ -176,64 +176,64 @@ "design": "Shared action menu", "check": "scripts/menuConsistency.smoke.mjs" }, - "RuneStone_ProjectManagement/src/choices-ui.ts": { + "RuneStone_Project_Management/src/choices-ui.ts": { "counts": { "action": 1 }, "design": "Shared action menus and searchable picker classes; older-host fallback retained", - "check": "RuneStone_ProjectManagement/tests/menu-audit.spec.ts; tests/shared-menu.spec.ts; tests/relations-menu.spec.ts" + "check": "RuneStone_Project_Management/tests/menu-audit.spec.ts; tests/shared-menu.spec.ts; tests/relations-menu.spec.ts" }, - "RuneStone_ProjectManagement/src/details-ui.ts": { + "RuneStone_Project_Management/src/details-ui.ts": { "counts": { "picker": 1, "localPopup": 4 }, "design": "Shared action menus and searchable picker classes; older-host fallback retained", - "check": "RuneStone_ProjectManagement/tests/menu-audit.spec.ts; tests/shared-menu.spec.ts; tests/relations-menu.spec.ts" + "check": "RuneStone_Project_Management/tests/menu-audit.spec.ts; tests/shared-menu.spec.ts; tests/relations-menu.spec.ts" }, - "RuneStone_ProjectManagement/src/labels-ui.ts": { + "RuneStone_Project_Management/src/labels-ui.ts": { "counts": { "picker": 1, "localPopup": 3 }, "design": "Shared action menus and searchable picker classes; older-host fallback retained", - "check": "RuneStone_ProjectManagement/tests/menu-audit.spec.ts; tests/shared-menu.spec.ts; tests/relations-menu.spec.ts" + "check": "RuneStone_Project_Management/tests/menu-audit.spec.ts; tests/shared-menu.spec.ts; tests/relations-menu.spec.ts" }, - "RuneStone_ProjectManagement/src/preferences.ts": { + "RuneStone_Project_Management/src/preferences.ts": { "counts": { "action": 1, "nativeChoice": 1 }, "design": "Shared choice adapter; native selects hidden on current host, older-host fallback retained", - "check": "RuneStone_ProjectManagement/tests/menu-audit.spec.ts; tests/shared-menu.spec.ts; tests/relations-menu.spec.ts" + "check": "RuneStone_Project_Management/tests/menu-audit.spec.ts; tests/shared-menu.spec.ts; tests/relations-menu.spec.ts" }, - "RuneStone_ProjectManagement/src/priority-ui.ts": { + "RuneStone_Project_Management/src/priority-ui.ts": { "counts": { "action": 1, "picker": 1, "localPopup": 3 }, "design": "Shared action menus and searchable picker classes; older-host fallback retained", - "check": "RuneStone_ProjectManagement/tests/menu-audit.spec.ts; tests/shared-menu.spec.ts; tests/relations-menu.spec.ts" + "check": "RuneStone_Project_Management/tests/menu-audit.spec.ts; tests/shared-menu.spec.ts; tests/relations-menu.spec.ts" }, - "RuneStone_ProjectManagement/src/relations-ui.ts": { + "RuneStone_Project_Management/src/relations-ui.ts": { "counts": { "nativeChoice": 1, "picker": 1, "localPopup": 5 }, "design": "Shared relationship choice and direct searchable picker rows; older-host choice fallback retained", - "check": "RuneStone_ProjectManagement/tests/relations-menu.spec.ts; tests/menu-audit.spec.ts; tests/related-cards.spec.ts" + "check": "RuneStone_Project_Management/tests/relations-menu.spec.ts; tests/menu-audit.spec.ts; tests/related-cards.spec.ts" }, - "RuneStone_ProjectManagement/src/tags.ts": { + "RuneStone_Project_Management/src/tags.ts": { "counts": { "picker": 2, "localPopup": 2 }, "design": "Shared action menus and searchable picker classes; older-host fallback retained", - "check": "RuneStone_ProjectManagement/tests/menu-audit.spec.ts; tests/shared-menu.spec.ts; tests/relations-menu.spec.ts" + "check": "RuneStone_Project_Management/tests/menu-audit.spec.ts; tests/shared-menu.spec.ts; tests/relations-menu.spec.ts" }, - "RuneStone_ProjectManagement/src/ui.ts": { + "RuneStone_Project_Management/src/ui.ts": { "counts": { "action": 4, "nativeChoice": 14, @@ -241,7 +241,7 @@ "localPopup": 1 }, "design": "Shared choice adapter; native selects hidden on current host, older-host fallback retained", - "check": "RuneStone_ProjectManagement/tests/menu-audit.spec.ts; tests/shared-menu.spec.ts; tests/relations-menu.spec.ts" + "check": "RuneStone_Project_Management/tests/menu-audit.spec.ts; tests/shared-menu.spec.ts; tests/relations-menu.spec.ts" }, "RuneStone_Terminal/src/TerminalDock.svelte": { "counts": { @@ -266,14 +266,14 @@ "design": "Synchronized shared action menu snapshot", "check": "RuneStone_Terminal/scripts/terminal.smoke.mjs" }, - "RuneStone_BG_Slideshow/src/contracts.ts": { + "RuneStone_Background_Slideshow/src/contracts.ts": { "counts": { "action": 1 }, "design": "API type declaration, no renderer", "check": "pnpm check" }, - "RuneStone_BG_Slideshow/src/image-settings-ui.ts": { + "RuneStone_Background_Slideshow/src/image-settings-ui.ts": { "counts": { "action": 1, "nativeChoice": 1, @@ -281,16 +281,16 @@ "localPopup": 3 }, "design": "Host action menus and shared searchable image picker; native image select only on older hosts", - "check": "RuneStone_BG_Slideshow/tests/settings.smoke.mjs" + "check": "RuneStone_Background_Slideshow/tests/settings.smoke.mjs" }, - "RuneStone_BG_Slideshow/src/settings.ts": { + "RuneStone_Background_Slideshow/src/settings.ts": { "counts": { "action": 1 }, "design": "Host action menus and shared searchable image picker; native image select only on older hosts", - "check": "RuneStone_BG_Slideshow/tests/settings.smoke.mjs" + "check": "RuneStone_Background_Slideshow/tests/settings.smoke.mjs" }, - "RuneStone_LocalAutocomplete/src/main.mjs": { + "RuneStone_Local_Autocomplete/src/main.mjs": { "counts": { "action": 1, "nativeChoice": 1 @@ -305,12 +305,22 @@ "design": "Commit history listbox, not a popup menu", "check": "Source inspection: persistent history list retains its own layout" }, - "RuneStone_CSVViewer/src/index.js": { + "RuneStone_CSV_Viewer/src/index.js": { "counts": { - "action": 1 + "action": 1, + "picker": 1, + "localPopup": 5 }, - "design": "Host action menus for columns, sorting, filter types, and operators", - "check": "RuneStone_CSVViewer/tests/browser.mjs; tests/host.mjs" + "design": "Shared action menus for sorting, filters, and header actions. Persistent searchable column visibility dialog uses rs-picker rows and shared surfaces.", + "check": "RuneStone_CSV_Viewer/tests/browser.mjs; RuneStone_CSV_Viewer/tests/host.mjs" + }, + "RuneStone/src/lib/layout/SettingsDialog.svelte": { + "counts": { + "action": 1, + "localPopup": 1 + }, + "design": "Shared action menu for interface language; settings retain ordinary controls", + "check": "scripts/appearanceLanguage.smoke.mjs; scripts/menuConsistency.smoke.mjs" } } } diff --git a/docs/plugin-names.md b/docs/plugin-names.md index 15bb578..42e306d 100644 --- a/docs/plugin-names.md +++ b/docs/plugin-names.md @@ -1,40 +1,32 @@ # Plugin names and source folders -Use these names in Settings, plugin manifests, help, and problem reports. -Use names without spaces for source folders and package metadata. +Use these display names in Settings, manifests, help, and problem reports. +Each checkout sits beside `RuneStone`, except the built-in Browser. -| Plugin name | Source folder after manual rename | Current source folder | npm package name | Stable plugin ID | -| --- | --- | --- | --- | --- | -| Browser (built in) | `RuneStone/browser-runtime` | Not applicable | `runestone-browser` | `runestone.browser` (legacy) | -| Local Autocomplete | `RuneStone_LocalAutocomplete` | `RuneStone_LocalModel` | `runestone-local-autocomplete` | `runestone.local-autocomplete` | -| Project Management | `RuneStone_ProjectManagement` | `RuneStone_PM` | `runestone-project-management` | `runestone.pm` | - -## Manual source folder changes - -The remaining plugin folder changes need care because local tools and saved project paths can depend on them. -Browser source now lives inside RuneStone and does not need a separate folder rename. -These changes remain pending. The current folders and repository URLs still use their earlier names. - -1. Close development servers and tools that use the affected plugin folders. -2. Rename each current source folder to its matching name in the table. -3. Update saved editor projects, shortcuts, task paths, and local scripts that contain the old absolute paths. -4. Update cross-project documentation links after the folders move. -5. Run the documented checks from each renamed checkout before the next build. - -Keep each plugin beside the `RuneStone` host checkout, or set `RUNESTONE_ROOT` to the host path. -The plugin build and package scripts use their own checkout or working directory and the host path. -They support both the current and intended folder names. -A local folder rename does not rename a remote repository. Keep existing remote URLs until the team changes them. +| Display name | Source folder | Stable plugin ID | +| --- | --- | --- | +| Browser (built in) | `RuneStone/browser-runtime` | `runestone.browser` (legacy) | +| Background Slideshow | `RuneStone_Background_Slideshow` | `runestone.bg-slideshow` | +| CSV Viewer | `RuneStone_CSV_Viewer` | `runestone.csv-viewer` | +| Git | `RuneStone_Git` | `runestone.git` | +| Local Autocomplete | `RuneStone_Local_Autocomplete` | `runestone.local-autocomplete` | +| PDF Viewer | `RuneStone_PDF_Viewer` | `runestone.pdf-viewer` | +| Project Management | `RuneStone_Project_Management` | `runestone.pm` | +| Table Formulas | `RuneStone_Table_Formulas` | `runestone.table-formulas` | +| Terminal | `RuneStone_Terminal` | `runestone.terminal` | ## Stable package and data names Display names describe the plugins. Stable IDs connect installed packages to their settings and saved data. The packager uses each stable plugin ID and version for the ZIP filename. -For example, Project Management keeps `runestone.pm-.zip`. -Do not rename published ZIP files or change plugin IDs as part of a display-name change. +For example, Project Management uses `runestone.pm-.zip`. +Changing capitalization does not change plugin IDs, settings, or saved workspace data. -Project Management retains `.runestone/pm/`, `runestone_pm`, and its existing preview storage key. -Existing view IDs, setting keys, and document IDs also stay unchanged. -These technical names preserve access to existing data and are not alternate product names. +Project Management retains `.runestone/pm/`, `runestone_pm`, and its preview storage key. +Existing view IDs and document IDs retain their names too. + +Local folder names can differ from remote repository names. +Keep existing remote URLs when a local checkout moves. +Set `RUNESTONE_ROOT` when a plugin's packager needs a different host checkout. The [plugin package reference](plugins.md) explains packaging and installation. diff --git a/docs/plugins.md b/docs/plugins.md index 305de11..79c9d81 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -4,18 +4,18 @@ RuneStone installs JavaScript plugins from local ZIP files and experimental Gitea release downloads. Open Settings → Plug-ins to install, enable, disable, or uninstall them. -See [plugin names and source folders](plugin-names.md) for display names, stable IDs, and pending manual folder changes. -Terminal and Table formulas use the same installed package system as all other plugins. +See [plugin names and source folders](plugin-names.md) for display names, stable IDs, and checkout locations. +Terminal and Table Formulas use the same installed package system as all other plugins. ## Build and install the feature packages -1. Clone `RuneStone_TableFormulas` beside RuneStone and run `pnpm install --frozen-lockfile` in that checkout. -2. Run `pnpm build:plugins` from the RuneStone repository root for Table formulas. +1. Clone `RuneStone_Table_Formulas` beside RuneStone and run `pnpm install --frozen-lockfile` in that checkout. +2. Run `pnpm build:plugins` from the RuneStone repository root for Table Formulas. 3. In Settings → Plug-ins, choose Install plugin ZIP. -4. Select the ZIP files in `../RuneStone_TableFormulas/releases/`, then choose Install and enable. +4. Select the ZIP files in `../RuneStone_Table_Formulas/releases/`, then choose Install and enable. -The build creates `runestone.table-formulas-0.1.0.zip`. -Table formulas is a development package in its [own repository](https://git.knottywyvern.com/kwyvern-gitea/RuneStone_TableFormulas). +The build creates `runestone.table-formulas-.zip` in that plugin's `releases/` folder. +Table Formulas is a development package in its [own repository](https://git.knottywyvern.com/kwyvern-gitea/RuneStone_TableFormulas). Set `RUNESTONE_TABLE_FORMULAS_ROOT` to use a different checkout location. That repository also supports `pnpm package:plugin`, with `RUNESTONE_ROOT` selecting the host packager. The folders beside them contain build output for inspection and tests. @@ -23,8 +23,7 @@ Use the ZIP files for installation and releases. Terminal development lives in the separate [RuneStone_Terminal repository](https://git.knottywyvern.com/kwyvern-gitea/RuneStone_Terminal). In that repository, run `pnpm install --frozen-lockfile`, then `pnpm build`. -Install `releases/runestone.terminal-0.1.0.zip` through the same plugin ZIP installer. -Version 0.1.0 marks Terminal as a development package. +Install `releases/runestone.terminal-.zip` through the same plugin ZIP installer. The local source folder is `../RuneStone_Terminal/` when both repositories share a parent directory. No plugin starts automatically in a fresh installation. @@ -298,8 +297,8 @@ The test checked the installed hashes and kept all four plugins disabled. | Plugin | Package version | | --- | --- | | Terminal | 0.1.0 | -| Table formulas | 0.1.0 | -| PDF viewer | 0.0.1 | +| Table Formulas | 0.1.0 | +| PDF Viewer | 0.0.1 | | Project management | 0.2.3 | The authenticated check of the personal Gitea server found no releases in these four repositories. @@ -345,6 +344,9 @@ export function activate(api) { | --- | --- | | `api.id` | The installed plugin ID | | `api.signal` | An abort signal triggered before shutdown | +| `api.i18n.locale` | Current interface language: `en`, `fr`, `ja`, or `zh-CN`. Optional API | +| `api.i18n.t(message, values?, catalogs?)` | Translate an explicit interface message with optional plugin catalogs and named placeholders | +| `api.i18n.subscribe(listener)` | Receive the current language immediately and subsequent changes. Returns cleanup and stops when the plugin is disabled | | `contribute(key, value)` | Register a typed terminal or table formula contribution | | `registerCommand({ id, title, run })` | Add a command to Commands in the toolbar | | `registerCommand({ category: "open", ... })` | Add a launch action to Open tab or view | @@ -365,6 +367,7 @@ export function activate(api) { | `workspace.list(path?)` | List a directory in this window's active workspace | | `workspace.listMarkdown()` | Return sorted visible Markdown paths in one native request. Optional API | | `workspace.read(path)` | Read a workspace text file | +| `workspace.readMany(paths)` | Optional batched text read. Accept at most 64 paths and return a source or error for each path | | `workspace.readBytes(path)` | Read workspace bytes as a Uint8Array, with a 64 MiB limit. Requires the binary document host update | | `workspace.readOptional(path)` | Read text, or return null when the file is absent. Added in 0.1.6 | | `workspace.create(path, contents)` | Create complete text without replacing an existing file. Added in 0.1.6 | @@ -374,9 +377,14 @@ export function activate(api) { | `settings.subscribe(listener)` | Receive saved settings changes across windows. Optional API | | `assets.read(path)` | Read package bytes as a `Uint8Array` | +Check for `workspace.readMany` before calling it. Older hosts require individual reads. +Each result contains `path` and either `source` or `error`. One failed file does not discard the remaining results. +The native batch accepts at most 64 paths and 16 MiB of combined UTF-8 text. +Workspace path checks and plugin shutdown checks apply to these reads. + Command and view IDs must be unique within their respective plugin collections. -Plugin commands can supply an optional `icon` from the view icon set. -Use the same icon for the command and its view. Older hosts can ignore this field. +Plugin commands can supply an optional `icon` from the shared action icon set in `src/lib/ui/actionIcons.ts`. +Use a recognizable action icon, such as `skip-forward` or `pause`, for each command. Older hosts can ignore this field. Sidebar views belong in the left navigation. Views with a direct navigation button do not repeat in the plugin launch menu. Plugin configuration appears in Settings under the plugin name. Register a view with `settings: true` to add its configuration page. @@ -384,6 +392,13 @@ The host mounts that view inside Settings and removes it from the launch menu. Settings loads enabled plugins so their configuration pages remain available in the separate settings window. The host calls `mount(container, context)` with `context.surface` set to `"settings"` or `"view"`. Older hosts can omit the context argument. + +The optional language API shares the language selected in General settings across plugin views and windows. +Plugins supply their own catalogs for plugin-specific text. A missing message falls back to the shared host catalog, then its English source. +For example, `api.i18n?.t('Hide column', {}, { fr: { 'Hide column': 'Masquer la colonne' } }) ?? 'Hide column'`. +Use a subscription to refresh interface labels after a language change. Dispose a view's subscription when that view closes. +Translate explicit interface text only. Keep document text, filenames, board names, IDs, and keyboard identifiers unchanged. +Existing packages retain their current language until their source adopts this API and supplies catalogs. Local Autocomplete keeps temporary reference text in its editor view because that text belongs to one window. Open Commands → Configure Local Autocomplete in that window to use reference text. @@ -448,8 +463,8 @@ The plugin must stop its mounted controls and native sessions in `onDispose` bef | `src/lib/plugins/registry.ts` / `contracts.ts` | Shared feature contributions and their types | | `src/lib/plugins/TerminalSlot.svelte` | The host element for terminal controls | | `../RuneStone_Terminal/src/` | Terminal plugin source in its own repository | -| `../RuneStone_TableFormulas/` | Table formulas source, unit tests, and package build | -| `scripts/buildPlugins.mjs` | Table formulas compilation and ZIP release in `../RuneStone_TableFormulas/releases/` | +| `../RuneStone_Table_Formulas/` | Table Formulas source, unit tests, and package build | +| `scripts/buildPlugins.mjs` | Table Formulas compilation and ZIP release in `../RuneStone_Table_Formulas/releases/` | | `scripts/packagePlugin.mjs` | Shared checks and ZIP creation for plugin authors | Run `pnpm build:plugins`, `pnpm check`, `pnpm test`, `pnpm build`, and `cargo test --manifest-path src-tauri/Cargo.toml --lib --offline`. diff --git a/docs/product-scope.md b/docs/product-scope.md index 16e6b02..49708cc 100644 --- a/docs/product-scope.md +++ b/docs/product-scope.md @@ -6,7 +6,7 @@ This reference preserves intended capabilities and design constraints. Some feat See the [interface design reference](ui-design.md) for shared controls, dimensions, and visual checks. See the [roadmap](roadmap.md) for goals and milestones, and the [user guide](user-guide.md) for current behavior and limitations. -The core stays active while installed packages supply optional Terminal and Table formulas features. +The core stays active while installed packages supply optional Terminal and Table Formulas features. External JavaScript packages can add commands and views. See the [plugin guide](plugins.md) for current boundaries. ## Workspace and files @@ -49,7 +49,7 @@ External JavaScript packages can add commands and views. See the [plugin guide]( ## Plugins -Terminal and Table formulas use the same installed package system as all other plugins. +Terminal and Table Formulas use the same installed package system as all other plugins. External JavaScript packages now support local installation, commands, views, retained settings, and removal with one confirmation. Users can enable or disable each plugin. A marketplace is outside the planned scope. Installation accepts standard ZIP packages and stores copies in the application data directory. @@ -72,14 +72,14 @@ See the [installation and removal guide](plugins.md#uninstall-with-one-confirmat - [ ] Add isolated execution and restricted permissions. - [x] Move terminal views, shortcuts, settings, and desktop API calls into an external plugin package. - [ ] Move native terminal services into a separate in-house package. -- [x] Move formula evaluation, rendered results, and help controls into an external Table formulas package. +- [x] Move formula evaluation, rendered results, and help controls into an external Table Formulas package. - [ ] Move the remaining spreadsheet operations into a separate in-house package. -- [ ] Add one Project Management plugin with connected Kanban, Gantt, and Calendar views. +- [x] Add one Project Management plugin with connected Kanban, Gantt, and Calendar views. - [ ] Add a virtual tabletop system plugin. Keep basic Markdown table editing and rendering in the core. Users must retain access to workspace files when plugins are disabled. Kanban, Gantt, and Calendar belong to one optional Project Management package with shared items. -The Project Management plugin has a separate development project. See its [design and scope](../../RuneStone_ProjectManagement/project-management.md). +The Project Management plugin has a separate development project. See its [design and scope](../../RuneStone_Project_Management/project-management.md). ### Planned plugin lineup diff --git a/docs/roadmap.md b/docs/roadmap.md index 309ec74..029bee5 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -44,7 +44,7 @@ and identify a reported code problem within the workspace. **Objective:** Support different ways of working while keeping the core editor simple. -Users can install, disable, and remove Terminal and Table formulas while retaining access to their files. +Users can install, disable, and remove Terminal and Table Formulas while retaining access to their files. Separately packaged plugins can extend that choice to planning, tabletop play, and other workflows. Users can now install local packages and remove them through one confirmation while retaining their data. Restricted permissions and the remaining spreadsheet modules are still planned. @@ -52,7 +52,7 @@ Restricted permissions and the remaining spreadsheet modules are still planned. **Milestone:** A user can enable a packaged plugin, use it with workspace files, and disable it while retaining access to those files in the core editor. -Project Management plugin planning lives in the separate [Project Management roadmap](../../RuneStone_ProjectManagement/roadmap.md). +Project Management plugin planning lives in the separate [Project Management roadmap](../../RuneStone_Project_Management/roadmap.md). ## Why this order? diff --git a/docs/ui-design.md b/docs/ui-design.md index e96e94c..ebf9c9f 100644 --- a/docs/ui-design.md +++ b/docs/ui-design.md @@ -80,6 +80,8 @@ Right opens a submenu. Left returns to its parent. Keyboard dismissal restores f Menus stay inside the viewport and scroll when their contents exceed its height. Menus use 24-pixel rows, 13-pixel text, and a borderless panel with a shadow. Menus use an 82% surface tint through `--rs-menu-bg` and `--rs-menu-active-bg`. +Appearance can adjust this tint or make surfaces opaque through `--rs-surface-opacity`. +Text and icons retain their opacity. Compatible plugins consume the same surface token. The shared action menu applies this tint to host and plugin menus, including submenus. The workspace picker shares the menu surface. Labels and icons remain opaque. See [UI-013](design-decisions.md#ui-013--translucent-menu-surfaces). @@ -99,6 +101,11 @@ The host filters the native collection before shared display or native fallback. ## Settings Settings navigation pairs icons with labels. Each settings page uses readable text and ordinary controls. +General offers the interface language. The language menu uses the shared action menu. +Custom theme templates use one fixed `colors` palette in schema 2. +Templates also include `fonts` stacks for the interface, prose, headings, and code. +The transparency amount covers 0% to 100%. Its slider uses the current theme's accent and surface tokens. +Schema 1 imports select the current appearance's palette. See [UI-028](design-decisions.md#ui-028--adjustable-surface-transparency-and-fixed-custom-palettes). Related plugin metadata and actions occupy compact rows. Controls wrap at narrow widths, and the content area scrolls. Long navigation lists must leave room for the selected page. The app work area and Project Management keep separate background images and settings in every theme. Images can be up to 50 MiB. diff --git a/docs/user-guide.md b/docs/user-guide.md index d1bb627..af587d3 100644 --- a/docs/user-guide.md +++ b/docs/user-guide.md @@ -19,6 +19,8 @@ Check its release notes if a control is missing. Use the folder button or Ctrl+O to open a folder or choose a recent workspace. The menu shows full paths and remembers the 20 most recent folders. +Use the × beside a recent workspace to remove it from this menu. +Removal keeps its files, settings, and open windows. New workspace creates a named folder without replacing an existing folder. Opening another workspace creates a new window and keeps the current window's documents and terminals. @@ -121,11 +123,16 @@ Settings searches by category. Preferences apply to all workspaces on this devic The desktop uses a separate Settings window. The browser preview uses a dialog. Settings → Appearance selects built-in colors or installs a theme. See the [appearance guide](guides/themes.md). +Settings → General → Display language selects English, French, Japanese, or Simplified Chinese for the host interface. +This setting does not translate documents, plugin-owned content, operating-system messages, or bundled Monaco controls. +Some runtime and file-operation diagnostics retain English fallback text. +Reopen a document to refresh existing editor widget tooltips after a language change. +The documentation remains in English. Settings → Plug-ins installs local ZIPs or experimental Gitea release links. Use the [plugin guide](plugins.md#install-a-plugin) for installation, access, and removal details. No optional plugin starts automatically in a fresh installation. Enable choices persist across restarts and windows. -Disabling Terminal ends its sessions. Disabling Table formulas preserves formulas and basic table editing. +Disabling Terminal ends its sessions. Disabling Table Formulas preserves formulas and basic table editing. Uninstall removes the installed package after confirmation and retains its settings and workspace documents. ## Keyboard reference diff --git a/package.json b/package.json index 2c9d2f2..8010d53 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "runestone", - "version": "0.1.34", + "version": "0.1.36", "description": "Desktop editor for a local workspace", "type": "module", "scripts": { diff --git a/scripts/appearance.spec.ts b/scripts/appearance.spec.ts index 07e8b4f..b21bd49 100644 --- a/scripts/appearance.spec.ts +++ b/scripts/appearance.spec.ts @@ -47,7 +47,7 @@ test('Character palettes restore one appearance and export readable surfaces and const exported = exportAppearanceTheme(theme); for (const mode of ['light', 'dark'] as const) { assert.deepEqual(parseAppearance(JSON.stringify({ theme, mode })), { theme, mode: CHARACTER_THEMES[theme].mode }); - const colors = exported[mode]; + const colors = exported.colors; for (const foreground of ['text', 'text-dim', 'text-strong', 'accent'] as const) { for (const background of ['bg', 'bg-elevated', 'bg-active', 'selection'] as const) { if (foreground === 'accent' && background === 'selection') continue; @@ -56,15 +56,15 @@ test('Character palettes restore one appearance and export readable surfaces and } } assert.deepEqual(themeModes(theme), [CHARACTER_THEMES[theme].mode]); - assert.deepEqual(exported.light, exported.dark); + assert.equal(exported.schema, 2); assert.deepEqual(parseCustomTheme(exported), exported); for (const role of SYNTAX_ROLES) { for (const background of ['bg', 'bg-active'] as const) { - assert(contrast(exported.light[`syntax-${role}`]!, exported.light[background]!) >= 4.5, `${theme}: ${role} on ${background}`); + assert(contrast(exported.colors[`syntax-${role}`]!, exported.colors[background]!) >= 4.5, `${theme}: ${role} on ${background}`); } } - assert(new Set(SYNTAX_ROLES.map(role => exported.light[`syntax-${role}`])).size >= 7); - assert.notDeepEqual(exported.dark, exportAppearanceTheme('default').dark); + assert(new Set(SYNTAX_ROLES.map(role => exported.colors[`syntax-${role}`])).size >= 7); + assert.notDeepEqual(exported.colors, exportAppearanceTheme('default').colors); } }); test('Sakura cannot restore or save a dark appearance', () => { diff --git a/scripts/appearanceLanguage.smoke.mjs b/scripts/appearanceLanguage.smoke.mjs new file mode 100644 index 0000000..6599f51 --- /dev/null +++ b/scripts/appearanceLanguage.smoke.mjs @@ -0,0 +1,125 @@ +import assert from 'node:assert/strict'; +import { mkdir } from 'node:fs/promises'; +import { createRequire } from 'node:module'; +const require = createRequire(import.meta.url); +const { chromium } = require(process.env.PLAYWRIGHT_MODULE || 'playwright'); +const origin = process.env.SMOKE_URL || 'http://127.0.0.1:1420'; +const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) }); +const errors = []; +await mkdir('.audit/appearance-language', { recursive: true }); +try { + const context = await browser.newContext({ viewport: { width: 1100, height: 800 } }); + await context.addInitScript(() => { + window.isTauri = true; + const root = "C:\\appearance-smoke"; + const files = new Map(Array.from({ length: 12 }, (_, index) => [`theme-${index}.py`, `# Theme sample ${index}\ndef sample(parameter):\n return parameter\nname = "RuneStone"\nprint(name, 42)\n`])); + const callbacks = new Map(); + let sequence = 0; + window.__TAURI_INTERNALS__ = { + metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } }, + transformCallback: callback => { const id = ++sequence; callbacks.set(id, callback); return id; }, + unregisterCallback: id => callbacks.delete(id), + invoke: async (command, args = {}) => { + if (command === "plugins_snapshot") return { root: "C:/appearance-smoke-plugins", plugins: [] }; + if (command === "workspace_last_path") return root; + if (command === "workspace_open") return { root, name: "appearance-smoke", watch_mode: "native" }; + if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("File absent"); return files.get(args.rel); } + if (command === "workspace_write") { files.set(args.rel, args.contents); return; } + if (command === "workspace_list") return [...files.keys()].filter(path => !path.startsWith(".")).map(path => ({ name: path, rel_path: path, kind: "file" })); + if (command === "workspace_search") return []; + if (command === "plugin:event|listen") return args.handler; + if (command === "plugin:window|is_maximized") return false; + return null; + }, + }; + window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} }; + }); + const settings = await context.newPage(); + const main = await context.newPage(); + for (const page of [settings, main]) { page.on('pageerror', error => errors.push(error.message)); page.setDefaultTimeout(15000); } + await main.goto(origin); + await settings.goto(`${origin}/?settingsWindow=true`); + await settings.locator('#language-picker').waitFor(); + for (const [language, name, heading, appearance, enabled, files] of [ + ['fr', 'Français', 'Paramètres', 'Apparence', 'Surfaces transparentes', 'Fichiers'], + ['ja', '日本語', '設定', '外観', '背景を透過', 'ファイル'], + ['zh-CN', '简体中文', '设置', '外观', '透明界面', '文件'], + ['en', 'English', 'Settings', 'Appearance', 'Transparent surfaces', 'Files'], + ]) { + await settings.locator('#language-picker').click(); + await settings.getByRole('menuitemradio', { name, exact: true }).click(); + await settings.getByRole('heading', { name: heading, exact: true }).waitFor(); + await main.getByRole('button', { name: files, exact: true }).waitFor(); + assert.equal(await settings.locator('html').getAttribute('lang'), language); + assert.equal(await main.locator('html').getAttribute('lang'), language); + assert.equal(await settings.evaluate(() => localStorage.getItem('runestone.language')), language); + await settings.reload(); + await settings.getByRole('heading', { name: heading, exact: true }).waitFor(); + // Arrow keys and Escape retain shared menu focus behavior. + await settings.locator('#language-picker').focus(); + await settings.keyboard.press('Enter'); + await settings.keyboard.press('End'); + await settings.keyboard.press('Home'); + await settings.keyboard.press('Escape'); + assert(await settings.locator('#language-picker').evaluate(node => node === document.activeElement)); + assert(await main.evaluate(async () => { + const { imageControls } = await import('/src/lib/editor/imageControls.ts'); + const root = document.createElement('div'); root.innerHTML = 'sample'; document.body.append(root); + let removed = false; + const cleanup = imageControls(root, { remove: () => { removed = true; } }); + root.querySelector('.md-image-frame').dispatchEvent(new KeyboardEvent('keydown', { key: 'Delete', bubbles: true })); + cleanup(); root.remove(); return removed; + }), `${language}: Delete image keyboard action`); + assert(await main.evaluate(async () => { + const { tableSelectionControls } = await import('/src/lib/editor/tableSelectionControls.ts'); + const root = document.createElement('div'); root.innerHTML = '
AB
onetwo
'; document.body.append(root); + const wrapper = root.firstElementChild, table = root.querySelector('table'); + let text = '| A | B |\n| --- | --- |\n| one | two |'; + const view = { posAtDOM: () => 0, dom: root, focus() {} }; + const controls = tableSelectionControls(root, wrapper, table, view, () => text, () => {}, next => { text = next; }, { get: () => undefined, activate() {}, editSource() {} }, {}); + controls.select({ anchor: { row: 1, column: 0 }, head: { row: 1, column: 0 } }); + wrapper.dispatchEvent(new KeyboardEvent('keydown', { key: 'Delete', bubbles: true })); + controls.destroy(); root.remove(); return !text.includes('one') && text.includes('two'); + }), `${language}: Delete selected table cell keyboard action`); + await settings.screenshot({ path: `.audit/appearance-language/${language}-general.png` }); + await main.locator('[data-tree-rel="theme-0.py"]').click(); + await main.locator('.monaco-editor textarea').waitFor(); + await main.locator('.view-lines').first().click({ button: 'right' }); + await main.locator('.rs-menu').waitFor(); + const copyLabels = { fr: 'Copier', ja: 'コピー', 'zh-CN': '复制', en: 'Copy' }; + await main.locator('.rs-menu .action-label').filter({ hasText: new RegExp('^' + copyLabels[language] + '$') }).waitFor(); + await main.screenshot({ path: `.audit/appearance-language/${language}-workbench-editor-menu.png` }); + await main.keyboard.press('Escape'); + await settings.getByRole('button', { name: appearance, exact: true }).click(); + for (const mode of ['dark', 'light']) { + await settings.evaluate(async mode => { + const appearance = await import('/src/lib/theme/appearance.ts'); + appearance.saveAppearance({ theme: 'default', mode, transparency: { enabled: true, amount: 18 } }); + window.dispatchEvent(new Event('focus')); + }, mode); + const toggle = settings.getByRole('switch', { name: enabled, exact: true }); + await toggle.uncheck(); + assert.equal(await settings.locator('html').getAttribute('data-transparency'), 'off'); + await main.waitForFunction(() => document.documentElement.dataset.transparency === 'off'); + const opacity = await settings.evaluate(() => getComputedStyle(document.documentElement).getPropertyValue('--rs-surface-opacity').trim()); + assert.equal(opacity, '100%'); + await settings.locator('.picker').first().click(); + const menu = settings.getByRole('menu'); + const bg = await menu.evaluate(node => getComputedStyle(node).backgroundColor); + assert(!bg.endsWith('/ 0.82)') && !bg.startsWith('rgba'), `Opaque menu: ${bg}`); + await settings.screenshot({ path: `.audit/appearance-language/${language}-${mode}-opaque-menu.png` }); + await settings.keyboard.press('Escape'); + await toggle.check(); + await settings.locator('#surface-transparency').fill('30'); + assert.equal(await settings.evaluate(() => getComputedStyle(document.documentElement).getPropertyValue('--rs-surface-opacity').trim()), '70%'); + await settings.setViewportSize({ width: 360, height: 640 }); + await settings.locator("#surface-transparency").scrollIntoViewIfNeeded(); + assert(await settings.locator('.content').evaluate(node => node.scrollWidth <= node.clientWidth), `${language} ${mode}: narrow overflow`); + await settings.screenshot({ path: `.audit/appearance-language/${language}-${mode}-narrow.png` }); + await settings.setViewportSize({ width: 1100, height: 800 }); + } + await settings.reload(); + } + assert.deepEqual(errors, []); + console.log('PASS: 4 locales, persistence, cross-window updates, keyboard menu focus, both themes, opaque menus, transparency levels, narrow layout.'); +} finally { await browser.close(); } diff --git a/scripts/backgrounds.spec.ts b/scripts/backgrounds.spec.ts index fe83a97..0bf9d91 100644 --- a/scripts/backgrounds.spec.ts +++ b/scripts/backgrounds.spec.ts @@ -40,8 +40,8 @@ test('app override uses body properties and removes them without changing curren const owner = Symbol(); hub.set(owner, 'app', frame); assert.match(properties.get('--rs-background-image')!, /blob:http/); - assert.equal(properties.get('--rs-workarea-surface-opacity'), '82%'); - assert.equal(properties.get('--rs-workarea-plugin-bg'), 'transparent'); + assert.equal(properties.get('--rs-workarea-surface-opacity'), 'var(--rs-surface-opacity, 82%)'); + assert.equal(properties.get('--rs-workarea-plugin-bg'), 'var(--rs-transparent-plugin-bg, transparent)'); root.set('--rs-background-image', 'new saved image'); hub.set(owner, 'app', { ...frame, overlay: -0.5, size: 'contain' }); assert.match(properties.get('--rs-background-image')!, /255,255,255,0.5/); diff --git a/scripts/buildPlugins.mjs b/scripts/buildPlugins.mjs index d60549f..0aa7c90 100644 --- a/scripts/buildPlugins.mjs +++ b/scripts/buildPlugins.mjs @@ -5,12 +5,12 @@ import { fileURLToPath } from "node:url"; import { packagePlugin } from "./packagePlugin.mjs"; const root = fileURLToPath(new URL("../", import.meta.url)); -const formulasRoot = resolve(process.env.RUNESTONE_TABLE_FORMULAS_ROOT || resolve(root, "../RuneStone_TableFormulas")); +const formulasRoot = resolve(process.env.RUNESTONE_TABLE_FORMULAS_ROOT || resolve(root, "../RuneStone_Table_Formulas")); const formulasBuild = resolve(formulasRoot, "scripts/build.mjs"); try { await access(formulasBuild); } catch { - throw new Error("Clone RuneStone_TableFormulas beside RuneStone, or set RUNESTONE_TABLE_FORMULAS_ROOT. Install its dependencies before building plugins."); + throw new Error("Clone RuneStone_Table_Formulas beside RuneStone, or set RUNESTONE_TABLE_FORMULAS_ROOT. Install its dependencies before building plugins."); } execFileSync(process.execPath, [formulasBuild], { cwd: formulasRoot, stdio: "inherit" }); const formulasOutput = resolve(root, "plugin-packages/table-formulas"); diff --git a/scripts/customThemes.spec.ts b/scripts/customThemes.spec.ts index a0c0a0b..ec5d7f8 100644 --- a/scripts/customThemes.spec.ts +++ b/scripts/customThemes.spec.ts @@ -1,15 +1,111 @@ -import { test } from "node:test"; -import assert from "node:assert/strict"; -import { parseCustomTheme } from "../src/lib/theme/customThemes.ts"; - -const palette = { bg: "#123", text: "#abcdef", accent: "#AABBCC" }; -const theme = { schema: 1, id: "my-theme", name: "My theme", light: palette, dark: palette }; -test("theme files accept explicit color tokens in both appearances", () => { +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { COLOR_TOKENS, parseCustomTheme } from '../src/lib/theme/customThemes.ts'; +import { applyTransparency, normalizeAppearance, exportAppearanceTheme, BUILTIN_THEMES, themeModes } from '../src/lib/theme/appearance.ts'; +const palette = { bg: '#123', text: '#abcdef', accent: '#AABBCC' }; +const theme = { schema: 2, id: 'my-theme', name: 'My theme', colors: palette }; +test('Fixed theme palettes retain all supplied colors', () => { assert.deepEqual(parseCustomTheme(theme), theme); }); -test("theme files reject CSS injection, unknown tokens, and incomplete palettes", () => { - for (const dark of [{ ...palette, bg: "url(https://invalid.test)" }, { ...palette, position: "fixed" }, { bg: "#000" }, []]) { - assert.throws(() => parseCustomTheme({ ...theme, dark })); +test('Legacy import selects the current appearance and validates both palettes', () => { + const light = { ...palette, bg: '#fff' }; + const legacy = { schema: 1, id: theme.id, name: theme.name, light, dark: palette }; + assert.deepEqual(parseCustomTheme(legacy).colors, palette); + assert.deepEqual(parseCustomTheme(legacy, 'light').colors, light); + assert.throws(() => parseCustomTheme({ ...legacy, light: {} })); +}); +test('Theme files reject CSS injection, unknown tokens, and incomplete palettes', () => { + for (const colors of [{ ...palette, bg: 'url(https://invalid.test)' }, { ...palette, position: 'fixed' }, { bg: '#000' }, []]) { + assert.throws(() => parseCustomTheme({ ...theme, colors })); } - assert.throws(() => parseCustomTheme({ ...theme, id: "../unsafe" })); + assert.throws(() => parseCustomTheme({ ...theme, id: '../unsafe' })); +}); +test('Every built-in template contains every current color token and one palette', () => { + for (const item of BUILTIN_THEMES) for (const mode of themeModes(item.id)) { + const exported = exportAppearanceTheme(item.id, mode); + assert.deepEqual(Object.keys(exported.colors).sort(), [...COLOR_TOKENS].sort()); + assert.deepEqual(parseCustomTheme(exported), exported); + assert.equal('light' in exported, false); + assert.equal('dark' in exported, false); + } + assert.notDeepEqual(exportAppearanceTheme('default', 'light').colors, exportAppearanceTheme('default', 'dark').colors); +}); +test('Transparency normalizes old, invalid, and extreme saved values', () => { + assert.equal(normalizeAppearance(null).transparency, undefined); + assert.deepEqual(normalizeAppearance({ transparency: { enabled: false, amount: 27 } }).transparency, { enabled: false, amount: 27 }); + for (const [amount, expected] of [[-10, 0], [55, 55], [100, 100], [120, 100], [NaN, 18], [Infinity, 18], [12.8, 13]]) { + assert.equal(normalizeAppearance({ transparency: { amount } }).transparency?.amount, expected); + } +}); + +test('Theme font roles round-trip and reject CSS injection', () => { + const fonts = { ui: 'Arial, sans-serif', prose: '"Times New Roman", serif', heading: 'Georgia, serif', mono: 'Consolas, monospace' }; + assert.deepEqual(parseCustomTheme({ ...theme, fonts }).fonts, fonts); + for (const fonts of [{ ui: 'url(https://example.test)' }, { ui: 'Arial; color: red' }, { unknown: 'Arial' }, { ui: '' }, { ui: 'Arial,,serif' }, { ui: '"Arial' }, []]) { + assert.throws(() => parseCustomTheme({ ...theme, fonts })); + } + for (const item of BUILTIN_THEMES) { + const exported = exportAppearanceTheme(item.id); + assert.deepEqual(Object.keys(exported.fonts!).sort(), ['heading', 'mono', 'prose', 'ui']); + assert.deepEqual(parseCustomTheme(exported), exported); + } + assert.match(exportAppearanceTheme('claude').fonts!.heading!, /Poppins/); + assert.match(exportAppearanceTheme('harvest-moon').fonts!.ui!, /Candara/); +}); + +test('Full transparency range produces valid surface opacity values', () => { + const values = new Map(); + const root = { dataset: {}, style: { setProperty: (key: string, value: string) => values.set(key, value) } } as unknown as HTMLElement; + for (const amount of [0, 18, 40, 55, 99, 100]) { + applyTransparency({ enabled: true, amount }, root); + assert.equal(values.get('--rs-surface-opacity'), `${100 - amount}%`); + for (const key of ['--rs-surface-opacity', '--rs-editor-surface-opacity', '--rs-hover-surface-opacity']) { + const opacity = parseFloat(values.get(key)!); + assert(opacity >= 0 && opacity <= 100); + } + } +}); +test('Opaque mode removes surface transparency and retains the amount for re-enabling', () => { + const values = new Map(); + const root = { dataset: {} as Record, style: { setProperty: (key: string, value: string) => values.set(key, value) } } as unknown as HTMLElement; + applyTransparency({ enabled: false, amount: 32 }, root); + assert.equal(values.get('--rs-surface-opacity'), '100%'); + assert.equal(values.get('--rs-editor-surface-opacity'), '100%'); + assert.equal(values.get('--rs-transparent-plugin-bg'), 'var(--rs-bg)'); + assert.equal(root.dataset.transparency, 'off'); + applyTransparency({ enabled: true, amount: 18 }, root); + assert.equal(values.get('--rs-surface-opacity'), '82%'); + assert.equal(values.get('--rs-editor-surface-opacity'), '90%'); + assert.equal(root.dataset.transparency, 'on'); +}); + +test('Saved legacy light themes migrate once and preserve both original palettes', async () => { + const { customThemes, CUSTOM_THEMES_KEY } = await import('../src/lib/theme/customThemes.ts'); + const legacy = { schema: 1, id: 'saved-light', name: 'Saved light', light: { ...palette, bg: '#fff' }, dark: { ...palette, bg: '#111' } }; + const stored = new Map([[CUSTOM_THEMES_KEY, JSON.stringify([legacy])], ['runestone.appearance', JSON.stringify({ theme: 'custom:saved-light', mode: 'light' })]]); + const previous = globalThis.localStorage; + try { + globalThis.localStorage = { getItem: (key: string) => stored.get(key) ?? null, setItem: (key: string, value: string) => stored.set(key, value) } as Storage; + assert.deepEqual(customThemes()[0].colors, legacy.light); + assert.deepEqual(themeModes('custom:saved-light'), ['light']); + assert.equal(normalizeAppearance({ theme: 'custom:saved-light', mode: 'dark' }).mode, 'light'); + assert.deepEqual(exportAppearanceTheme('custom:saved-light').colors.bg, '#fff'); + assert.equal(JSON.parse(stored.get(CUSTOM_THEMES_KEY)!)[0].schema, 2); + assert.deepEqual(JSON.parse(stored.get(`${CUSTOM_THEMES_KEY}.legacy`)!)[0], legacy); + assert.deepEqual(customThemes('dark')[0].colors, legacy.light); + } finally { globalThis.localStorage = previous; } +}); + +test('Legacy migration storage failure leaves the original palette available', async () => { + const { customThemes, CUSTOM_THEMES_KEY } = await import('../src/lib/theme/customThemes.ts'); + const legacy = { schema: 1, id: 'quota-light', name: 'Quota light', light: { ...palette, bg: '#fefefe' }, dark: palette }; + const raw = JSON.stringify([legacy]); + const previous = globalThis.localStorage; + let original = raw; + try { + globalThis.localStorage = { getItem: (key: string) => key === CUSTOM_THEMES_KEY ? original : null, setItem: () => { throw new Error('Quota exceeded'); } } as unknown as Storage; + assert.deepEqual(customThemes('light')[0].colors, legacy.light); + assert.equal(original, raw); + assert.deepEqual(customThemes('dark')[0].colors, legacy.light); + } finally { globalThis.localStorage = previous; } }); diff --git a/scripts/externalPlugins.spec.ts b/scripts/externalPlugins.spec.ts index 4cda00f..07c2071 100644 --- a/scripts/externalPlugins.spec.ts +++ b/scripts/externalPlugins.spec.ts @@ -2,6 +2,7 @@ import test from "node:test"; import assert from "node:assert/strict"; import { ExternalSession } from "../src/lib/plugins/externalSession.ts"; import type { PluginApi } from "../src/lib/plugins/sdk.ts"; +import { locale } from "../src/lib/i18n/index.ts"; function fixture() { let writes = 0; const session = new ExternalSession("org.test.demo", { @@ -12,6 +13,25 @@ function fixture() { return { session, writes: () => writes }; } +test("plugin language changes stop before cleanup and reject later access", async () => { + const { session } = fixture(); + const changes: string[] = []; + let api!: PluginApi; + try { + await session.start({ activate(value) { + api = value; + api.i18n!.subscribe(language => changes.push(language)); + api.onDispose(() => { locale.set('ja'); }); + } }); + locale.set('fr'); + assert.equal(api.i18n!.t('Settings'), 'Paramètres'); + await session.stop(); + assert.deepEqual(changes, ['en', 'fr']); + assert.throws(() => api.i18n!.t('Settings'), /disabled/); + assert.throws(() => api.i18n!.locale, /disabled/); + } finally { await session.stop(); locale.set('en'); } +}); + test("native Markdown discovery remains optional and is revoked on disable", async () => { let api!: PluginApi; let scans = 0; @@ -93,3 +113,23 @@ test("cleanup returned by late activation still blocks shutdown when it fails", await Promise.resolve(); const stopping = session.stop(); done(); await assert.rejects(starting, /Late cleanup failed/); await assert.rejects(stopping, /Late cleanup failed/); }); + +test("batch workspace reads remain optional and stop when the plugin is disabled", async () => { + let api!: PluginApi; + let calls = 0; + const rows = [{ path: "Card.md", source: "Card source" }, { path: "Missing.md", error: "File not found" }]; + const session = new ExternalSession("org.test.batch", { + workspace: { list: async () => [], read: async () => "", write: async () => {}, + readMany: async paths => { calls++; assert.deepEqual(paths, ["Card.md", "Missing.md"]); return rows; } }, + settings: { read: async () => null, write: async () => {} }, + assets: { read: async () => new Uint8Array() }, + }, () => {}, () => {}); + await session.start({ activate(value) { api = value; } }); + assert.deepEqual(await api.workspace.readMany!(["Card.md", "Missing.md"]), rows); + await session.stop(); + assert.throws(() => api.workspace.readMany!(["Card.md"]), /disabled/); + assert.equal(calls, 1); + const old = fixture().session; + await old.start({ activate(value) { assert.equal(value.workspace.readMany, undefined); } }); + await old.stop(); +}); diff --git a/scripts/hostAppearance.smoke.mjs b/scripts/hostAppearance.smoke.mjs new file mode 100644 index 0000000..825fb64 --- /dev/null +++ b/scripts/hostAppearance.smoke.mjs @@ -0,0 +1,100 @@ +import assert from 'node:assert/strict'; +import { mkdir } from 'node:fs/promises'; +import { createRequire } from 'node:module'; +const require = createRequire(import.meta.url); +const { chromium } = require(process.env.PLAYWRIGHT_MODULE || 'playwright'); +const origin = process.env.SMOKE_URL || 'http://127.0.0.1:1420'; +const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) }); +const errors = []; +await mkdir('.audit/host-ui', { recursive: true }); +try { + const context = await browser.newContext({ viewport: { width: 1100, height: 800 } }); + await context.addInitScript(() => { + window.isTauri = true; + const root = "C:\\appearance-smoke"; + const files = new Map(Array.from({ length: 12 }, (_, index) => [`theme-${index}.py`, `# Theme sample ${index}\ndef sample(parameter):\n return parameter\nname = "RuneStone"\nprint(name, 42)\n`])); + const callbacks = new Map(); + let sequence = 0; + window.__TAURI_INTERNALS__ = { + metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } }, + transformCallback: callback => { const id = ++sequence; callbacks.set(id, callback); return id; }, + unregisterCallback: id => callbacks.delete(id), + invoke: async (command, args = {}) => { + if (command === "plugins_snapshot") return { root: "C:/appearance-smoke-plugins", plugins: [] }; + if (command === "workspace_last_path") return root; + if (command === "workspace_open") return { root, name: "appearance-smoke", watch_mode: "native" }; + if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("File absent"); return files.get(args.rel); } + if (command === "workspace_write") { files.set(args.rel, args.contents); return; } + if (command === "workspace_list") return [...files.keys()].filter(path => !path.startsWith(".")).map(path => ({ name: path, rel_path: path, kind: "file" })); + if (command === "workspace_search") return []; + if (command === "plugin:event|listen") return args.handler; + if (command === "plugin:window|is_maximized") return false; + return null; + }, + }; + window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} }; + }); + const page = await context.newPage(); + page.on('pageerror', error => errors.push(error.message)); + await page.goto(`${origin}/?settingsWindow=true`); + await page.getByRole('button', { name: 'Appearance', exact: true }).click(); + for (const [theme, mode] of [['default','dark'],['default','light'],['claude','dark'],['claude','light'],['sakura','light'],['harvest-moon','dark'],['crimson-pilot','dark'],['silver-serpent','dark']]) { + await page.evaluate(async ({theme,mode}) => { + (await import('/src/lib/theme/appearance.ts')).saveAppearance({theme,mode,transparency:{enabled:true,amount:18}}); + window.dispatchEvent(new Event('focus')); + },{theme,mode}); + const slider = page.locator('#surface-transparency'); + await slider.fill('100'); + assert.equal(await page.evaluate(() => JSON.parse(localStorage.getItem('runestone.appearance')).transparency.amount),100); + await slider.focus(); await page.keyboard.press('Home'); assert.equal(await slider.inputValue(),'0'); + await page.keyboard.press('End'); assert.equal(await slider.inputValue(),'100'); + await page.screenshot({path:`.audit/host-ui/${theme}-${mode}-slider-focus.png`}); + await page.getByRole('switch',{name:'Transparent surfaces',exact:true}).uncheck(); + assert(await slider.isDisabled()); + await page.screenshot({path:`.audit/host-ui/${theme}-${mode}-slider-disabled.png`}); + await page.getByRole('switch',{name:'Transparent surfaces',exact:true}).check(); + await page.setViewportSize({width:360,height:740}); await slider.scrollIntoViewIfNeeded(); + assert(await page.locator('.content').evaluate(node => node.scrollWidth <= node.clientWidth)); + await page.screenshot({path:`.audit/host-ui/${theme}-${mode}-narrow.png`}); + await page.setViewportSize({width:1100,height:800}); + } + await page.evaluate(async () => { + const {installTheme} = await import('/src/lib/theme/customThemes.ts'); + const {saveAppearance,exportAppearanceTheme} = await import('/src/lib/theme/appearance.ts'); + const theme = exportAppearanceTheme('default'); theme.fonts = {ui:'Arial, sans-serif',prose:'Georgia, serif',heading:'Georgia, serif',mono:'Consolas, monospace'}; + installTheme(theme); saveAppearance({theme:'custom:my-theme',mode:'dark'}); window.dispatchEvent(new Event('focus')); + }); + assert.match(await page.locator('.preview-prose').evaluate(node => getComputedStyle(node).fontFamily),/Georgia/); + assert.match(await page.evaluate(async () => (await import('/src/lib/theme/appearance.ts')).exportAppearanceTheme('custom:my-theme').fonts.ui),/Arial/); + await page.screenshot({path:'.audit/host-ui/custom-fonts.png'}); + const main = await context.newPage(); await main.goto(origin); + await main.bringToFront(); + await main.getByRole('button',{name:'Files',exact:true}).waitFor(); + await main.evaluate(async () => { + const loaded = performance.getEntriesByType('resource').map(entry => entry.name).find(name => new URL(name).pathname === '/src/lib/plugins/external.ts'); + const {pluginTools,refreshPlugins} = await import(loaded || '/src/lib/plugins/external.ts'); + await refreshPlugins(); + const invoke = window.__TAURI_INTERNALS__.invoke; + window.__TAURI_INTERNALS__.invoke = (command,args) => command === 'plugins_snapshot' ? Promise.resolve(null) : invoke(command,args); + const commands = [{owner:'runestone.background-slideshow',id:'next-image',title:'Next background image',kind:'command',surface:'commands',icon:'skip-forward'},{owner:'runestone.background-slideshow',id:'pause-resume',title:'Pause or resume background slideshow',kind:'command',surface:'commands',icon:'pause'}]; + pluginTools.set(commands); + }); + for (const mode of ['dark','light']) { + await main.evaluate(async mode => (await import('/src/lib/theme/appearance.ts')).saveAppearance({theme:'default',mode}),mode); + const button = main.getByRole('button',{name:'Commands',exact:true}); + assert.equal(await button.getAttribute('title'),null); + await button.hover(); await main.waitForTimeout(1100); + assert.equal(await main.locator('[role=tooltip]:visible').count(),1); + await main.screenshot({path:`.audit/host-ui/${mode}-single-tooltip.png`}); + await main.keyboard.press('Escape'); assert.equal(await main.locator('[role=tooltip]:visible').count(),0); + await main.mouse.move(400,400); + await button.evaluate(node => node.blur()); + await button.focus(); await main.waitForTimeout(600); assert.equal(await main.locator('[role=tooltip]:visible').count(),1); + await button.click(); await main.getByRole('menu').waitFor(); + const paths = await main.locator('.rs-menu svg').evaluateAll(nodes => nodes.map(node => node.innerHTML)); + assert(paths.some(path => path.includes('M7 4v16'))); assert(paths.some(path => path.includes('m4 4 12 8'))); + await main.screenshot({path:`.audit/host-ui/${mode}-slideshow-command-icons.png`}); await main.keyboard.press('Escape'); + } + assert.deepEqual(errors,[]); + console.log('PASS: eight theme variants, slider endpoints, persistence, disabled states, narrow layout, font import/export, single tooltip, and command icons.'); +} finally { await browser.close(); } diff --git a/scripts/i18n.spec.ts b/scripts/i18n.spec.ts new file mode 100644 index 0000000..8b868ef --- /dev/null +++ b/scripts/i18n.spec.ts @@ -0,0 +1,75 @@ +import assert from 'node:assert/strict'; +import { test } from 'node:test'; +import { catalogs, messageRows } from '../src/lib/i18n/messages.ts'; +import { get } from 'svelte/store'; +import { LANGUAGE_KEY, locale, normalizeLocale, setLocale, t, translate, syncLocale } from '../src/lib/i18n/index.ts'; +test('Every catalog entry has all translations and preserves its placeholders', () => { + const seen = new Set(); + for (const [english, ...translations] of messageRows) { + assert(!seen.has(english), `Duplicate message: ${english}`); seen.add(english); + const placeholders = (value: string) => [...value.matchAll(/\{(\w+)\}/g)].map(match => match[1]).sort(); + for (const value of translations) { + assert(value.trim(), `Empty translation: ${english}`); + assert.deepEqual(placeholders(value), placeholders(english), english); + } + } + assert.equal(Object.keys(catalogs.fr).length, messageRows.length); +}); +test('Locale parsing rejects unsupported values and interpolation preserves user text', () => { + assert.equal(normalizeLocale('ja'), 'ja'); + assert.equal(normalizeLocale('zh-CN'), 'zh-CN'); + for (const value of [null, undefined, 'constructor', 'de', [], {}]) assert.equal(normalizeLocale(value), 'en'); + assert.equal(translate('fr', 'Missing source text'), 'Missing source text'); + assert.equal(translate('ja', 'Close {name}', { name: '' }), 'を閉じる'); +}); +test('Language saves before reactive changes and syncs across windows', () => { + const stored = new Map(); + const events = new Map(); + const priorStorage = globalThis.localStorage, priorWindow = globalThis.window, priorDocument = globalThis.document; + try { + globalThis.localStorage = { getItem: (key: string) => stored.get(key) ?? null, setItem: (key: string, value: string) => stored.set(key, value) } as Storage; + globalThis.window = { addEventListener: (key: string, handler: Function) => events.set(key, handler), removeEventListener: (key: string) => events.delete(key) } as unknown as Window & typeof globalThis; + globalThis.document = { documentElement: { lang: '' } } as unknown as Document; + const stop = syncLocale(); + setLocale('fr'); + assert.equal(stored.get(LANGUAGE_KEY), 'fr'); + assert.equal(get(t)('Settings'), 'Paramètres'); + assert.equal(document.documentElement.lang, 'fr'); + stored.set(LANGUAGE_KEY, 'zh-CN'); events.get('storage')!({ key: LANGUAGE_KEY }); + assert.equal(get(locale), 'zh-CN'); assert.equal(get(t)('Settings'), '设置'); + globalThis.localStorage.setItem = () => { throw new Error('Storage unavailable'); }; + assert.throws(() => setLocale('ja')); + assert.equal(get(locale), 'zh-CN'); + stop(); assert.equal(events.size, 0); + } finally { globalThis.localStorage = priorStorage; globalThis.window = priorWindow; globalThis.document = priorDocument; locale.set('en'); } +}); + +import { readFileSync, readdirSync } from 'node:fs'; +import path from 'node:path'; +import ts from 'typescript'; +function sourceFiles(dir: string): string[] { + return readdirSync(dir, { withFileTypes: true }).flatMap(entry => entry.isDirectory() ? sourceFiles(path.join(dir, entry.name)) : /\.(ts|svelte)$/.test(entry.name) ? [path.join(dir, entry.name)] : []); +} +test('Every static host translation call has all three catalog entries', () => { + const missing: string[] = []; + for (const file of sourceFiles('src/lib')) { + const source = readFileSync(file, 'utf8'); + for (const match of source.matchAll(/(?:\$t|\btr)\(\s*((?:"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'))/g)) { + const parsed = ts.createSourceFile('literal.ts', match[1], ts.ScriptTarget.Latest, true); + const statement = parsed.statements[0]; + const value = ts.isExpressionStatement(statement) && ts.isStringLiteral(statement.expression) ? statement.expression.text : ''; + if (value && !Object.hasOwn(catalogs.fr, value)) missing.push(`${file}: ${value}`); + } + } + assert.deepEqual(missing, []); +}); +test('Keyboard identifiers remain untranslated in event handlers', () => { + const failures: string[] = []; + for (const file of sourceFiles('src/lib')) { + const source = readFileSync(file, 'utf8'); + for (const line of source.split(/\r?\n/)) { + if (/event\.(?:key|code)\s*[!=]==?\s*(?:tr|\$t)\(/.test(line) || /(?:tr|\$t)\([^\n]+\]\.(?:includes|indexOf)\(event\.(?:key|code)/.test(line)) failures.push(`${file}: ${line.trim()}`); + } + } + assert.deepEqual(failures, []); +}); diff --git a/scripts/menuConsistency.smoke.mjs b/scripts/menuConsistency.smoke.mjs index 9330738..0f893b1 100644 --- a/scripts/menuConsistency.smoke.mjs +++ b/scripts/menuConsistency.smoke.mjs @@ -25,7 +25,10 @@ await page.addInitScript(() => { if (command === "plugin:event|listen") { listeners.set(args.event, args.handler); return ++sequence; } if (command === "plugin:event|unlisten") return; if (command.startsWith("spelling_menu_")) { window.spellingTest.commands.push({ method: command, ...args }); return; } - if (command === "spelling_suggestions") return { language: "en-US", words: [], misspelled: false }; + if (command === "spelling_suggestions") { + if (window.spellingTest.delay) return new Promise(resolve => window.spellingTest.resolve = resolve); + return { language: "en-US", words: [], misspelled: false }; + } if (command === "workspace_last_path") return root; if (command === "workspace_open") return { root, name: "tab-menu-workspace", watch_mode: "native" }; if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("missing"); return files.get(args.rel); } @@ -208,6 +211,37 @@ try { await emitSpelling("new"); assert.deepEqual(await page.evaluate(() => window.spellingTest.commands.at(-1)), { method: "spelling_menu_select", request: "old", command: null }); await dismiss(); + await page.evaluate(() => { + window.spellingTest.delay = true; + const input = document.querySelector('#native-spelling-test'); + input.value = 'recieved'; input.focus(); input.setSelectionRange(3, 3); + input.dispatchEvent(new MouseEvent('contextmenu', { bubbles: true })); + window.spellingTest.emit({ request: 'delayed-spelling', fallback_spelling: true, items: [ + { id: 90, name: 'copy', label: 'Copy', shortcut: '', kind: 0, enabled: true, checked: false, children: [] }, + ] }); + }); + await spelling.waitFor(); + assert.equal(await item('Copy').count(), 1, 'Editing actions appear before the spelling service resolves'); + await page.evaluate(() => { window.spellingTest.resolve({ language: 'en-US', words: ['received'], misspelled: true }); window.spellingTest.delay = false; }); + await item('received').waitFor(); + await page.screenshot({ path: `.audit/menu-spelling-async-${theme}.png` }); + await dismiss(); + await page.evaluate(() => { + window.spellingTest.delay = true; + document.querySelector('#native-spelling-test').dispatchEvent(new MouseEvent('contextmenu', { bubbles: true })); + window.spellingTest.emit({ request: 'dismissed-spelling', fallback_spelling: true, items: [ + { id: 91, name: 'copy', label: 'Copy', shortcut: '', kind: 0, enabled: true, checked: false, children: [] }, + ] }); + }); + await spelling.waitFor(); + await dismiss(); + await page.evaluate(async () => { + window.spellingTest.resolve({ language: 'en-US', words: ['received'], misspelled: true }); + window.spellingTest.delay = false; + await new Promise(resolve => requestAnimationFrame(resolve)); + }); + assert.equal(await spelling.count(), 0, 'Late spelling results cannot reopen a dismissed menu'); + await page.evaluate(() => { document.querySelector('#native-spelling-test').value = 'Original'; }); await page.locator("#native-spelling-test").evaluate(node => node.remove()); await page.evaluate(() => { const input = document.createElement("input"); @@ -220,6 +254,17 @@ try { assert.deepEqual(await page.evaluate(() => window.spellingTest.commands.at(-1)), { method: "spelling_menu_select", request: "ordinary-input", command: null, fallback: true }); } await page.setViewportSize({ width: 420, height: 320 }); + await page.evaluate(async () => { + const { actionMenu } = await import("/src/lib/ui/actionMenu.ts"); + const root = actionMenu(418, 318, [{ label: "Modifier toutes les occurrences dans le document", icon: "select", shortcut: "Ctrl+F2" }], () => root.remove(), "Long translated label"); + }); + const translated = menu("Long translated label"); + assert(await translated.locator('.action-label').evaluate(node => { + const css = getComputedStyle(node); + return css.whiteSpace === 'normal' && css.textOverflow !== 'ellipsis' && node.scrollWidth <= node.clientWidth; + }), 'Long translated actions wrap without truncation'); + await page.screenshot({ path: '.audit/menu-translated-long-label.png' }); + await dismiss(); await page.evaluate(async () => { const { actionMenu } = await import("/src/lib/ui/actionMenu.ts"); const root = actionMenu(418, 318, [ diff --git a/scripts/menuSurfaceAudit.mjs b/scripts/menuSurfaceAudit.mjs index fee067c..458077b 100644 --- a/scripts/menuSurfaceAudit.mjs +++ b/scripts/menuSurfaceAudit.mjs @@ -3,7 +3,7 @@ import path from 'node:path'; import { fileURLToPath } from 'node:url'; const root = fileURLToPath(new URL('../', import.meta.url)); -export const projects = ['RuneStone', 'RuneStone_ProjectManagement', 'RuneStone_Terminal', 'RuneStone_BG_Slideshow', 'RuneStone_LocalAutocomplete', 'RuneStone_Git', 'RuneStone_PDFViewer', 'RuneStone_TableFormulas', 'RuneStone_CSVViewer']; +export const projects = ['RuneStone', 'RuneStone_Project_Management', 'RuneStone_Terminal', 'RuneStone_Background_Slideshow', 'RuneStone_Local_Autocomplete', 'RuneStone_Git', 'RuneStone_PDF_Viewer', 'RuneStone_Table_Formulas', 'RuneStone_CSV_Viewer']; const patterns = { action: /\b(?:showActionMenu|actionMenu)\s*\(/g, svelteMenu: / { + const api = pluginTranslation(() => {}, () => {}); + try { + locale.set('fr'); + assert.equal(api.locale, 'fr'); + assert.equal(api.t('Settings'), 'Paramètres'); + assert.equal(api.t('Column {name}', { name: 'User data' }, { fr: { 'Column {name}': 'Colonne {name}' } }), 'Colonne User data'); + assert.equal(api.t('Unknown {name}', { name: 'text' }), 'Unknown text'); + assert.equal(api.t('constructor'), 'constructor'); + assert.equal(api.t('Settings', {}, { fr: Object.create({ Settings: 'Inherited' }) }), 'Paramètres'); + } finally { locale.set('en'); } +}); + +test('Plugin language subscriptions stop at disposal and reject access after disable', () => { + const cleanup: (() => void)[] = [], languages: string[] = []; + let stopped = false; + const api = pluginTranslation(() => { if (stopped) throw new Error('Disabled'); }, off => cleanup.push(off)); + try { + api.subscribe(language => languages.push(language)); + locale.set('ja'); + assert.deepEqual(languages, ['en', 'ja']); + stopped = true; + for (const off of cleanup) off(); + locale.set('zh-CN'); + assert.deepEqual(languages, ['en', 'ja']); + assert.throws(() => api.locale, /Disabled/); + assert.throws(() => api.t('Settings'), /Disabled/); + assert.throws(() => api.subscribe(() => {}), /Disabled/); + } finally { locale.set('en'); } +}); diff --git a/scripts/workspaces.smoke.mjs b/scripts/workspaces.smoke.mjs index 42c078d..ea21a0d 100644 --- a/scripts/workspaces.smoke.mjs +++ b/scripts/workspaces.smoke.mjs @@ -10,7 +10,7 @@ page.on("pageerror", err => errors.push(err.message)); await page.addInitScript(() => { window.isTauri = true; let current = "D:\\Notes"; - let recent = [current, "D:\\Writing\\Notes", "D:\\Missing"]; + let recent = ["D:\\Writing\\Notes", current, "D:\\Missing"]; let picked = null; let contents = "Original note"; const calls = []; @@ -22,6 +22,7 @@ await page.addInitScript(() => { calls.push({ command, args }); if (command === "workspace_last_path") return current; if (command === "workspace_recent") return recent; + if (command === "workspace_forget") { recent = recent.filter(path => path !== args.path); return recent; } if (command === "workspace_list") return args.rel ? [] : [{ name: "note.txt", rel_path: "note.txt", kind: "file" }]; if (command === "workspace_read") { if (args.rel === "note.txt") return contents; throw "File not found"; } if (command === "workspace_write") { contents = args.contents; return; } @@ -49,7 +50,7 @@ await page.addInitScript(() => { }, }; window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} }; - window.__TEST__ = { calls, windows, pick: path => picked = path, clear: () => recent = [] }; + window.__TEST__ = { calls, windows, pick: path => picked = path, clear: () => recent = [], reorder: () => recent = ["D:\\Writing\\Notes", current, "D:\\Missing"] }; }); try { await page.goto(process.env.SMOKE_URL || "http://127.0.0.1:1420"); @@ -64,8 +65,13 @@ try { }); const trigger = page.getByRole("button", { name: "Open folder", exact: true }); const menu = page.getByRole("dialog", { name: "Workspaces", exact: true }); + await page.evaluate(() => window.__TEST__.reorder()); await trigger.click(); await menu.getByText("D:\\Writing\\Notes", { exact: true }).waitFor(); + await page.mouse.move(1000, 50); + assert.equal(await menu.locator('.workspace-row').first().evaluate(node => node === document.activeElement), false, "Pointer opening does not force focus onto a different workspace"); + assert.equal(await menu.locator('.workspace-row').first().evaluate(node => getComputedStyle(node).backgroundColor), "rgba(0, 0, 0, 0)", "The first workspace has no stuck highlight"); + assert.equal(await menu.locator('[aria-current="true"]').count(), 1); assert.equal(await page.evaluate(() => window.__TEST__.calls.filter(c => c.command === "plugin:dialog|open").length), 0); await page.screenshot({ path: ".audit/workspaces-menu.png" }); const opened = await page.evaluate(() => window.__TEST__.calls.filter(c => c.command === "workspace_open").length); @@ -109,6 +115,26 @@ try { assert.equal(await page.locator(":focus").textContent(), " Open another folder…"); await page.keyboard.press("Escape"); await menu.waitFor({ state: "hidden" }); + for (const theme of ['light', 'dark']) { + await page.evaluate(async mode => { + const { applyAppearance } = await import('/src/lib/theme/appearance.ts'); + applyAppearance({ theme: 'default', mode }); + }, theme); + await page.setViewportSize({ width: theme === 'light' ? 1100 : 380, height: 800 }); + await trigger.click(); + await menu.getByRole('button', { name: 'Remove D:\\Missing from recent workspaces', exact: true }).focus(); + await page.screenshot({ path: `.audit/workspaces-remove-${theme}.png` }); + if (theme === 'dark') { + await page.keyboard.press('Enter'); + await menu.getByText('D:\\Missing', { exact: true }).waitFor({ state: 'detached' }); + assert.equal(await page.locator('.ws').textContent(), 'Notes', 'History removal does not close the current workspace'); + await page.keyboard.press('Escape'); + await trigger.click(); + assert.equal(await menu.getByText('D:\\Missing', { exact: true }).count(), 0, 'Removed paths stay absent after reopening'); + } + await page.keyboard.press('Escape'); + } + await page.setViewportSize({ width: 1100, height: 800 }); await page.evaluate(() => window.__TEST__.clear()); await trigger.click(); await menu.getByText("No recent workspaces yet.").waitFor(); diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index 90c9bb4..d0815e2 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -3130,7 +3130,7 @@ dependencies = [ [[package]] name = "runestone" -version = "0.1.34" +version = "0.1.36" dependencies = [ "base64 0.23.1", "dunce", diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index ae5b5ca..337d007 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "runestone" -version = "0.1.34" +version = "0.1.36" description = "Writing workspace plus script editor" authors = ["you"] edition = "2021" @@ -44,4 +44,4 @@ panic = "abort" strip = true [package.metadata.runestone] -version = "0.1.34" +version = "0.1.36" diff --git a/src-tauri/build.rs b/src-tauri/build.rs index fd060d2..634d23d 100644 --- a/src-tauri/build.rs +++ b/src-tauri/build.rs @@ -34,10 +34,12 @@ fn main() { "workspace_open_window", "workspace_last_path", "workspace_recent", + "workspace_forget", "workspace_new", "workspace_list", "workspace_list_markdown", "workspace_read", + "workspace_read_many", "workspace_read_bytes", "workspace_write", "workspace_create", diff --git a/src-tauri/capabilities/default.json b/src-tauri/capabilities/default.json index 3c4bafc..ff79961 100644 --- a/src-tauri/capabilities/default.json +++ b/src-tauri/capabilities/default.json @@ -43,10 +43,12 @@ "allow-workspace-open-window", "allow-workspace-last-path", "allow-workspace-recent", + "allow-workspace-forget", "allow-workspace-new", "allow-workspace-list", "allow-workspace-list-markdown", "allow-workspace-read", + "allow-workspace-read-many", "allow-workspace-read-bytes", "allow-workspace-write", "allow-workspace-create", diff --git a/src-tauri/permissions/autogenerated/workspace_forget.toml b/src-tauri/permissions/autogenerated/workspace_forget.toml new file mode 100644 index 0000000..a229a92 --- /dev/null +++ b/src-tauri/permissions/autogenerated/workspace_forget.toml @@ -0,0 +1,11 @@ +# Automatically generated - DO NOT EDIT! + +[[permission]] +identifier = "allow-workspace-forget" +description = "Enables the workspace_forget command without any pre-configured scope." +commands.allow = ["workspace_forget"] + +[[permission]] +identifier = "deny-workspace-forget" +description = "Denies the workspace_forget command without any pre-configured scope." +commands.deny = ["workspace_forget"] diff --git a/src-tauri/permissions/autogenerated/workspace_read_many.toml b/src-tauri/permissions/autogenerated/workspace_read_many.toml new file mode 100644 index 0000000..30b5fce --- /dev/null +++ b/src-tauri/permissions/autogenerated/workspace_read_many.toml @@ -0,0 +1,11 @@ +# Automatically generated - DO NOT EDIT! + +[[permission]] +identifier = "allow-workspace-read-many" +description = "Enables the workspace_read_many command without any pre-configured scope." +commands.allow = ["workspace_read_many"] + +[[permission]] +identifier = "deny-workspace-read-many" +description = "Denies the workspace_read_many command without any pre-configured scope." +commands.deny = ["workspace_read_many"] diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 7495024..9474320 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -59,10 +59,12 @@ pub fn run() { workspace::workspace_open_window, workspace::workspace_last_path, workspace::workspace_recent, + workspace::workspace_forget, workspace::workspace_new, workspace::workspace_list, workspace::workspace_list_markdown, workspace::workspace_read, + workspace::workspace_read_many, workspace::workspace_read_bytes, workspace::workspace_write, workspace::workspace_create, diff --git a/src-tauri/src/spelling.rs b/src-tauri/src/spelling.rs index 34918b6..24c37be 100644 --- a/src-tauri/src/spelling.rs +++ b/src-tauri/src/spelling.rs @@ -220,49 +220,79 @@ pub fn spelling_menu_uninstall(window: tauri::WebviewWindow) -> Result<(), Strin #[derive(serde::Serialize)] pub struct Suggestions { language: String, words: Vec, misspelled: bool } +#[cfg(windows)] +mod suggestions_worker { + use super::Suggestions; + use std::{collections::HashMap, sync::{mpsc, OnceLock}}; + use windows::{core::{HSTRING, PWSTR}, Win32::{Globalization::{ISpellChecker, ISpellCheckerFactory, SpellCheckerFactory}, System::Com::{CoInitializeEx, CoUninitialize, CoCreateInstance, CLSCTX_INPROC_SERVER, COINIT_APARTMENTTHREADED}}}; + type Reply = Result; + type Request = (String, Vec, bool, mpsc::SyncSender); + static WORKER: OnceLock> = OnceLock::new(); + + pub fn request(word: String, languages: Vec, add: bool) -> Reply { + let worker = WORKER.get_or_init(|| { + let (send, receive) = mpsc::channel::(); + std::thread::spawn(move || unsafe { + let initialized = CoInitializeEx(None, COINIT_APARTMENTTHREADED).ok().map_err(|error| error.to_string()); + let apartment_initialized = initialized.is_ok(); + let factory: Result = initialized.and_then(|_| CoCreateInstance(&SpellCheckerFactory, None, CLSCTX_INPROC_SERVER).map_err(|error| error.to_string())); + let mut checkers = HashMap::::new(); + for (word, languages, add, reply) in receive { + let result = (|| -> Reply { + let factory = factory.as_ref().map_err(Clone::clone)?; + for language in languages { + if language.len() > 85 || language.contains('\0') { continue; } + if !checkers.contains_key(&language) { + let tag = HSTRING::from(&language); + if !factory.IsSupported(&tag).map_err(|error| error.to_string())?.as_bool() { continue; } + let checker = factory.CreateSpellChecker(&tag).map_err(|error| error.to_string())?; + checkers.insert(language.clone(), checker); + } + let checker = &checkers[&language]; + let value = HSTRING::from(&word); + if add { + checker.Add(&value).map_err(|error| error.to_string())?; + return Ok(Suggestions { language, words: Vec::new(), misspelled: false }); + } + let errors = checker.Check(&value).map_err(|error| error.to_string())?; + let mut error = None; + errors.Next(&mut error).ok().map_err(|error| error.to_string())?; + if error.is_none() { return Ok(Suggestions { language, words: Vec::new(), misspelled: false }); } + let suggestions = checker.Suggest(&value).map_err(|error| error.to_string())?; + let mut words = Vec::new(); + for _ in 0..8 { + let mut values = [PWSTR::null()]; + let mut count = 0; + suggestions.Next(&mut values, Some(&mut count)).ok().map_err(|error| error.to_string())?; + if count == 0 { break; } + let suggestion = webview2_com::take_pwstr(values[0]); + if !suggestion.is_empty() && suggestion != word { words.push(suggestion); } + } + return Ok(Suggestions { language, words, misspelled: true }); + } + Err("No spelling dictionary is installed for this language.".into()) + })(); + let _ = reply.send(result); + } + drop(checkers); + drop(factory); + if apartment_initialized { CoUninitialize(); } + }); + send + }); + let (reply, receive) = mpsc::sync_channel(1); + worker.send((word, languages, add, reply)).map_err(|_| "The spelling service stopped.".to_owned())?; + receive.recv().map_err(|_| "The spelling service stopped.".to_owned())? + } +} + #[tauri::command] pub async fn spelling_suggestions(word: String, languages: Vec, add: Option) -> Result { if word.is_empty() || word.len() > 256 || word.contains('\0') || languages.len() > 20 { return Err("Invalid spelling request.".into()); } #[cfg(windows)] { - tauri::async_runtime::spawn_blocking(move || -> Result { - use windows::{core::{HSTRING, PWSTR}, Win32::{Globalization::{ISpellCheckerFactory, SpellCheckerFactory}, System::Com::{CoInitializeEx, CoUninitialize, CoCreateInstance, CLSCTX_INPROC_SERVER, COINIT_APARTMENTTHREADED}}}; - unsafe { - CoInitializeEx(None, COINIT_APARTMENTTHREADED).ok().map_err(|error| error.to_string())?; - struct Apartment; - impl Drop for Apartment { fn drop(&mut self) { unsafe { CoUninitialize(); } } } - let _apartment = Apartment; - let factory: ISpellCheckerFactory = CoCreateInstance(&SpellCheckerFactory, None, CLSCTX_INPROC_SERVER).map_err(|error| error.to_string())?; - for language in languages { - if language.len() > 85 || language.contains('\0') { continue; } - let tag = HSTRING::from(&language); - if !factory.IsSupported(&tag).map_err(|error| error.to_string())?.as_bool() { continue; } - let checker = factory.CreateSpellChecker(&tag).map_err(|error| error.to_string())?; - let value = HSTRING::from(&word); - if add.unwrap_or(false) { - checker.Add(&value).map_err(|error| error.to_string())?; - return Ok(Suggestions { language, words: Vec::new(), misspelled: false }); - } - let errors = checker.Check(&value).map_err(|error| error.to_string())?; - let mut error = None; - errors.Next(&mut error).ok().map_err(|error| error.to_string())?; - if error.is_none() { return Ok(Suggestions { language, words: Vec::new(), misspelled: false }); } - let suggestions = checker.Suggest(&value).map_err(|error| error.to_string())?; - let mut words = Vec::new(); - for _ in 0..8 { - let mut values = [PWSTR::null()]; - let mut count = 0; - suggestions.Next(&mut values, Some(&mut count)).ok().map_err(|error| error.to_string())?; - if count == 0 { break; } - let suggestion = webview2_com::take_pwstr(values[0]); - if !suggestion.is_empty() && suggestion != word { words.push(suggestion); } - } - return Ok(Suggestions { language, words, misspelled: true }); - } - Err("No spelling dictionary is installed for this language.".into()) - } - }).await.map_err(|error| error.to_string())? + tauri::async_runtime::spawn_blocking(move || suggestions_worker::request(word, languages, add.unwrap_or(false))).await.map_err(|error| error.to_string())? } #[cfg(not(windows))] { let _ = (word, languages, add); Err("System spelling is unavailable.".into()) } } @@ -272,6 +302,26 @@ mod tests { use super::*; use std::collections::HashSet; + #[cfg(windows)] + #[test] + fn spelling_worker_reuses_the_dictionary_for_repeated_requests() { + let start = std::time::Instant::now(); + let first = suggestions_worker::request("recieved".into(), vec!["en-US".into()], false); + let cold = start.elapsed(); + if let Err(error) = &first { + if error.contains("No spelling dictionary") { eprintln!("No English dictionary installed: {error}"); return; } + } + let first = first.unwrap(); + assert!(first.misspelled); + assert!(first.words.iter().any(|word| word == "received")); + let start = std::time::Instant::now(); + for _ in 0..10 { + let next = suggestions_worker::request("recieved".into(), vec!["en-US".into()], false).unwrap(); + assert_eq!(first.words, next.words); + } + eprintln!("Spelling service: cold {cold:?}, average warm {:?}", start.elapsed() / 10); + } + #[test] fn unrelated_browser_tools_are_removed_without_changing_editor_commands() { for name in ["share", "writingDirection", "voiceTyping", "other"] { assert!(excluded_command(name, true)); } diff --git a/src-tauri/src/workspace.rs b/src-tauri/src/workspace.rs index 55dc0b0..66e83f9 100644 --- a/src-tauri/src/workspace.rs +++ b/src-tauri/src/workspace.rs @@ -142,6 +142,22 @@ pub fn workspace_recent(app: AppHandle) -> WsResult> { Ok(load_workspace_history(&last_workspace_file(&app)?)) } +fn forget_workspace(path: &Path, root: &str) -> WsResult> { + let mut roots = load_workspace_history(path); + roots.retain(|previous| { + if cfg!(windows) { !previous.eq_ignore_ascii_case(root) } else { previous != root } + }); + let payload = serde_json::json!({ "root": roots.first(), "recent": roots }); + fs::write(path, serde_json::to_string_pretty(&payload).unwrap())?; + Ok(roots) +} + +#[tauri::command] +pub fn workspace_forget(app: AppHandle, path: String) -> WsResult> { + let _guard = HISTORY_LOCK.lock().map_err(|_| err("workspace history lock"))?; + forget_workspace(&last_workspace_file(&app)?, &path) +} + fn create_workspace_folder(parent: &str, name: &str) -> WsResult { let name = name.trim(); let stem = name.split('.').next().unwrap_or("").to_ascii_uppercase(); @@ -575,6 +591,45 @@ fn read_optional_text(path: &Path, missing_ok: bool) -> WsResult> } } +#[derive(Debug, Serialize)] +pub struct TextRead { + path: String, + #[serde(skip_serializing_if = "Option::is_none")] + source: Option, + #[serde(skip_serializing_if = "Option::is_none")] + error: Option, +} + +fn read_many_text(root: &Path, paths: Vec) -> WsResult> { + if paths.len() > 64 { return Err(err("Read at most 64 files per request.")); } + let mut remaining = 16 * 1024 * 1024usize; + Ok(paths.into_iter().map(|path| { + let result = (|| -> WsResult { + let resolved = resolve_existing(root, &path)?; + let file = fs::File::open(resolved)?; + let metadata = file.metadata()?; + if !metadata.is_file() { return Err(err("The path must be a file.")); } + if metadata.len() > remaining as u64 { return Err(err("The batch exceeds the 16 MiB limit.")); } + let mut bytes = Vec::new(); + file.take(remaining as u64 + 1).read_to_end(&mut bytes)?; + if bytes.len() > remaining { return Err(err("The batch exceeds the 16 MiB limit.")); } + remaining -= bytes.len(); + String::from_utf8(bytes).map_err(|_| err("The file is not valid UTF-8.")) + })(); + match result { + Ok(source) => TextRead { path, source: Some(source), error: None }, + Err(error) => TextRead { path, source: None, error: Some(error.to_string()) }, + } + }).collect()) +} + +#[tauri::command] +pub async fn workspace_read_many(window: tauri::Window, state: State<'_, WorkspaceState>, paths: Vec) -> WsResult> { + let root = current_root(&state, window.label())?; + tauri::async_runtime::spawn_blocking(move || read_many_text(&root, paths)) + .await.map_err(|error| err(error.to_string()))? +} + const MAX_BINARY_BYTES: u64 = 64 * 1024 * 1024; fn read_workspace_bytes(root: &Path, rel: &str) -> WsResult> { @@ -1268,6 +1323,33 @@ mod tests { fs::remove_file(path).unwrap(); } + #[test] + fn forgetting_workspaces_persists_without_restoring_the_last_root() { + let path = std::env::temp_dir().join(format!("rs-forget-history-{}.json", std::process::id())); + fs::write(&path, r#"{"root":"D:/first","recent":["D:/first","D:/second"]}"#).unwrap(); + assert_eq!(forget_workspace(&path, "D:/first").unwrap(), vec!["D:/second"]); + assert_eq!(load_workspace_history(&path), vec!["D:/second"]); + assert!(forget_workspace(&path, "D:/second").unwrap().is_empty()); + assert!(load_workspace_history(&path).is_empty()); + fs::remove_file(path).unwrap(); + } + + #[test] + fn batch_reads_keep_errors_per_file_and_enforce_workspace_limits() { + let root = std::env::temp_dir().join(format!("rs-read-many-{}", std::process::id())); + fs::create_dir_all(&root).unwrap(); + let root = dunce::canonicalize(root).unwrap(); + fs::write(root.join("valid.md"), "card text").unwrap(); + fs::write(root.join("binary"), [0xff]).unwrap(); + let items = read_many_text(&root, vec!["valid.md".into(), "missing".into(), "../outside".into(), ".".into(), "binary".into()]).unwrap(); + assert_eq!(items[0].source.as_deref(), Some("card text")); + assert!(items[1..].iter().all(|item| item.source.is_none() && item.error.is_some())); + assert!(read_many_text(&root, vec!["valid.md".into(); 65]).is_err()); + fs::write(root.join("large"), vec![b'x'; 16 * 1024 * 1024 + 1]).unwrap(); + assert!(read_many_text(&root, vec!["large".into()]).unwrap()[0].error.is_some()); + fs::remove_dir_all(root).unwrap(); + } + #[test] fn new_workspace_creates_only_a_new_child_folder() { let parent = std::env::temp_dir().join(format!("rs-new-workspace-{}", std::process::id())); diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index 240ec9c..ec7621e 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "https://schema.tauri.app/config/2", "productName": "RuneStone", - "version": "0.1.34", + "version": "0.1.36", "identifier": "com.runestone.app", "build": { "beforeDevCommand": "pnpm dev", diff --git a/src/lib/browser/Bookmarks.svelte b/src/lib/browser/Bookmarks.svelte index 3db49d0..4f87ae9 100644 --- a/src/lib/browser/Bookmarks.svelte +++ b/src/lib/browser/Bookmarks.svelte @@ -1,4 +1,5 @@
-

Browser

Choose how you browse within RuneStone.

-

General

+

{$t("Browser")}

{$t("Choose how you browse within RuneStone.")}

+

{$t("General")}

{ event.preventDefault(); if (ready && !busy) void save(); }}>
- - -
Search engine
- - + + +
{$t("Search engine")}
+ +
- - + +
-

Profiles

New profiles start blank. Duplicate a profile to copy its stored browsing data and bookmarks.

+

{$t("Profiles")}

{$t("New profiles start blank. Duplicate a profile to copy its stored browsing data and bookmarks.")}

-
Profile
- -
-

Duplication briefly restarts browser tabs. The copies remain separate. Agent permissions are not copied.

+
{$t("Profile")}
+ +
+

{$t("Duplication briefly restarts browser tabs. The copies remain separate. Agent permissions are not copied.")}

-

Web data

Clear data for the selected profile. Its browser tabs will close. Bookmarks remain.

-
+

{$t("Web data")}

{$t("Clear data for the selected profile. Its browser tabs will close. Bookmarks remain.")}

+

{message}

{#if ready}{/if}
diff --git a/src/lib/browser/WebData.svelte b/src/lib/browser/WebData.svelte index a9a3179..d6e0cd1 100644 --- a/src/lib/browser/WebData.svelte +++ b/src/lib/browser/WebData.svelte @@ -1,4 +1,5 @@ -
+
-
Show
- - +
{$t("Show")}
+ +
-

Remove individual entries for this profile. Open tabs stay open. Sites can create cookies again.

+

{$t("Remove individual entries for this profile. Open tabs stay open. Sites can create cookies again.")}

{#if error}

{error}

{/if} - {#if busy}

Please wait…

{/if} + {#if busy}

{$t("Please wait…")}

{/if}
{#if kind === 'cookies'} - {#each cookies as cookie (cookie.id)}
{cookie.name || '(unnamed cookie)'}{cookie.domain} · {cookie.path}
{/each} - {#if data && !cookies.length}

No matching cookies.

{/if} + {#each cookies as cookie (cookie.id)}
{cookie.name || '(unnamed cookie)'}{cookie.domain} · {cookie.path}
{/each} + {#if data && !cookies.length}

{$t("No matching cookies.")}

{/if} {:else} - {#each history as visit (visit.id)}
{visit.title || visit.url}{visit.url}{new Date(visit.at).toLocaleString()}
{/each} - {#if data && !history.length}

No matching history.

{/if} + {#each history as visit (visit.id)}
{visit.title || visit.url}{visit.url}{new Date(visit.at).toLocaleString()}
{/each} + {#if data && !history.length}

{$t("No matching history.")}

{/if} {/if}
diff --git a/src/lib/editor/EditorHost.svelte b/src/lib/editor/EditorHost.svelte index 1d03d92..44ca688 100644 --- a/src/lib/editor/EditorHost.svelte +++ b/src/lib/editor/EditorHost.svelte @@ -1,4 +1,5 @@ -
+
- searchText, value => { searchText = value; commit(); }} />
- findPrevious(view)} disabled={!query.valid} /> - findNext(view)} disabled={!query.valid} /> - - closeSearchPanel(view)} /> + findPrevious(view)} disabled={!query.valid} /> + findNext(view)} disabled={!query.valid} /> + + closeSearchPanel(view)} />
- - - - {#if searchText && !query.valid}Invalid expression{/if} + + + + {#if searchText && !query.valid}{$t("Invalid expression")}{/if}
{#if !view.state.readOnly}
- replacement, value => { replacement = value; commit(); }} /> + replacement, value => { replacement = value; commit(); }} />
- - + +
{/if} diff --git a/src/lib/editor/LiveWriter.svelte b/src/lib/editor/LiveWriter.svelte index 55c35dd..4858afb 100644 --- a/src/lib/editor/LiveWriter.svelte +++ b/src/lib/editor/LiveWriter.svelte @@ -1,4 +1,5 @@ -
{ if (!onInsertImage || !hasFileDrag(event.dataTransfer)) return; event.preventDefault(); @@ -403,7 +404,7 @@ }} ondropcapture={(event) => { if (editor) void insertImages(event, editor); }} >
-{#if error}{/if} +{#if error}{/if} diff --git a/src/lib/plugins/PluginManager.svelte b/src/lib/plugins/PluginManager.svelte index 5b06a42..8bfb70e 100644 --- a/src/lib/plugins/PluginManager.svelte +++ b/src/lib/plugins/PluginManager.svelte @@ -1,4 +1,5 @@ -

Plug-ins

-

Install a plugin ZIP file or get a release from a Git repository link.

+

{$t("Plug-ins")}

+

{$t("Install a plugin ZIP file or get a release from a Git repository link.")}

- - - reveal()} /> - + + + reveal()} /> +
{#if $installedPlugins.root}

{$installedPlugins.root}

{/if} -{#if !desktop}

Installation requires the RuneStone desktop app.

{/if} +{#if !desktop}

{$t("Installation requires the RuneStone desktop app.")}

{/if} {#if $pluginServiceError}{/if} -

Installed plugins

-

Plugins run with RuneStone's access. Only enable code you trust.

-{#if !external.length}

No plugins installed.

{/if} +

{$t("Installed plugins")}

+

{$t("Plugins run with RuneStone's access. Only enable code you trust.")}

+{#if !external.length}

{$t("No plugins installed.")}

{/if} {#each external as plugin (plugin.manifest.id)}
-

{plugin.manifest.description}

{plugin.manifest.author} · {plugin.manifest.version} · Full app access +

{plugin.manifest.description}

{plugin.manifest.author} · {plugin.manifest.version} · {$t("Full app access")}
- {plugin.manifest.id === "runestone.browser" ? "Included with RuneStone" : plugin.removal ? "Removal incomplete" : plugin.enabled ? "Enabled" : "Disabled"} + {plugin.manifest.id === "runestone.browser" ? $t("Included with RuneStone") : plugin.removal ? $t("Removal incomplete") : plugin.enabled ? $t("Enabled") : $t("Disabled")} {#if plugin.installedAt != null} - Installed + {$t("Installed")} {:else} - Install date unknown + {$t("Install date unknown")} {/if}
{ const value = event.currentTarget.checked; event.currentTarget.checked = plugin.enabled; void toggle(plugin.manifest.id, value, plugin.hash); }} /> - reveal(plugin.manifest.id)} /> + reveal(plugin.manifest.id)} /> {#if plugin.removal} - + {:else} - prepare(plugin)} /> + prepare(plugin)} /> {/if}
- {#if plugin.manifest.id === "runestone.browser"}

Browser is now built in. You can remove this old package. Your browser profiles and bookmarks stay available.

{/if} + {#if plugin.manifest.id === "runestone.browser"}

{$t("Browser is now built in. You can remove this old package. Your browser profiles and bookmarks stay available.")}

{/if} {#if plugin.error || $externalErrors[plugin.manifest.id]}{/if}
{/each} -{#if $restartPlugins.length}

Restart RuneStone to clear all code from plugins that stopped in this window.

{/if} +{#if $restartPlugins.length}

{$t("Restart RuneStone to clear all code from plugins that stopped in this window.")}

{/if} {#if error}{/if} {#if message}

{message}

{/if} {#if candidates.length || plan || gitForm} { event.preventDefault(); event.stopPropagation(); void cancel(); }}> {#if gitForm} -

Install from Git link

-

Get a Gitea release ZIP, then review it before installation. Git-link installation is an experimental feature.

+

{$t("Install from Git link")}

+

{$t("Get a Gitea release ZIP, then review it before installation. Git-link installation is an experimental feature.")}

{ event.preventDefault(); if (!busy) void fromGit(); }}> - - - -

Private repositories need a token with read access. RuneStone does not save the token.

- {#if gitUrl.trim().startsWith("http:")}

HTTP sends the token and package without encryption. Use it only for a trusted local server.

{/if} + + + +

{$t("Private repositories need a token with read access. RuneStone does not save the token.")}

+ {#if gitUrl.trim().startsWith("http:")}

{$t("HTTP sends the token and package without encryption. Use it only for a trusted local server.")}

{/if} {#if error}{/if} -
+
{:else if plan} -

{`Uninstall ${plan.plugin.manifest.name}?`}

+

{$t("Uninstall {name}?", { name: plan.plugin.manifest.name })}

{plan.plugin.manifest.author} · {plan.plugin.manifest.version}

{plan.plugin.path}

-

This stops the plugin in every window and permanently deletes its installed folder. Settings, source packages, and workspace documents stay intact.

+

{$t("This stops the plugin in every window and permanently deletes its installed folder. Settings, source packages, and workspace documents stay intact.")}

{#if error}{/if}
- - - + + +
{:else} -

Review plugin installation

-

Plugins run with RuneStone's access. Only enable code you trust.

+

{$t("Review plugin installation")}

+

{$t("Plugins run with RuneStone's access. Only enable code you trust.")}

{#each candidates as candidate (candidate.token)}
- - {#if candidate.manifest}

{candidate.manifest.author} · {candidate.manifest.version}

{candidate.manifest.description}

Destination: {$installedPlugins.root}\{candidate.manifest.id}

{/if} -

Source: {candidate.source}

+ + {#if candidate.manifest}

{candidate.manifest.author} · {candidate.manifest.version}

{candidate.manifest.description}

{$t("Destination: {path}", { path: `${$installedPlugins.root}\\${candidate.manifest.id}` })}

{/if} +

{$t("Source: {path}", { path: candidate.source })}

{#if candidate.error}

{candidate.error}

{/if}
{/each} {#if error}{/if} -
+
{/if}
{/if} diff --git a/src/lib/plugins/PluginTools.svelte b/src/lib/plugins/PluginTools.svelte index 5841ee5..64f1f82 100644 --- a/src/lib/plugins/PluginTools.svelte +++ b/src/lib/plugins/PluginTools.svelte @@ -1,4 +1,5 @@ -{#if error && $pluginView?.placement !== "dialog"}{/if} +{#if error && $pluginView?.placement !== "dialog"}{/if} {#if $pluginView?.placement === "dialog"} { event.preventDefault(); pluginView.set(null); }}> -

{$pluginView.title}

pluginView.set(null)} />
+

{$pluginView.title}

pluginView.set(null)} />
{#if error}{/if}
diff --git a/src/lib/plugins/access.ts b/src/lib/plugins/access.ts index 0232f6a..e43e2ed 100644 --- a/src/lib/plugins/access.ts +++ b/src/lib/plugins/access.ts @@ -3,7 +3,7 @@ import type { PluginCommand, PluginView } from "./sdk.ts"; export type PluginTool = { owner: string; id: string; title: string; kind: "command" | "view"; surface: "commands" | "open" | "settings"; - icon?: PluginView["icon"]; + icon?: PluginCommand["icon"]; }; export function pluginAccess(owner: string, commands: Iterable, views: Iterable): PluginTool[] { diff --git a/src/lib/plugins/backgrounds.ts b/src/lib/plugins/backgrounds.ts index 58266f8..0b6ad53 100644 --- a/src/lib/plugins/backgrounds.ts +++ b/src/lib/plugins/backgrounds.ts @@ -105,8 +105,8 @@ export class BackgroundHub { body.style.setProperty('--rs-background-previous-layer-positions', frame.previous ? image(frame.previous).positions : layerPositions); body.style.setProperty('--rs-workarea-sidebar-bg', 'var(--rs-image-sidebar-bg)'); body.style.setProperty('--rs-workarea-editor-bg', 'var(--rs-image-editor-bg)'); - body.style.setProperty('--rs-workarea-surface-opacity', '82%'); - body.style.setProperty('--rs-workarea-plugin-bg', 'transparent'); + body.style.setProperty('--rs-workarea-surface-opacity', 'var(--rs-surface-opacity, 82%)'); + body.style.setProperty('--rs-workarea-plugin-bg', 'var(--rs-transparent-plugin-bg, transparent)'); body.style.setProperty('--rs-background-transition-image', frame.previous ? currentImage : 'none'); body.style.setProperty('--rs-background-previous-image', frame.previous ? image(frame.previous).image : 'none'); body.style.setProperty('--rs-background-previous-position', frame.previous?.position ?? frame.position); diff --git a/src/lib/plugins/external.ts b/src/lib/plugins/external.ts index 7cc6aa6..4ae1fd8 100644 --- a/src/lib/plugins/external.ts +++ b/src/lib/plugins/external.ts @@ -254,6 +254,7 @@ async function activate(row: InstalledPlugin, builtin?: PluginModule) { workspace: { list: path => workspaceList(path ?? ""), read: workspaceRead, listMarkdown: () => invoke("workspace_list_markdown"), + readMany: paths => invoke<{ path: string; source?: string; error?: string }[]>("workspace_read_many", { paths }), readBytes: workspaceReadBytes, write: async (path, source, expected) => { canWrite(path); await workspaceWrite(path, source, expected); notifyPluginWorkspace(); }, subscribe: listener => { workspaceListeners.add(listener); return () => { workspaceListeners.delete(listener); }; }, diff --git a/src/lib/plugins/externalSession.ts b/src/lib/plugins/externalSession.ts index aab09a0..be2c608 100644 --- a/src/lib/plugins/externalSession.ts +++ b/src/lib/plugins/externalSession.ts @@ -4,6 +4,7 @@ import { registerCompletionInput } from "../completion/input.ts"; import { showActionMenu } from "../ui/managedActionMenu.ts"; import { backgroundHub } from "./backgrounds.ts"; import type { BackgroundFiles } from "./backgroundContracts.ts"; +import { pluginTranslation } from "./translation.ts"; import type { Dispose, PluginApi, PluginCommand, PluginModule, PluginView, PluginDocumentType, PluginDocumentContext } from "./sdk.ts"; export function deadline(work: Promise, milliseconds = 5000): Promise { @@ -54,6 +55,7 @@ export class ExternalSession { }; const api: PluginApi = { id: this.id, signal: this.controller.signal, + i18n: pluginTranslation(() => this.check(), off => { this.contributions.push(off); }), ...(this.services.backgrounds ? { backgrounds: { version: 1 as const, chooseFolder: () => this.backgroundRequest(() => this.services.backgrounds!.chooseFolder()), @@ -139,6 +141,7 @@ export class ExternalSession { list: path => { this.check(); return this.services.workspace.list(path); }, ...(this.services.workspace.listMarkdown ? { listMarkdown: () => { this.check(); return this.services.workspace.listMarkdown!(); } } : {}), read: path => { this.check(); return this.services.workspace.read(path); }, + ...(this.services.workspace.readMany ? { readMany: (paths: string[]) => { this.check(); return this.services.workspace.readMany!(paths); } } : {}), ...(this.services.workspace.readBytes ? { readBytes: (path: string) => { this.check(); return this.services.workspace.readBytes!(path); } } : {}), ...(this.services.workspace.readOptional ? { readOptional: (path: string) => { this.check(); return this.services.workspace.readOptional!(path); } } : {}), ...(this.services.workspace.create ? { create: (path: string, contents: string) => { this.check(); return this.services.workspace.create!(path, contents); } } : {}), diff --git a/src/lib/plugins/sdk.ts b/src/lib/plugins/sdk.ts index 2596689..457e54a 100644 --- a/src/lib/plugins/sdk.ts +++ b/src/lib/plugins/sdk.ts @@ -1,10 +1,11 @@ import type { Contributions } from "./contracts.ts"; import type { CompletionApi } from "../completion/contracts.ts"; import type { ActionMenuItem } from "../ui/actionMenu.ts"; +import type { ActionIcon } from "../ui/actionIcons.ts"; export type { BackgroundFrame, BackgroundApi } from "./backgroundContracts.ts"; /** Package API v1. Compiled plugins export activate(api). */ export type Dispose = () => void | Promise; -export interface PluginCommand { id: string; title: string; icon?: PluginView["icon"]; category?: "open" | "action"; run: () => void | Promise } +export interface PluginCommand { id: string; title: string; icon?: ActionIcon | PluginView["icon"]; category?: "open" | "action"; run: () => void | Promise } export interface PluginView { id: string; title: string; settings?: boolean; launcher?: boolean; placement?: "dialog" | "editor" | "sidebar"; navigation?: boolean; toolbar?: boolean; pinned?: boolean; icon?: "list" | "kanban" | "puzzle" | "globe" | "git"; iconImage?: string | null; tabActions?: (context: { pinned: boolean }) => ActionMenuItem[]; tabDragData?: (context: { pinned: boolean }) => string | undefined; find?: () => void; saveTabState?: () => unknown; restoreTabState?: (state: unknown) => void | Promise; mount: (container: HTMLElement, context?: { surface: "settings" | "view" }) => void | Dispose | Promise } export interface PluginViewOpenOptions { split: "right" | "down"; relativeTo: string } export interface PluginDocumentContext { id: string; path: string } @@ -19,6 +20,7 @@ export interface PluginDocumentType { mount(container: HTMLElement, document: PluginDocumentContext): void | Dispose | Promise; } export interface PluginApi { + i18n?: import("./translation.ts").PluginTranslation; backgrounds?: import("./backgroundContracts.ts").BackgroundApi; ui?: { showActionMenu(options: import("../ui/managedActionMenu.ts").MenuOptions): { close(): void } }; git?: import("../git/contracts.ts").GitApi; @@ -44,6 +46,7 @@ export interface PluginApi { list(path?: string): Promise<{ name: string; rel_path: string; kind: string }[]>; listMarkdown?(): Promise; read(path: string): Promise; + readMany?(paths: string[]): Promise<{ path: string; source?: string; error?: string }[]>; readBytes?(path: string): Promise; readOptional?(path: string): Promise; create?(path: string, contents: string): Promise; diff --git a/src/lib/plugins/translation.ts b/src/lib/plugins/translation.ts new file mode 100644 index 0000000..7377514 --- /dev/null +++ b/src/lib/plugins/translation.ts @@ -0,0 +1,30 @@ +import { get } from 'svelte/store'; +import { locale, translate, type Locale } from '../i18n/index.ts'; + +export type PluginCatalogs = Partial>>; +export interface PluginTranslation { + readonly locale: Locale; + t(message: string, values?: Record, catalogs?: PluginCatalogs): string; + subscribe(listener: (language: Locale) => void): () => void; +} + +/** Translates only explicit interface messages. Document content stays with the plugin. */ +export function pluginTranslation(check: () => void, track: (cleanup: () => void) => void): PluginTranslation { + return { + get locale() { check(); return get(locale); }, + t(message, values = {}, catalogs = {}) { + check(); + const language = get(locale); + const catalog = Object.hasOwn(catalogs, language) ? catalogs[language] : undefined; + if (!catalog || !Object.hasOwn(catalog, message)) return translate(language, message, values); + return catalog[message].replace(/\{(\w+)\}/g, (match, key: string) => Object.hasOwn(values, key) ? String(values[key]) : match); + }, + subscribe(listener) { + check(); + if (typeof listener !== 'function') throw new Error('A language listener must be a function.'); + const off = locale.subscribe(listener); + track(off); + return off; + }, + }; +} diff --git a/src/lib/theme/AppearanceSettings.svelte b/src/lib/theme/AppearanceSettings.svelte index 54455f7..295b102 100644 --- a/src/lib/theme/AppearanceSettings.svelte +++ b/src/lib/theme/AppearanceSettings.svelte @@ -1,4 +1,5 @@ -

Appearance

-

Choose a color theme variant.

+

{$t("Appearance")}

+

{$t("Choose a color theme variant.")}

-
Color theme
+
{$t("Color theme")}
-