Add interface languages and improve themes and workspace controls for 0.1.36

This commit is contained in:
Knotty Wyvern
2026-10-15 10:55:59 -07:00
parent b066359b66
commit 68e86ab6eb
98 changed files with 5499 additions and 874 deletions
+90 -13
View File
@@ -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. 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/`. 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 ## 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: If the maintainer supplied a Windows installer:
1. Open `RuneStone_<version>_x64-setup.exe`. 1. Open `RuneStone_<version>_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. The installer needs no developer tools. It downloads WebView2 if that runtime is missing.
Keep workspace folders outside the application folder. 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 [email protected] || 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 ## Find help
+1 -1
View File
@@ -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. 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).
+20
View File
@@ -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. - 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. - 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. - 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. - 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. - 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. - 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. - 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. - 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.
+4 -4
View File
@@ -47,8 +47,8 @@ The frontend uses port 1420, and Tauri loads `http://localhost:1420`.
| Change or task | Action | | Change or task | Action |
| --- | --- | | --- | --- |
| Svelte, TypeScript, or CSS under `src/` | Save the source file. Vite updates the interface without a Rust rebuild. | | 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. | | 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_TableFormulas/` | Install that checkout's dependencies, then run `pnpm build:plugins` in RuneStone. Reinstall 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 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. | | 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. | | 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. 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. Use `pnpm tauri dev` for manual tests of those features.
Run `pnpm build:plugins` before tests that use Terminal or Table formulas. 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. 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. Set `RUNESTONE_TABLE_FORMULAS_ROOT` if that checkout is elsewhere.
These tests load the compiled packages through the production module loader. These tests load the compiled packages through the production module loader.
The browser tests use the real interface with mocked desktop communication. The browser tests use the real interface with mocked desktop communication.
+3 -3
View File
@@ -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 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. 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 `=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. the header, so the first data row is 2. References stay inside the current table.
Arithmetic supports `+`, `-`, `*`, `/`, `^`, parentheses, and postfix `%`. Arithmetic supports `+`, `-`, `*`, `/`, `^`, parentheses, and postfix `%`.
+3
View File
@@ -23,6 +23,9 @@ persist locally. New terminals inherit the app environment, including PATH.
## Run scripts and navigate commands ## 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 More terminal actions clears scrollback, runs selected editor text, or saves
and runs the active script. Supported runners include Python, JavaScript, and runs the active script. Supported runners include Python, JavaScript,
PowerShell, Bash, Ruby, Windows batch files, and executables. Their runtimes PowerShell, Bash, Ruby, Windows batch files, and executables. Their runtimes
+56 -41
View File
@@ -2,70 +2,85 @@
[User guide](../user-guide.md) · [Interface design](../ui-design.md) [User guide](../user-guide.md) · [Interface design](../ui-design.md)
Open Settings → Appearance to choose RuneStone, Claude, Sakura, or an installed custom theme. Open Settings → Appearance to choose a palette or install a custom theme.
RuneStone and Claude offer light and dark appearances. Sakura uses light only. RuneStone and Claude offer separate light and dark choices in the theme menu.
Claude uses local Lora and Poppins fonts, with Georgia and Arial fallbacks. It does not download fonts. 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 ## Create a theme
1. Choose Export theme template. 1. Select the appearance that you want as a starting point.
2. Edit the saved JSON file in a text editor. 2. Choose Export theme template.
3. Choose Install theme and select the file. 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. The export contains one `colors` palette, including the current surface, text, accent, status, and syntax colors.
Use hexadecimal colors with 3, 4, 6, or 8 digits. The example supplies complete surface and text colors for both modes. 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 ```json
{ {
"schema": 1, "schema": 2,
"id": "harbor", "id": "harbor",
"name": "Harbor", "name": "Harbor",
"light": { "colors": {
"bg": "#f3f6f8", "bg": "#141414",
"bg-elevated": "#ffffff", "bg-elevated": "#1c1c1c",
"bg-active": "#dfe9ef", "bg-active": "#2a2a2a",
"border": "#bccdd8", "border": "#454545",
"text": "#223344", "text": "#e6e6e6",
"text-dim": "#526778", "text-dim": "#b0b0b0",
"text-strong": "#102536", "text-strong": "#ffffff",
"accent": "#14658f", "accent": "#00c8ff",
"selection": "#b5d9ef" "selection": "#264f78"
},
"dark": {
"bg": "#14232e",
"bg-elevated": "#1b2d3b",
"bg-active": "#294354",
"border": "#405b6d",
"text": "#e0eaf0",
"text-dim": "#a3bac8",
"text-strong": "#f5fafc",
"accent": "#81c8ed",
"selection": "#315d77"
} }
} }
``` ```
The ID starts with a lowercase letter and permits lowercase letters, numbers, and hyphens, up to 64 characters. 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. Reinstalling the same ID replaces that theme's colors. The visible name permits up to 80 characters. Installing the same ID replaces that theme's colors.
Unknown color keys or invalid values stop installation with an error. 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 ## Available colors
| Keys | Use | | 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 | | `text`, `text-dim`, `text-strong` | Normal, secondary, and prominent text |
| `accent`, `accent-2`, `selection` | Links, accents, and editor selection | | `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. Optional colors use the base appearance when omitted. Export includes all supported keys to make these choices explicit.
The theme file contains color values, without scripts, style rules, or plugin code. 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 ## Share or remove a theme
With a custom theme selected, Export theme template saves its current definition. 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. Share the JSON file with another user, who can install it through Appearance.
Remove custom theme removes the selected definition and returns to RuneStone colors. Remove custom theme returns to RuneStone colors. Themes remain in this device's preferences across workspaces.
Themes stay in this device's application preferences and apply 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.
+8 -15
View File
@@ -5,7 +5,7 @@
| Platform | Current route | | Platform | Current route |
| --- | --- | | --- | --- |
| Windows 10 or 11, Intel/AMD 64-bit | Supplied local test installer | | 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. | | 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. 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 ## 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. Run the app inside your graphical desktop session as your ordinary user.
2. Install the [Tauri system packages for your distribution](https://v2.tauri.app/start/prerequisites/#linux). Keep Linux dependencies and build output separate from Windows copies.
3. Download or clone RuneStone into a Linux folder. Linux remains experimental. The [validation record](linux.md#release-package-validation-2026-10-15) describes the completed Ubuntu 26.04 checks and remaining limits.
4. Open a terminal in that folder and run the commands below. Ubuntu 24.04 and system-wide package installation remain untested.
```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.
## Try the source on macOS ## Try the source on macOS
+46 -16
View File
@@ -1,6 +1,6 @@
# Linux readiness # 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; Linux support is experimental. Limited native validation is recorded below;
the complete desktop and installer acceptance checks remain outstanding. 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 ## 2. Prepare the Linux build environment
Install Node.js 24, pnpm 10, and stable Rust on the Linux box. Use the [complete README setup](../README.md#linux-ubuntu-2404-lts-intelamd-64-bit) for a first Ubuntu 24.04 trial.
Use a separate Linux checkout. Do not copy Windows `node_modules` or `src-tauri/target` folders. 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). The commands use the project's configured private clone address.
For Ubuntu or Debian with WebKitGTK 4.1 available, use: Source access is required. No public source-download location is configured.
The first build needs internet access for tools and dependencies.
```sh ### Command sources
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
```
These commands are an Ubuntu/Debian example, not instructions for every Linux distribution. The setup instructions were checked against these primary sources on October 15, 2026:
The first Rust build and package build need internet access for dependencies and packaging tools.
- [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 ## 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: From the Linux checkout, install the project dependencies:
```sh ```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. 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 native host uses WebKitGTK and the Browser uses Electron; both need testing.
The full test suite needs the Table formulas package. 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). Clone `RuneStone_Table_Formulas` beside RuneStone and install its dependencies, as described in the [plugin guide](plugins.md).
Then run these checks from RuneStone: Then run these checks from RuneStone:
```sh ```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. 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. 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 ## Validation record: 2026-10-14
Validated on `desk`: Ubuntu 26.04.1 LTS, x86_64, four CPUs, 7.2 GiB reported RAM, 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. was used. Existing user settings and workspaces were not used.
No installer or release package was produced, versions were unchanged, and nothing 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 and rerunning the full source suite, completing the desktop checks above, and
validating Debian/AppImage installation and lifecycle behavior on the intended validating Debian/AppImage installation and lifecycle behavior on the intended
target distribution. These results do not establish full Linux support. target distribution. These results do not establish full Linux support.
+44 -34
View File
@@ -1,15 +1,15 @@
{ {
"date": "2026-10-14", "date": "2026-10-15",
"scope": [ "scope": [
"RuneStone", "RuneStone",
"RuneStone_ProjectManagement", "RuneStone_Project_Management",
"RuneStone_Terminal", "RuneStone_Terminal",
"RuneStone_BG_Slideshow", "RuneStone_Background_Slideshow",
"RuneStone_LocalAutocomplete", "RuneStone_Local_Autocomplete",
"RuneStone_Git", "RuneStone_Git",
"RuneStone_PDFViewer", "RuneStone_PDF_Viewer",
"RuneStone_TableFormulas", "RuneStone_Table_Formulas",
"RuneStone_CSVViewer" "RuneStone_CSV_Viewer"
], ],
"limits": [ "limits": [
"Source patterns detect known menu construction routes. Browser evidence remains a separate check.", "Source patterns detect known menu construction routes. Browser evidence remains a separate check.",
@@ -127,7 +127,7 @@
"RuneStone/src/lib/layout/WorkspacePicker.svelte": { "RuneStone/src/lib/layout/WorkspacePicker.svelte": {
"counts": { "counts": {
"picker": 1, "picker": 1,
"localPopup": 7 "localPopup": 8
}, },
"design": "Shared rich picker; paths retain a detail row", "design": "Shared rich picker; paths retain a detail row",
"check": "scripts/workspaces.smoke.mjs" "check": "scripts/workspaces.smoke.mjs"
@@ -176,64 +176,64 @@
"design": "Shared action menu", "design": "Shared action menu",
"check": "scripts/menuConsistency.smoke.mjs" "check": "scripts/menuConsistency.smoke.mjs"
}, },
"RuneStone_ProjectManagement/src/choices-ui.ts": { "RuneStone_Project_Management/src/choices-ui.ts": {
"counts": { "counts": {
"action": 1 "action": 1
}, },
"design": "Shared action menus and searchable picker classes; older-host fallback retained", "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": { "counts": {
"picker": 1, "picker": 1,
"localPopup": 4 "localPopup": 4
}, },
"design": "Shared action menus and searchable picker classes; older-host fallback retained", "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": { "counts": {
"picker": 1, "picker": 1,
"localPopup": 3 "localPopup": 3
}, },
"design": "Shared action menus and searchable picker classes; older-host fallback retained", "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": { "counts": {
"action": 1, "action": 1,
"nativeChoice": 1 "nativeChoice": 1
}, },
"design": "Shared choice adapter; native selects hidden on current host, older-host fallback retained", "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": { "counts": {
"action": 1, "action": 1,
"picker": 1, "picker": 1,
"localPopup": 3 "localPopup": 3
}, },
"design": "Shared action menus and searchable picker classes; older-host fallback retained", "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": { "counts": {
"nativeChoice": 1, "nativeChoice": 1,
"picker": 1, "picker": 1,
"localPopup": 5 "localPopup": 5
}, },
"design": "Shared relationship choice and direct searchable picker rows; older-host choice fallback retained", "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": { "counts": {
"picker": 2, "picker": 2,
"localPopup": 2 "localPopup": 2
}, },
"design": "Shared action menus and searchable picker classes; older-host fallback retained", "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": { "counts": {
"action": 4, "action": 4,
"nativeChoice": 14, "nativeChoice": 14,
@@ -241,7 +241,7 @@
"localPopup": 1 "localPopup": 1
}, },
"design": "Shared choice adapter; native selects hidden on current host, older-host fallback retained", "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": { "RuneStone_Terminal/src/TerminalDock.svelte": {
"counts": { "counts": {
@@ -266,14 +266,14 @@
"design": "Synchronized shared action menu snapshot", "design": "Synchronized shared action menu snapshot",
"check": "RuneStone_Terminal/scripts/terminal.smoke.mjs" "check": "RuneStone_Terminal/scripts/terminal.smoke.mjs"
}, },
"RuneStone_BG_Slideshow/src/contracts.ts": { "RuneStone_Background_Slideshow/src/contracts.ts": {
"counts": { "counts": {
"action": 1 "action": 1
}, },
"design": "API type declaration, no renderer", "design": "API type declaration, no renderer",
"check": "pnpm check" "check": "pnpm check"
}, },
"RuneStone_BG_Slideshow/src/image-settings-ui.ts": { "RuneStone_Background_Slideshow/src/image-settings-ui.ts": {
"counts": { "counts": {
"action": 1, "action": 1,
"nativeChoice": 1, "nativeChoice": 1,
@@ -281,16 +281,16 @@
"localPopup": 3 "localPopup": 3
}, },
"design": "Host action menus and shared searchable image picker; native image select only on older hosts", "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": { "counts": {
"action": 1 "action": 1
}, },
"design": "Host action menus and shared searchable image picker; native image select only on older hosts", "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": { "counts": {
"action": 1, "action": 1,
"nativeChoice": 1 "nativeChoice": 1
@@ -305,12 +305,22 @@
"design": "Commit history listbox, not a popup menu", "design": "Commit history listbox, not a popup menu",
"check": "Source inspection: persistent history list retains its own layout" "check": "Source inspection: persistent history list retains its own layout"
}, },
"RuneStone_CSVViewer/src/index.js": { "RuneStone_CSV_Viewer/src/index.js": {
"counts": { "counts": {
"action": 1 "action": 1,
"picker": 1,
"localPopup": 5
}, },
"design": "Host action menus for columns, sorting, filter types, and operators", "design": "Shared action menus for sorting, filters, and header actions. Persistent searchable column visibility dialog uses rs-picker rows and shared surfaces.",
"check": "RuneStone_CSVViewer/tests/browser.mjs; tests/host.mjs" "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"
} }
} }
} }
+21 -29
View File
@@ -1,40 +1,32 @@
# Plugin names and source folders # Plugin names and source folders
Use these names in Settings, plugin manifests, help, and problem reports. Use these display names in Settings, manifests, help, and problem reports.
Use names without spaces for source folders and package metadata. 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 | | Display name | Source folder | Stable plugin ID |
| --- | --- | --- | --- | --- | | --- | --- | --- |
| Browser (built in) | `RuneStone/browser-runtime` | Not applicable | `runestone-browser` | `runestone.browser` (legacy) | | Browser (built in) | `RuneStone/browser-runtime` | `runestone.browser` (legacy) |
| Local Autocomplete | `RuneStone_LocalAutocomplete` | `RuneStone_LocalModel` | `runestone-local-autocomplete` | `runestone.local-autocomplete` | | Background Slideshow | `RuneStone_Background_Slideshow` | `runestone.bg-slideshow` |
| Project Management | `RuneStone_ProjectManagement` | `RuneStone_PM` | `runestone-project-management` | `runestone.pm` | | CSV Viewer | `RuneStone_CSV_Viewer` | `runestone.csv-viewer` |
| Git | `RuneStone_Git` | `runestone.git` |
## Manual source folder changes | Local Autocomplete | `RuneStone_Local_Autocomplete` | `runestone.local-autocomplete` |
| PDF Viewer | `RuneStone_PDF_Viewer` | `runestone.pdf-viewer` |
The remaining plugin folder changes need care because local tools and saved project paths can depend on them. | Project Management | `RuneStone_Project_Management` | `runestone.pm` |
Browser source now lives inside RuneStone and does not need a separate folder rename. | Table Formulas | `RuneStone_Table_Formulas` | `runestone.table-formulas` |
These changes remain pending. The current folders and repository URLs still use their earlier names. | Terminal | `RuneStone_Terminal` | `runestone.terminal` |
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.
## Stable package and data names ## Stable package and data names
Display names describe the plugins. Stable IDs connect installed packages to their settings and saved data. 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. The packager uses each stable plugin ID and version for the ZIP filename.
For example, Project Management keeps `runestone.pm-<version>.zip`. For example, Project Management uses `runestone.pm-<version>.zip`.
Do not rename published ZIP files or change plugin IDs as part of a display-name change. 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. Project Management retains `.runestone/pm/`, `runestone_pm`, and its preview storage key.
Existing view IDs, setting keys, and document IDs also stay unchanged. Existing view IDs and document IDs retain their names too.
These technical names preserve access to existing data and are not alternate product names.
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. The [plugin package reference](plugins.md) explains packaging and installation.
+30 -15
View File
@@ -4,18 +4,18 @@
RuneStone installs JavaScript plugins from local ZIP files and experimental Gitea release downloads. RuneStone installs JavaScript plugins from local ZIP files and experimental Gitea release downloads.
Open Settings → Plug-ins to install, enable, disable, or uninstall them. 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. 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. Terminal and Table Formulas use the same installed package system as all other plugins.
## Build and install the feature packages ## Build and install the feature packages
1. Clone `RuneStone_TableFormulas` beside RuneStone and run `pnpm install --frozen-lockfile` in that checkout. 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. 2. Run `pnpm build:plugins` from the RuneStone repository root for Table Formulas.
3. In Settings → Plug-ins, choose Install plugin ZIP. 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`. The build creates `runestone.table-formulas-<version>.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). 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. 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. 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. 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). 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`. 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. Install `releases/runestone.terminal-<version>.zip` through the same plugin ZIP installer.
Version 0.1.0 marks Terminal as a development package.
The local source folder is `../RuneStone_Terminal/` when both repositories share a parent directory. The local source folder is `../RuneStone_Terminal/` when both repositories share a parent directory.
No plugin starts automatically in a fresh installation. 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 | | Plugin | Package version |
| --- | --- | | --- | --- |
| Terminal | 0.1.0 | | Terminal | 0.1.0 |
| Table formulas | 0.1.0 | | Table Formulas | 0.1.0 |
| PDF viewer | 0.0.1 | | PDF Viewer | 0.0.1 |
| Project management | 0.2.3 | | Project management | 0.2.3 |
The authenticated check of the personal Gitea server found no releases in these four repositories. 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.id` | The installed plugin ID |
| `api.signal` | An abort signal triggered before shutdown | | `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 | | `contribute(key, value)` | Register a typed terminal or table formula contribution |
| `registerCommand({ id, title, run })` | Add a command to Commands in the toolbar | | `registerCommand({ id, title, run })` | Add a command to Commands in the toolbar |
| `registerCommand({ category: "open", ... })` | Add a launch action to Open tab or view | | `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.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.listMarkdown()` | Return sorted visible Markdown paths in one native request. Optional API |
| `workspace.read(path)` | Read a workspace text file | | `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.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.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 | | `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 | | `settings.subscribe(listener)` | Receive saved settings changes across windows. Optional API |
| `assets.read(path)` | Read package bytes as a `Uint8Array` | | `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. Command and view IDs must be unique within their respective plugin collections.
Plugin commands can supply an optional `icon` from the view icon set. Plugin commands can supply an optional `icon` from the shared action icon set in `src/lib/ui/actionIcons.ts`.
Use the same icon for the command and its view. Older hosts can ignore this field. 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. 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. Plugin configuration appears in Settings under the plugin name.
Register a view with `settings: true` to add its configuration page. 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. 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"`. The host calls `mount(container, context)` with `context.surface` set to `"settings"` or `"view"`.
Older hosts can omit the context argument. 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. 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. 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/registry.ts` / `contracts.ts` | Shared feature contributions and their types |
| `src/lib/plugins/TerminalSlot.svelte` | The host element for terminal controls | | `src/lib/plugins/TerminalSlot.svelte` | The host element for terminal controls |
| `../RuneStone_Terminal/src/` | Terminal plugin source in its own repository | | `../RuneStone_Terminal/src/` | Terminal plugin source in its own repository |
| `../RuneStone_TableFormulas/` | Table formulas source, unit tests, and package build | | `../RuneStone_Table_Formulas/` | Table Formulas source, unit tests, and package build |
| `scripts/buildPlugins.mjs` | Table formulas compilation and ZIP release in `../RuneStone_TableFormulas/releases/` | | `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 | | `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`. Run `pnpm build:plugins`, `pnpm check`, `pnpm test`, `pnpm build`, and `cargo test --manifest-path src-tauri/Cargo.toml --lib --offline`.
+5 -5
View File
@@ -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 [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. 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. External JavaScript packages can add commands and views. See the [plugin guide](plugins.md) for current boundaries.
## Workspace and files ## Workspace and files
@@ -49,7 +49,7 @@ External JavaScript packages can add commands and views. See the [plugin guide](
## Plugins ## 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. 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. 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. 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. - [ ] Add isolated execution and restricted permissions.
- [x] Move terminal views, shortcuts, settings, and desktop API calls into an external plugin package. - [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. - [ ] 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. - [ ] 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. - [ ] 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. 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. 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 ### Planned plugin lineup
+2 -2
View File
@@ -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. **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. 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. 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. 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, **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. 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? ## Why this order?
+7
View File
@@ -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 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 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`. 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 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. The workspace picker shares the menu surface. Labels and icons remain opaque.
See [UI-013](design-decisions.md#ui-013--translucent-menu-surfaces). 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
Settings navigation pairs icons with labels. Each settings page uses readable text and ordinary controls. 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. 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. 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. The app work area and Project Management keep separate background images and settings in every theme. Images can be up to 50 MiB.
+8 -1
View File
@@ -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. 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. 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. 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. 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. 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 → 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. 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. 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. 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. Uninstall removes the installed package after confirmation and retains its settings and workspace documents.
## Keyboard reference ## Keyboard reference
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "runestone", "name": "runestone",
"version": "0.1.34", "version": "0.1.36",
"description": "Desktop editor for a local workspace", "description": "Desktop editor for a local workspace",
"type": "module", "type": "module",
"scripts": { "scripts": {
+5 -5
View File
@@ -47,7 +47,7 @@ test('Character palettes restore one appearance and export readable surfaces and
const exported = exportAppearanceTheme(theme); const exported = exportAppearanceTheme(theme);
for (const mode of ['light', 'dark'] as const) { for (const mode of ['light', 'dark'] as const) {
assert.deepEqual(parseAppearance(JSON.stringify({ theme, mode })), { theme, mode: CHARACTER_THEMES[theme].mode }); 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 foreground of ['text', 'text-dim', 'text-strong', 'accent'] as const) {
for (const background of ['bg', 'bg-elevated', 'bg-active', 'selection'] as const) { for (const background of ['bg', 'bg-elevated', 'bg-active', 'selection'] as const) {
if (foreground === 'accent' && background === 'selection') continue; 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(themeModes(theme), [CHARACTER_THEMES[theme].mode]);
assert.deepEqual(exported.light, exported.dark); assert.equal(exported.schema, 2);
assert.deepEqual(parseCustomTheme(exported), exported); assert.deepEqual(parseCustomTheme(exported), exported);
for (const role of SYNTAX_ROLES) { for (const role of SYNTAX_ROLES) {
for (const background of ['bg', 'bg-active'] as const) { 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(new Set(SYNTAX_ROLES.map(role => exported.colors[`syntax-${role}`])).size >= 7);
assert.notDeepEqual(exported.dark, exportAppearanceTheme('default').dark); assert.notDeepEqual(exported.colors, exportAppearanceTheme('default').colors);
} }
}); });
test('Sakura cannot restore or save a dark appearance', () => { test('Sakura cannot restore or save a dark appearance', () => {
+125
View File
@@ -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 = '<img data-md-src="sample.png" alt="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 = '<div><table><tr><th>A</th><th>B</th></tr><tr><td>one</td><td>two</td></tr></table></div>'; 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(); }
+2 -2
View File
@@ -40,8 +40,8 @@ test('app override uses body properties and removes them without changing curren
const owner = Symbol(); const owner = Symbol();
hub.set(owner, 'app', frame); hub.set(owner, 'app', frame);
assert.match(properties.get('--rs-background-image')!, /blob:http/); assert.match(properties.get('--rs-background-image')!, /blob:http/);
assert.equal(properties.get('--rs-workarea-surface-opacity'), '82%'); assert.equal(properties.get('--rs-workarea-surface-opacity'), 'var(--rs-surface-opacity, 82%)');
assert.equal(properties.get('--rs-workarea-plugin-bg'), 'transparent'); assert.equal(properties.get('--rs-workarea-plugin-bg'), 'var(--rs-transparent-plugin-bg, transparent)');
root.set('--rs-background-image', 'new saved image'); root.set('--rs-background-image', 'new saved image');
hub.set(owner, 'app', { ...frame, overlay: -0.5, size: 'contain' }); hub.set(owner, 'app', { ...frame, overlay: -0.5, size: 'contain' });
assert.match(properties.get('--rs-background-image')!, /255,255,255,0.5/); assert.match(properties.get('--rs-background-image')!, /255,255,255,0.5/);
+2 -2
View File
@@ -5,12 +5,12 @@ import { fileURLToPath } from "node:url";
import { packagePlugin } from "./packagePlugin.mjs"; import { packagePlugin } from "./packagePlugin.mjs";
const root = fileURLToPath(new URL("../", import.meta.url)); 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"); const formulasBuild = resolve(formulasRoot, "scripts/build.mjs");
try { try {
await access(formulasBuild); await access(formulasBuild);
} catch { } 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" }); execFileSync(process.execPath, [formulasBuild], { cwd: formulasRoot, stdio: "inherit" });
const formulasOutput = resolve(root, "plugin-packages/table-formulas"); const formulasOutput = resolve(root, "plugin-packages/table-formulas");
+107 -11
View File
@@ -1,15 +1,111 @@
import { test } from "node:test"; import { test } from 'node:test';
import assert from "node:assert/strict"; import assert from 'node:assert/strict';
import { parseCustomTheme } from "../src/lib/theme/customThemes.ts"; 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 palette = { bg: '#123', text: '#abcdef', accent: '#AABBCC' };
const theme = { schema: 1, id: "my-theme", name: "My theme", light: palette, dark: palette }; const theme = { schema: 2, id: 'my-theme', name: 'My theme', colors: palette };
test("theme files accept explicit color tokens in both appearances", () => { test('Fixed theme palettes retain all supplied colors', () => {
assert.deepEqual(parseCustomTheme(theme), theme); assert.deepEqual(parseCustomTheme(theme), theme);
}); });
test("theme files reject CSS injection, unknown tokens, and incomplete palettes", () => { test('Legacy import selects the current appearance and validates both palettes', () => {
for (const dark of [{ ...palette, bg: "url(https://invalid.test)" }, { ...palette, position: "fixed" }, { bg: "#000" }, []]) { const light = { ...palette, bg: '#fff' };
assert.throws(() => parseCustomTheme({ ...theme, dark })); 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<string, string>();
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<string, string>();
const root = { dataset: {} as Record<string, string>, 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; }
}); });
+40
View File
@@ -2,6 +2,7 @@ import test from "node:test";
import assert from "node:assert/strict"; import assert from "node:assert/strict";
import { ExternalSession } from "../src/lib/plugins/externalSession.ts"; import { ExternalSession } from "../src/lib/plugins/externalSession.ts";
import type { PluginApi } from "../src/lib/plugins/sdk.ts"; import type { PluginApi } from "../src/lib/plugins/sdk.ts";
import { locale } from "../src/lib/i18n/index.ts";
function fixture() { function fixture() {
let writes = 0; let writes = 0;
const session = new ExternalSession("org.test.demo", { const session = new ExternalSession("org.test.demo", {
@@ -12,6 +13,25 @@ function fixture() {
return { session, writes: () => writes }; 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 () => { test("native Markdown discovery remains optional and is revoked on disable", async () => {
let api!: PluginApi; let api!: PluginApi;
let scans = 0; 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 Promise.resolve(); const stopping = session.stop(); done();
await assert.rejects(starting, /Late cleanup failed/); await assert.rejects(stopping, /Late cleanup failed/); 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();
});
+100
View File
@@ -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(); }
+75
View File
@@ -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<string>();
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: '<script>例.md</script>' }), '<script>例.md</script>を閉じる');
});
test('Language saves before reactive changes and syncs across windows', () => {
const stored = new Map<string, string>();
const events = new Map<string, Function>();
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, []);
});
+46 -1
View File
@@ -25,7 +25,10 @@ await page.addInitScript(() => {
if (command === "plugin:event|listen") { listeners.set(args.event, args.handler); return ++sequence; } if (command === "plugin:event|listen") { listeners.set(args.event, args.handler); return ++sequence; }
if (command === "plugin:event|unlisten") return; if (command === "plugin:event|unlisten") return;
if (command.startsWith("spelling_menu_")) { window.spellingTest.commands.push({ method: command, ...args }); 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_last_path") return root;
if (command === "workspace_open") return { root, name: "tab-menu-workspace", watch_mode: "native" }; 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); } 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"); await emitSpelling("new");
assert.deepEqual(await page.evaluate(() => window.spellingTest.commands.at(-1)), { method: "spelling_menu_select", request: "old", command: null }); assert.deepEqual(await page.evaluate(() => window.spellingTest.commands.at(-1)), { method: "spelling_menu_select", request: "old", command: null });
await dismiss(); 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.locator("#native-spelling-test").evaluate(node => node.remove());
await page.evaluate(() => { await page.evaluate(() => {
const input = document.createElement("input"); 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 }); 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.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 () => { await page.evaluate(async () => {
const { actionMenu } = await import("/src/lib/ui/actionMenu.ts"); const { actionMenu } = await import("/src/lib/ui/actionMenu.ts");
const root = actionMenu(418, 318, [ const root = actionMenu(418, 318, [
+1 -1
View File
@@ -3,7 +3,7 @@ import path from 'node:path';
import { fileURLToPath } from 'node:url'; import { fileURLToPath } from 'node:url';
const root = fileURLToPath(new URL('../', import.meta.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 = { const patterns = {
action: /\b(?:showActionMenu|actionMenu)\s*\(/g, action: /\b(?:showActionMenu|actionMenu)\s*\(/g,
svelteMenu: /<ContextMenu\b/g, svelteMenu: /<ContextMenu\b/g,
+35
View File
@@ -0,0 +1,35 @@
import assert from 'node:assert/strict';
import { test } from 'node:test';
import { locale } from '../src/lib/i18n/index.ts';
import { pluginTranslation } from '../src/lib/plugins/translation.ts';
test('Plugin messages use the host language, explicit catalogs, and safe fallbacks', () => {
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: '<b>User data</b>' }, { fr: { 'Column {name}': 'Colonne {name}' } }), 'Colonne <b>User data</b>');
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'); }
});
+28 -2
View File
@@ -10,7 +10,7 @@ page.on("pageerror", err => errors.push(err.message));
await page.addInitScript(() => { await page.addInitScript(() => {
window.isTauri = true; window.isTauri = true;
let current = "D:\\Notes"; let current = "D:\\Notes";
let recent = [current, "D:\\Writing\\Notes", "D:\\Missing"]; let recent = ["D:\\Writing\\Notes", current, "D:\\Missing"];
let picked = null; let picked = null;
let contents = "Original note"; let contents = "Original note";
const calls = []; const calls = [];
@@ -22,6 +22,7 @@ await page.addInitScript(() => {
calls.push({ command, args }); calls.push({ command, args });
if (command === "workspace_last_path") return current; if (command === "workspace_last_path") return current;
if (command === "workspace_recent") return recent; 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_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_read") { if (args.rel === "note.txt") return contents; throw "File not found"; }
if (command === "workspace_write") { contents = args.contents; return; } if (command === "workspace_write") { contents = args.contents; return; }
@@ -49,7 +50,7 @@ await page.addInitScript(() => {
}, },
}; };
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} }; 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 { try {
await page.goto(process.env.SMOKE_URL || "http://127.0.0.1:1420"); 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 trigger = page.getByRole("button", { name: "Open folder", exact: true });
const menu = page.getByRole("dialog", { name: "Workspaces", exact: true }); const menu = page.getByRole("dialog", { name: "Workspaces", exact: true });
await page.evaluate(() => window.__TEST__.reorder());
await trigger.click(); await trigger.click();
await menu.getByText("D:\\Writing\\Notes", { exact: true }).waitFor(); 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); 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" }); await page.screenshot({ path: ".audit/workspaces-menu.png" });
const opened = await page.evaluate(() => window.__TEST__.calls.filter(c => c.command === "workspace_open").length); 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…"); assert.equal(await page.locator(":focus").textContent(), " Open another folder…");
await page.keyboard.press("Escape"); await page.keyboard.press("Escape");
await menu.waitFor({ state: "hidden" }); 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 page.evaluate(() => window.__TEST__.clear());
await trigger.click(); await trigger.click();
await menu.getByText("No recent workspaces yet.").waitFor(); await menu.getByText("No recent workspaces yet.").waitFor();
+1 -1
View File
@@ -3130,7 +3130,7 @@ dependencies = [
[[package]] [[package]]
name = "runestone" name = "runestone"
version = "0.1.34" version = "0.1.36"
dependencies = [ dependencies = [
"base64 0.23.1", "base64 0.23.1",
"dunce", "dunce",
+2 -2
View File
@@ -1,6 +1,6 @@
[package] [package]
name = "runestone" name = "runestone"
version = "0.1.34" version = "0.1.36"
description = "Writing workspace plus script editor" description = "Writing workspace plus script editor"
authors = ["you"] authors = ["you"]
edition = "2021" edition = "2021"
@@ -44,4 +44,4 @@ panic = "abort"
strip = true strip = true
[package.metadata.runestone] [package.metadata.runestone]
version = "0.1.34" version = "0.1.36"
+2
View File
@@ -34,10 +34,12 @@ fn main() {
"workspace_open_window", "workspace_open_window",
"workspace_last_path", "workspace_last_path",
"workspace_recent", "workspace_recent",
"workspace_forget",
"workspace_new", "workspace_new",
"workspace_list", "workspace_list",
"workspace_list_markdown", "workspace_list_markdown",
"workspace_read", "workspace_read",
"workspace_read_many",
"workspace_read_bytes", "workspace_read_bytes",
"workspace_write", "workspace_write",
"workspace_create", "workspace_create",
+2
View File
@@ -43,10 +43,12 @@
"allow-workspace-open-window", "allow-workspace-open-window",
"allow-workspace-last-path", "allow-workspace-last-path",
"allow-workspace-recent", "allow-workspace-recent",
"allow-workspace-forget",
"allow-workspace-new", "allow-workspace-new",
"allow-workspace-list", "allow-workspace-list",
"allow-workspace-list-markdown", "allow-workspace-list-markdown",
"allow-workspace-read", "allow-workspace-read",
"allow-workspace-read-many",
"allow-workspace-read-bytes", "allow-workspace-read-bytes",
"allow-workspace-write", "allow-workspace-write",
"allow-workspace-create", "allow-workspace-create",
@@ -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"]
@@ -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"]
+2
View File
@@ -59,10 +59,12 @@ pub fn run() {
workspace::workspace_open_window, workspace::workspace_open_window,
workspace::workspace_last_path, workspace::workspace_last_path,
workspace::workspace_recent, workspace::workspace_recent,
workspace::workspace_forget,
workspace::workspace_new, workspace::workspace_new,
workspace::workspace_list, workspace::workspace_list,
workspace::workspace_list_markdown, workspace::workspace_list_markdown,
workspace::workspace_read, workspace::workspace_read,
workspace::workspace_read_many,
workspace::workspace_read_bytes, workspace::workspace_read_bytes,
workspace::workspace_write, workspace::workspace_write,
workspace::workspace_create, workspace::workspace_create,
+87 -37
View File
@@ -220,49 +220,79 @@ pub fn spelling_menu_uninstall(window: tauri::WebviewWindow) -> Result<(), Strin
#[derive(serde::Serialize)] #[derive(serde::Serialize)]
pub struct Suggestions { language: String, words: Vec<String>, misspelled: bool } pub struct Suggestions { language: String, words: Vec<String>, 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<Suggestions, String>;
type Request = (String, Vec<String>, bool, mpsc::SyncSender<Reply>);
static WORKER: OnceLock<mpsc::Sender<Request>> = OnceLock::new();
pub fn request(word: String, languages: Vec<String>, add: bool) -> Reply {
let worker = WORKER.get_or_init(|| {
let (send, receive) = mpsc::channel::<Request>();
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<ISpellCheckerFactory, String> = initialized.and_then(|_| CoCreateInstance(&SpellCheckerFactory, None, CLSCTX_INPROC_SERVER).map_err(|error| error.to_string()));
let mut checkers = HashMap::<String, ISpellChecker>::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] #[tauri::command]
pub async fn spelling_suggestions(word: String, languages: Vec<String>, add: Option<bool>) -> Result<Suggestions, String> { pub async fn spelling_suggestions(word: String, languages: Vec<String>, add: Option<bool>) -> Result<Suggestions, String> {
if word.is_empty() || word.len() > 256 || word.contains('\0') || languages.len() > 20 { if word.is_empty() || word.len() > 256 || word.contains('\0') || languages.len() > 20 {
return Err("Invalid spelling request.".into()); return Err("Invalid spelling request.".into());
} }
#[cfg(windows)] { #[cfg(windows)] {
tauri::async_runtime::spawn_blocking(move || -> Result<Suggestions, String> { tauri::async_runtime::spawn_blocking(move || suggestions_worker::request(word, languages, add.unwrap_or(false))).await.map_err(|error| error.to_string())?
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())?
} }
#[cfg(not(windows))] { let _ = (word, languages, add); Err("System spelling is unavailable.".into()) } #[cfg(not(windows))] { let _ = (word, languages, add); Err("System spelling is unavailable.".into()) }
} }
@@ -272,6 +302,26 @@ mod tests {
use super::*; use super::*;
use std::collections::HashSet; 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] #[test]
fn unrelated_browser_tools_are_removed_without_changing_editor_commands() { fn unrelated_browser_tools_are_removed_without_changing_editor_commands() {
for name in ["share", "writingDirection", "voiceTyping", "other"] { assert!(excluded_command(name, true)); } for name in ["share", "writingDirection", "voiceTyping", "other"] { assert!(excluded_command(name, true)); }
+82
View File
@@ -142,6 +142,22 @@ pub fn workspace_recent(app: AppHandle) -> WsResult<Vec<String>> {
Ok(load_workspace_history(&last_workspace_file(&app)?)) Ok(load_workspace_history(&last_workspace_file(&app)?))
} }
fn forget_workspace(path: &Path, root: &str) -> WsResult<Vec<String>> {
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<Vec<String>> {
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<PathBuf> { fn create_workspace_folder(parent: &str, name: &str) -> WsResult<PathBuf> {
let name = name.trim(); let name = name.trim();
let stem = name.split('.').next().unwrap_or("").to_ascii_uppercase(); let stem = name.split('.').next().unwrap_or("").to_ascii_uppercase();
@@ -575,6 +591,45 @@ fn read_optional_text(path: &Path, missing_ok: bool) -> WsResult<Option<String>>
} }
} }
#[derive(Debug, Serialize)]
pub struct TextRead {
path: String,
#[serde(skip_serializing_if = "Option::is_none")]
source: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
error: Option<String>,
}
fn read_many_text(root: &Path, paths: Vec<String>) -> WsResult<Vec<TextRead>> {
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<String> {
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<String>) -> WsResult<Vec<TextRead>> {
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; const MAX_BINARY_BYTES: u64 = 64 * 1024 * 1024;
fn read_workspace_bytes(root: &Path, rel: &str) -> WsResult<Vec<u8>> { fn read_workspace_bytes(root: &Path, rel: &str) -> WsResult<Vec<u8>> {
@@ -1268,6 +1323,33 @@ mod tests {
fs::remove_file(path).unwrap(); 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] #[test]
fn new_workspace_creates_only_a_new_child_folder() { fn new_workspace_creates_only_a_new_child_folder() {
let parent = std::env::temp_dir().join(format!("rs-new-workspace-{}", std::process::id())); let parent = std::env::temp_dir().join(format!("rs-new-workspace-{}", std::process::id()));
+1 -1
View File
@@ -1,7 +1,7 @@
{ {
"$schema": "https://schema.tauri.app/config/2", "$schema": "https://schema.tauri.app/config/2",
"productName": "RuneStone", "productName": "RuneStone",
"version": "0.1.34", "version": "0.1.36",
"identifier": "com.runestone.app", "identifier": "com.runestone.app",
"build": { "build": {
"beforeDevCommand": "pnpm dev", "beforeDevCommand": "pnpm dev",
+1
View File
@@ -1,4 +1,5 @@
<script lang="ts"> <script lang="ts">
import { t } from "$lib/i18n";
import { onMount } from 'svelte'; import { onMount } from 'svelte';
import Icon from '$lib/ui/Icon.svelte'; import Icon from '$lib/ui/Icon.svelte';
import IconButton from '$lib/ui/IconButton.svelte'; import IconButton from '$lib/ui/IconButton.svelte';
+43 -42
View File
@@ -1,4 +1,5 @@
<script lang="ts"> <script lang="ts">
import { t } from "$lib/i18n";
import { onMount, untrack, tick } from 'svelte'; import { onMount, untrack, tick } from 'svelte';
import IconButton from '$lib/ui/IconButton.svelte'; import IconButton from '$lib/ui/IconButton.svelte';
import Icon from '$lib/ui/Icon.svelte'; import Icon from '$lib/ui/Icon.svelte';
@@ -9,7 +10,7 @@
import { TabSession, type TabStatus } from './tabSession'; import { TabSession, type TabStatus } from './tabSession';
import { AutoScroll } from './autoScroll'; import { AutoScroll } from './autoScroll';
let { initial, onSessionChange, newTab }: { initial: { tabId?: string; profileId?: string; url?: string }; onSessionChange: (value: TabStatus) => void; newTab: (profileId: string, url?: string) => Promise<void> } = $props(); let { initial, onSessionChange, newTab }: { initial: { tabId?: string; profileId?: string; url?: string }; onSessionChange: (value: TabStatus) => void; newTab: (profileId: string, url?: string) => Promise<void> } = $props();
let status = $state<TabStatus>({ tabId: '', phase: 'connecting', message: 'Opening browser…' }); let status = $state<TabStatus>({ tabId: '', phase: 'connecting', message: $t('Opening browser…') });
const connection = new TabSession(request, untrack(() => initial), value => { status = value; onSessionChange(value); }); const connection = new TabSession(request, untrack(() => initial), value => { status = value; onSessionChange(value); });
const tabId = $derived(status.tabId); const tabId = $derived(status.tabId);
const ready = $derived(status.phase === 'ready'); const ready = $derived(status.phase === 'ready');
@@ -28,7 +29,7 @@
closeMenu?.(); closeMenu?.();
const anchor = event.currentTarget as HTMLButtonElement; const anchor = event.currentTarget as HTMLButtonElement;
const rect = anchor.getBoundingClientRect(); const rect = anchor.getBoundingClientRect();
closeMenu = showActionMenu({ x: rect.left, y: rect.bottom + 4, label: 'Browser profile', closeMenu = showActionMenu({ x: rect.left, y: rect.bottom + 4, label: $t('Browser profile'),
items: ($browserState?.profiles || []).map(profile => ({ label: profile.name, radio: true, items: ($browserState?.profiles || []).map(profile => ({ label: profile.name, radio: true,
checked: profile.id === current?.profileId, run: () => void openTab(profile.id) })) }).close; checked: profile.id === current?.profileId, run: () => void openTab(profile.id) })) }).close;
} }
@@ -92,30 +93,30 @@
const edit = (name: string) => () => { void orderedInput('edit', { action: name }); }; const edit = (name: string) => () => { void orderedInput('edit', { action: name }); };
const items: ActionMenuItem[] = []; const items: ActionMenuItem[] = [];
if (context.linkURL) items.push( if (context.linkURL) items.push(
{ label: 'Open link in new tab', icon: 'file-plus', run: () => void newTab(current?.profileId || 'user', context.linkURL) }, { label: $t('Open link in new tab'), icon: 'file-plus', run: () => void newTab(current?.profileId || 'user', context.linkURL) },
{ label: 'Open link in default browser', icon: 'external', run: action('openExternal') }, { label: $t('Open link in default browser'), icon: 'external', run: action('openExternal') },
{ label: 'Copy link address', icon: 'copy', run: action('copyLink') }, { label: $t('Copy link address'), icon: 'copy', run: action('copyLink') },
{ label: 'Save link as…', icon: 'save', run: action('saveLink') }, { separator: true }); { label: $t('Save link as…'), icon: 'save', run: action('saveLink') }, { separator: true });
if (context.hasImageContents) items.push( if (context.hasImageContents) items.push(
{ label: 'Save image as…', icon: 'save', disabled: !context.srcURL, run: action('saveImage') }, { label: $t('Save image as…'), icon: 'save', disabled: !context.srcURL, run: action('saveImage') },
{ label: 'Copy image', icon: 'copy', run: action('copyImage') }, { label: $t('Copy image'), icon: 'copy', run: action('copyImage') },
{ label: 'Copy image address', icon: 'copy', disabled: !context.srcURL, run: action('copyImageAddress') }, { separator: true }); { label: $t('Copy image address'), icon: 'copy', disabled: !context.srcURL, run: action('copyImageAddress') }, { separator: true });
if (context.isEditable) items.push( if (context.isEditable) items.push(
{ label: 'Undo', icon: 'undo', shortcut: 'Ctrl+Z', disabled: !context.editFlags.canUndo, run: edit('undo') }, { label: $t('Undo'), icon: 'undo', shortcut: 'Ctrl+Z', disabled: !context.editFlags.canUndo, run: edit('undo') },
{ label: 'Redo', icon: 'redo', shortcut: 'Ctrl+Shift+Z', disabled: !context.editFlags.canRedo, run: edit('redo') }, { separator: true }, { label: $t('Redo'), icon: 'redo', shortcut: 'Ctrl+Shift+Z', disabled: !context.editFlags.canRedo, run: edit('redo') }, { separator: true },
{ label: 'Cut', icon: 'cut', shortcut: 'Ctrl+X', disabled: !context.editFlags.canCut, run: edit('cut') }); { label: $t('Cut'), icon: 'cut', shortcut: 'Ctrl+X', disabled: !context.editFlags.canCut, run: edit('cut') });
if (context.isEditable || context.selectionText) items.push({ label: 'Copy', icon: 'copy', shortcut: 'Ctrl+C', disabled: !context.editFlags.canCopy, run: edit('copy') }); if (context.isEditable || context.selectionText) items.push({ label: $t('Copy'), icon: 'copy', shortcut: 'Ctrl+C', disabled: !context.editFlags.canCopy, run: edit('copy') });
if (context.isEditable) items.push( if (context.isEditable) items.push(
{ label: 'Paste', icon: 'paste', shortcut: 'Ctrl+V', disabled: !context.editFlags.canPaste, run: edit('paste') }, { label: $t('Paste'), icon: 'paste', shortcut: 'Ctrl+V', disabled: !context.editFlags.canPaste, run: edit('paste') },
{ label: 'Paste as plain text', icon: 'paste-text', shortcut: 'Ctrl+Shift+V', disabled: !context.editFlags.canPaste, run: edit('pasteAndMatchStyle') }, { label: $t('Paste as plain text'), icon: 'paste-text', shortcut: 'Ctrl+Shift+V', disabled: !context.editFlags.canPaste, run: edit('pasteAndMatchStyle') },
{ label: 'Select all', icon: 'task', shortcut: 'Ctrl+A', run: edit('selectAll') }, { separator: true }); { label: $t('Select all'), icon: 'task', shortcut: 'Ctrl+A', run: edit('selectAll') }, { separator: true });
items.push({ label: 'Back', icon: 'arrow-left', disabled: !current?.canBack, run: () => void send('back') }, items.push({ label: $t('Back'), icon: 'arrow-left', disabled: !current?.canBack, run: () => void send('back') },
{ label: 'Forward', icon: 'arrow-right', disabled: !current?.canForward, run: () => void send('forward') }, { label: $t('Forward'), icon: 'arrow-right', disabled: !current?.canForward, run: () => void send('forward') },
{ label: 'Reload', icon: 'refresh', run: () => void send('reload') }, { label: $t('Reload'), icon: 'refresh', run: () => void send('reload') },
{ label: 'Find in page', icon: 'search', shortcut: 'Ctrl+F', run: () => void find() }); { label: $t('Find in page'), icon: 'search', shortcut: 'Ctrl+F', run: () => void find() });
const rect = surface.getBoundingClientRect(); const rect = surface.getBoundingClientRect();
const menu = showActionMenu({ x: rect.left + context.x * rect.width / width, y: rect.top + context.y * rect.height / height, const menu = showActionMenu({ x: rect.left + context.x * rect.width / width, y: rect.top + context.y * rect.height / height,
items, label: 'Browser page actions' }); items, label: $t('Browser page actions') });
closeMenu = menu.close; closeMenu = menu.close;
} }
$effect(() => { if (mounted && ready && tabId) untrack(syncSize); }); $effect(() => { if (mounted && ready && tabId) untrack(syncSize); });
@@ -216,46 +217,46 @@
<svelte:document onvisibilitychange={() => { if (document.hidden) { stopScroll(); pageFocus(false); } else if (surface?.contains(document.activeElement)) pageFocus(true); }} /> <svelte:document onvisibilitychange={() => { if (document.hidden) { stopScroll(); pageFocus(false); } else if (surface?.contains(document.activeElement)) pageFocus(true); }} />
<div class="browser" class:blank data-browser-tab={tabId} data-browser-state={status.phase}> <div class="browser" class:blank data-browser-tab={tabId} data-browser-state={status.phase}>
<form class="toolbar" onsubmit={event => { event.preventDefault(); editing = false; void send('navigate', { input: address }); surface.focus(); }}> <form class="toolbar" onsubmit={event => { event.preventDefault(); editing = false; void send('navigate', { input: address }); surface.focus(); }}>
<IconButton icon="arrow-left" label="Back" disabled={!ready || !current?.canBack} onclick={() => void send('back')} /> <IconButton icon="arrow-left" label={$t("Back")} disabled={!ready || !current?.canBack} onclick={() => void send('back')} />
<IconButton icon="arrow-right" label="Forward" disabled={!ready || !current?.canForward} onclick={() => void send('forward')} /> <IconButton icon="arrow-right" label={$t("Forward")} disabled={!ready || !current?.canForward} onclick={() => void send('forward')} />
<IconButton icon={current?.loading ? 'stop' : 'refresh'} label={current?.loading ? 'Stop loading' : 'Reload'} disabled={!ready} onclick={() => void send(current?.loading ? 'stop' : 'reload')} /> <IconButton icon={current?.loading ? 'stop' : 'refresh'} label={current?.loading ? 'Stop loading' : $t('Reload')} disabled={!ready} onclick={() => void send(current?.loading ? 'stop' : 'reload')} />
<input bind:this={addressField} bind:value={address} disabled={!ready} onfocus={() => editing = true} onblur={() => editing = false} aria-label="Address or search" placeholder="Search or enter an address" spellcheck="false" autocomplete="off"> <input bind:this={addressField} bind:value={address} disabled={!ready} onfocus={() => editing = true} onblur={() => editing = false} aria-label={$t("Address or search")} placeholder={$t("Search or enter an address")} spellcheck="false" autocomplete="off">
<IconButton icon="bookmark" label="Bookmark this page" disabled={!ready || !current?.url.startsWith('http')} onclick={() => void send('bookmark')} /> <IconButton icon="bookmark" label={$t("Bookmark this page")} disabled={!ready || !current?.url.startsWith('http')} onclick={() => void send('bookmark')} />
<button type="button" class="profile-choice" aria-label="Browser profile" aria-haspopup="menu" disabled={opening} onclick={chooseProfile}> <button type="button" class="profile-choice" aria-label={$t("Browser profile")} aria-haspopup="menu" disabled={opening} onclick={chooseProfile}>
{$browserState?.profiles.find(profile => profile.id === current?.profileId)?.name ?? 'Profile'}<Icon icon="chevron-down" /> {$browserState?.profiles.find(profile => profile.id === current?.profileId)?.name ?? $t('Profile')}<Icon icon="chevron-down" />
</button> </button>
</form> </form>
{#if findOpen} {#if findOpen}
<!-- svelte-ignore a11y_no_noninteractive_element_interactions (Find controls share the Escape shortcut.) --> <!-- svelte-ignore a11y_no_noninteractive_element_interactions (Find controls share the Escape shortcut.) -->
<form class="findbar" role="search" aria-label="Find in page" onkeydown={findKey} onsubmit={event => { event.preventDefault(); search(true); }}> <form class="findbar" role="search" aria-label={$t("Find in page")} onkeydown={findKey} onsubmit={event => { event.preventDefault(); search(true); }}>
<input bind:this={findField} bind:value={findText} aria-label="Find in page" placeholder="Find in page" maxlength="1000" autocomplete="off" spellcheck="false" <input bind:this={findField} bind:value={findText} aria-label={$t("Find in page")} placeholder={$t("Find in page")} maxlength="1000" autocomplete="off" spellcheck="false"
disabled={!ready} oninput={() => { clearTimeout(findTimer); findTimer = setTimeout(() => search(), 120); }}> disabled={!ready} oninput={() => { clearTimeout(findTimer); findTimer = setTimeout(() => search(), 120); }}>
<span class="find-count" role="status" aria-live="polite">{!findText ? '' : !result || result.pending ? 'Searching…' : result.matches ? `${result.activeMatch} of ${result.matches}` : 'No matches'}</span> <span class="find-count" role="status" aria-live="polite">{!findText ? '' : !result || result.pending ? 'Searching…' : result.matches ? `${result.activeMatch} of ${result.matches}` : 'No matches'}</span>
<IconButton icon="up" label="Previous match (Shift+Enter)" disabled={!ready || !findText} onclick={() => search(true, false)} /> <IconButton icon="up" label={$t("Previous match (Shift+Enter)")} disabled={!ready || !findText} onclick={() => search(true, false)} />
<IconButton icon="down" label="Next match (Enter)" disabled={!ready || !findText} onclick={() => search(true)} /> <IconButton icon="down" label={$t("Next match (Enter)")} disabled={!ready || !findText} onclick={() => search(true)} />
<IconButton icon="close" label="Close find (Escape)" onclick={closeFind} /> <IconButton icon="close" label={$t("Close find (Escape)")} onclick={closeFind} />
</form> </form>
{/if} {/if}
{#if status.phase === 'connecting'}<p class="status" role="status">{status.message}</p>{/if} {#if status.phase === 'connecting'}<p class="status" role="status">{$t(status.message)}</p>{/if}
{#if ready && status.message}<p class="error" role="alert">{status.message}</p>{/if} {#if ready && status.message}<p class="error" role="alert">{$t(status.message)}</p>{/if}
{#if status.phase === 'disconnected'} {#if status.phase === 'disconnected'}
<div class="error" role="alert"><p>{status.message}</p><button class="reconnect" onclick={() => void connection.connect()}>Reconnect</button></div> <div class="error" role="alert"><p>{$t(status.message)}</p><button class="reconnect" onclick={() => void connection.connect()}>{$t("Reconnect")}</button></div>
{/if} {/if}
{#if status.detail} {#if status.detail}
<details class="diagnostics"><summary>Browser error details</summary><dl> <details class="diagnostics"><summary>{$t("Browser error details")}</summary><dl>
<dt>Operation</dt><dd>{status.detail.operation}</dd><dt>Reason</dt><dd>{status.detail.reason}</dd> <dt>{$t("Operation")}</dt><dd>{status.detail.operation}</dd><dt>{$t("Reason")}</dt><dd>{status.detail.reason}</dd>
<dt>Tab</dt><dd>{status.detail.tabId || 'Not created'}</dd><dt>Time</dt><dd>{status.detail.time}</dd> <dt>{$t("Tab")}</dt><dd>{status.detail.tabId || $t('Not created')}</dd><dt>{$t("Time")}</dt><dd>{status.detail.time}</dd>
<dt>Browser</dt><dd>Included with RuneStone</dd> <dt>{$t("Browser")}</dt><dd>{$t("Included with RuneStone")}</dd>
</dl></details> </dl></details>
{/if} {/if}
{#if openingError || $pageErrors[tabId]}<p class="error" role="alert">{openingError || $pageErrors[tabId]}</p>{/if} {#if openingError || $pageErrors[tabId]}<p class="error" role="alert">{openingError || $pageErrors[tabId]}</p>{/if}
<!-- svelte-ignore a11y_no_noninteractive_tabindex, a11y_no_noninteractive_element_interactions (This surface forwards native browser input.) --> <!-- svelte-ignore a11y_no_noninteractive_tabindex, a11y_no_noninteractive_element_interactions (This surface forwards native browser input.) -->
<div class="surface" class:autoscroll={!!scrollAnchor} bind:this={surface} role="application" aria-label="Web page" tabindex="0" <div class="surface" class:autoscroll={!!scrollAnchor} bind:this={surface} role="application" aria-label={$t("Web page")} tabindex="0"
onmousedown={event => pointer(event, 'mouseDown')} onmouseup={event => pointer(event, 'mouseUp')} onmousedown={event => pointer(event, 'mouseDown')} onmouseup={event => pointer(event, 'mouseUp')}
onmousemove={event => pointer(event, 'mouseMove')} onwheel={event => pointer(event, 'mouseWheel')} onmousemove={event => pointer(event, 'mouseMove')} onwheel={event => pointer(event, 'mouseWheel')}
onfocusin={() => pageFocus(true)} onfocusout={event => { if (!surface.contains(event.relatedTarget as Node | null)) pageFocus(false); }} onfocusin={() => pageFocus(true)} onfocusout={event => { if (!surface.contains(event.relatedTarget as Node | null)) pageFocus(false); }}
onkeydown={event => key(event, 'keyDown')} onkeyup={event => key(event, 'keyUp')} onblur={stopScroll} onmouseleave={stopScroll} onauxclick={event => event.preventDefault()} oncontextmenu={event => event.preventDefault()}> onkeydown={event => key(event, 'keyDown')} onkeyup={event => key(event, 'keyUp')} onblur={stopScroll} onmouseleave={stopScroll} onauxclick={event => event.preventDefault()} oncontextmenu={event => event.preventDefault()}>
<textarea class="text-input" bind:this={textInput} aria-label="Web page text input" autocomplete="off" spellcheck="false" <textarea class="text-input" bind:this={textInput} aria-label={$t("Web page text input")} autocomplete="off" spellcheck="false"
oncompositionstart={() => composing = true} oncompositionstart={() => composing = true}
oncompositionend={event => { composing = false; if (event.data) void orderedInput('insertText', { text: event.data }); textInput.value = ''; }} oncompositionend={event => { composing = false; if (event.data) void orderedInput('insertText', { text: event.data }); textInput.value = ''; }}
oninput={() => { if (!composing && textInput.value) { void orderedInput('insertText', { text: textInput.value }); textInput.value = ''; } }} oninput={() => { if (!composing && textInput.value) { void orderedInput('insertText', { text: textInput.value }); textInput.value = ''; } }}
+21 -20
View File
@@ -1,4 +1,5 @@
<script lang="ts"> <script lang="ts">
import { t } from "$lib/i18n";
import { onMount, onDestroy } from 'svelte'; import { onMount, onDestroy } from 'svelte';
import Icon from '$lib/ui/Icon.svelte'; import Icon from '$lib/ui/Icon.svelte';
import { showActionMenu } from '$lib/ui/managedActionMenu'; import { showActionMenu } from '$lib/ui/managedActionMenu';
@@ -14,7 +15,7 @@
closePicker(); closePicker();
const anchor = event.currentTarget as HTMLButtonElement; const anchor = event.currentTarget as HTMLButtonElement;
const bounds = anchor.getBoundingClientRect(); const bounds = anchor.getBoundingClientRect();
closePicker = showActionMenu({ x: bounds.left, y: bounds.bottom + 4, label: profile ? 'Profile' : 'Search engine', closePicker = showActionMenu({ x: bounds.left, y: bounds.bottom + 4, label: profile ? $t('Profile') : $t('Search engine'),
parent: anchor.closest('dialog') ?? undefined, parent: anchor.closest('dialog') ?? undefined,
items: (profile ? $browserState?.profiles || [] : engines).map(choice => ({ label: choice.name, items: (profile ? $browserState?.profiles || [] : engines).map(choice => ({ label: choice.name,
radio: true, checked: choice.id === (profile ? selected : search), radio: true, checked: choice.id === (profile ? selected : search),
@@ -26,15 +27,15 @@
homepage = value.settings.homepage || ''; filterLists = (value.settings.filterLists || []).join('\n'); ready = true; homepage = value.settings.homepage || ''; filterLists = (value.settings.filterLists || []).join('\n'); ready = true;
}).catch(error => message = String(error)); }); }).catch(error => message = String(error)); });
async function act(command: string, args: Record<string, unknown>) { async function act(command: string, args: Record<string, unknown>) {
try { const next = await request(command, args); message = 'Changes saved.'; return next; } catch (error) { message = String(error); return null; } try { const next = await request(command, args); message = $t('Changes saved.'); return next; } catch (error) { message = String(error); return null; }
} }
async function create(duplicate: boolean) { async function create(duplicate: boolean) {
if (!name.trim()) { message = 'Enter a profile name.'; return; } if (!name.trim()) { message = $t('Enter a profile name.'); return; }
const result = await act(duplicate ? 'duplicateProfile' : 'createProfile', duplicate ? { profileId: selected, name } : { name }); const result = await act(duplicate ? 'duplicateProfile' : 'createProfile', duplicate ? { profileId: selected, name } : { name });
if (result) { selected = result.profiles.at(-1)!.id; name = ''; } if (result) { selected = result.profiles.at(-1)!.id; name = ''; }
} }
async function save() { async function save() {
busy = true; message = 'Saving browser settings…'; busy = true; message = $t('Saving browser settings…');
try { try {
await act('settings', { search, adblock, linkDestination: internalLinks ? 'internal' : 'external', personalRules: rules, await act('settings', { search, adblock, linkDestination: internalLinks ? 'internal' : 'external', personalRules: rules,
homepage, filterLists: filterLists.split(/\r?\n/).map(value => value.trim()).filter(Boolean) }); homepage, filterLists: filterLists.split(/\r?\n/).map(value => value.trim()).filter(Boolean) });
@@ -42,30 +43,30 @@
} }
</script> </script>
<div class="settings"> <div class="settings">
<h2>Browser</h2><p>Choose how you browse within RuneStone.</p> <h2>{$t("Browser")}</h2><p>{$t("Choose how you browse within RuneStone.")}</p>
<h3>General</h3> <h3>{$t("General")}</h3>
<form onsubmit={event => { event.preventDefault(); if (ready && !busy) void save(); }}> <form onsubmit={event => { event.preventDefault(); if (ready && !busy) void save(); }}>
<fieldset disabled={!ready || busy}> <fieldset disabled={!ready || busy}>
<div class="card"> <div class="card">
<label class="row"><span>Open web links in RuneStone<small>Turn this off to use your system browser.</small></span><input class="switch" type="checkbox" role="switch" aria-label="Open web links in RuneStone" bind:checked={internalLinks}></label> <label class="row"><span>{$t("Open web links in RuneStone")}<small>{$t("Turn this off to use your system browser.")}</small></span><input class="switch" type="checkbox" role="switch" aria-label={$t("Open web links in RuneStone")} bind:checked={internalLinks}></label>
<label class="row"><span>Homepage<small>The page to open in each new browser tab. Leave blank for an empty page.</small></span><input class="address" type="url" aria-label="Homepage" placeholder="https://example.com" maxlength="8192" bind:value={homepage}></label> <label class="row"><span>{$t("Homepage")}<small>{$t("The page to open in each new browser tab. Leave blank for an empty page.")}</small></span><input class="address" type="url" aria-label={$t("Homepage")} placeholder="https://example.com" maxlength="8192" bind:value={homepage}></label>
<div class="row"><span>Search engine</span><button type="button" class="picker" aria-label="Search engine" aria-haspopup="menu" onclick={event => picker(event)}>{engines.find(engine => engine.id === search)?.name ?? 'DuckDuckGo'}<Icon icon="chevron-down" /></button></div> <div class="row"><span>{$t("Search engine")}</span><button type="button" class="picker" aria-label={$t("Search engine")} aria-haspopup="menu" onclick={event => picker(event)}>{engines.find(engine => engine.id === search)?.name ?? 'DuckDuckGo'}<Icon icon="chevron-down" /></button></div>
<label class="row"><span>Block ads and trackers<small>Apply the filter lists and personal rules to all browser tabs.</small></span><input class="switch" type="checkbox" role="switch" aria-label="Block ads and trackers" bind:checked={adblock}></label> <label class="row"><span>{$t("Block ads and trackers")}<small>{$t("Apply the filter lists and personal rules to all browser tabs.")}</small></span><input class="switch" type="checkbox" role="switch" aria-label={$t("Block ads and trackers")} bind:checked={adblock}></label>
<label class="row list-row"><span>Ad blocking lists<small>One HTTPS filter list URL per line, up to eight lists. New lists download when you save.</small></span><textarea aria-label="Ad blocking lists" rows="4" maxlength="66000" placeholder="https://easylist.to/easylist/easylist.txt" bind:value={filterLists}></textarea></label> <label class="row list-row"><span>{$t("Ad blocking lists")}<small>{$t("One HTTPS filter list URL per line, up to eight lists. New lists download when you save.")}</small></span><textarea aria-label={$t("Ad blocking lists")} rows="4" maxlength="66000" placeholder="https://easylist.to/easylist/easylist.txt" bind:value={filterLists}></textarea></label>
</div> </div>
<label class="rules">Personal filter rules<small>Use one rule per line. Block a domain with ||ads.example.com^, allow it with @@||ads.example.com^, or hide an element with example.com##.advertisement. Save to apply the rules.</small><textarea rows="4" maxlength="100000" placeholder={'! Block an advertising domain\n||ads.example.com^\n! Hide an element on one site\nexample.com##.advertisement'} bind:value={rules}></textarea></label> <label class="rules">{$t("Personal filter rules")}<small>{$t("Use one rule per line. Block a domain with ||ads.example.com^, allow it with @@||ads.example.com^, or hide an element with example.com##.advertisement. Save to apply the rules.")}</small><textarea rows="4" maxlength="100000" placeholder={'! Block an advertising domain\n||ads.example.com^\n! Hide an element on one site\nexample.com##.advertisement'} bind:value={rules}></textarea></label>
<button type="submit"><Icon icon="save" />{busy ? 'Saving…' : 'Save browser settings'}</button> <button type="submit"><Icon icon="save" />{busy ? $t('Saving…') : $t('Save browser settings')}</button>
</fieldset> </fieldset>
</form> </form>
<h3>Profiles</h3><p>New profiles start blank. Duplicate a profile to copy its stored browsing data and bookmarks.</p> <h3>{$t("Profiles")}</h3><p>{$t("New profiles start blank. Duplicate a profile to copy its stored browsing data and bookmarks.")}</p>
<div class="card profiles"> <div class="card profiles">
<div class="profile-choice"><span>Profile</span><button type="button" class="picker" aria-label="Profile" aria-haspopup="menu" disabled={!ready} onclick={event => picker(event, true)}>{$browserState?.profiles.find(profile => profile.id === selected)?.name ?? 'Profile'}<Icon icon="chevron-down" /></button></div> <div class="profile-choice"><span>{$t("Profile")}</span><button type="button" class="picker" aria-label={$t("Profile")} aria-haspopup="menu" disabled={!ready} onclick={event => picker(event, true)}>{$browserState?.profiles.find(profile => profile.id === selected)?.name ?? $t('Profile')}<Icon icon="chevron-down" /></button></div>
<label>New profile name<input bind:value={name} maxlength="60" placeholder="Profile name"></label> <label>{$t("New profile name")}<input bind:value={name} maxlength="60" placeholder={$t("Profile name")}></label>
<div class="actions"><button onclick={() => void create(false)}><Icon icon="plus" />New blank profile</button><button onclick={() => void create(true)}><Icon icon="copy" />Duplicate profile</button></div> <div class="actions"><button onclick={() => void create(false)}><Icon icon="plus" />{$t("New blank profile")}</button><button onclick={() => void create(true)}><Icon icon="copy" />{$t("Duplicate profile")}</button></div>
<p class="note">Duplication briefly restarts browser tabs. The copies remain separate. Agent permissions are not copied.</p> <p class="note">{$t("Duplication briefly restarts browser tabs. The copies remain separate. Agent permissions are not copied.")}</p>
</div> </div>
<h3>Web data</h3><p>Clear data for the selected profile. Its browser tabs will close. Bookmarks remain.</p> <h3>{$t("Web data")}</h3><p>{$t("Clear data for the selected profile. Its browser tabs will close. Bookmarks remain.")}</p>
<div class="actions"><button onclick={() => void act('clearData', { profileId: selected, kind: 'cache' })}>Clear cache</button><button onclick={() => void act('clearData', { profileId: selected, kind: 'cookies' })}>Clear cookies</button><button onclick={() => void act('clearData', { profileId: selected, kind: 'history' })}>Clear history</button></div> <div class="actions"><button onclick={() => void act('clearData', { profileId: selected, kind: 'cache' })}>{$t("Clear cache")}</button><button onclick={() => void act('clearData', { profileId: selected, kind: 'cookies' })}>{$t("Clear cookies")}</button><button onclick={() => void act('clearData', { profileId: selected, kind: 'history' })}>{$t("Clear history")}</button></div>
<p role="status">{message}</p> <p role="status">{message}</p>
{#if ready}<WebData profileId={selected} />{/if} {#if ready}<WebData profileId={selected} />{/if}
</div> </div>
+13 -12
View File
@@ -1,4 +1,5 @@
<script lang="ts"> <script lang="ts">
import { t } from "$lib/i18n";
import { onDestroy } from 'svelte'; import { onDestroy } from 'svelte';
import Icon from '$lib/ui/Icon.svelte'; import Icon from '$lib/ui/Icon.svelte';
import { showActionMenu } from '$lib/ui/managedActionMenu'; import { showActionMenu } from '$lib/ui/managedActionMenu';
@@ -14,9 +15,9 @@
function chooseKind(event: MouseEvent) { function chooseKind(event: MouseEvent) {
closePicker(); closePicker();
const anchor = event.currentTarget as HTMLButtonElement, rect = anchor.getBoundingClientRect(); const anchor = event.currentTarget as HTMLButtonElement, rect = anchor.getBoundingClientRect();
closePicker = showActionMenu({ x: rect.left, y: rect.bottom + 4, label: 'Web data type', closePicker = showActionMenu({ x: rect.left, y: rect.bottom + 4, label: $t('Web data type'),
parent: anchor.closest('dialog') ?? undefined, parent: anchor.closest('dialog') ?? undefined,
items: (['cookies', 'history'] as const).map(value => ({ label: value === 'cookies' ? 'Cookies' : 'History', items: (['cookies', 'history'] as const).map(value => ({ label: value === 'cookies' ? $t('Cookies') : $t('History'),
radio: true, checked: kind === value, run: () => kind = value })) }).close; radio: true, checked: kind === value, run: () => kind = value })) }).close;
} }
let generation = 0; let generation = 0;
@@ -36,22 +37,22 @@
finally { if (ticket === generation) busy = false; } finally { if (ticket === generation) busy = false; }
} }
</script> </script>
<section aria-label="Individual web data"> <section aria-label={$t("Individual web data")}>
<div class="toolbar"> <div class="toolbar">
<div class="choice"><span>Show</span><button type="button" aria-label="Web data type" aria-haspopup="menu" onclick={chooseKind}>{kind === 'cookies' ? 'Cookies' : 'History'}<Icon icon="chevron-down" /></button></div> <div class="choice"><span>{$t("Show")}</span><button type="button" aria-label={$t("Web data type")} aria-haspopup="menu" onclick={chooseKind}>{kind === 'cookies' ? $t('Cookies') : $t('History')}<Icon icon="chevron-down" /></button></div>
<label class="search">Filter<input type="search" aria-label="Filter web data" bind:value={query} placeholder="Search this profile"></label> <label class="search">{$t("Filter")}<input type="search" aria-label={$t("Filter web data")} bind:value={query} placeholder={$t("Search this profile")}></label>
<button disabled={busy} onclick={() => void refresh()}><Icon icon="refresh" />Refresh</button> <button disabled={busy} onclick={() => void refresh()}><Icon icon="refresh" />{$t("Refresh")}</button>
</div> </div>
<p>Remove individual entries for this profile. Open tabs stay open. Sites can create cookies again.</p> <p>{$t("Remove individual entries for this profile. Open tabs stay open. Sites can create cookies again.")}</p>
{#if error}<p role="alert">{error}</p>{/if} {#if error}<p role="alert">{error}</p>{/if}
{#if busy}<p role="status">Please wait…</p>{/if} {#if busy}<p role="status">{$t("Please wait…")}</p>{/if}
<div class="entries" aria-busy={busy}> <div class="entries" aria-busy={busy}>
{#if kind === 'cookies'} {#if kind === 'cookies'}
{#each cookies as cookie (cookie.id)}<div class="entry"><div><strong>{cookie.name || '(unnamed cookie)'}</strong><small>{cookie.domain} · {cookie.path}</small></div><button disabled={busy} aria-label={`Remove cookie ${cookie.name} from ${cookie.domain} at ${cookie.path}`} onclick={() => void remove('removeCookie', cookie.id)}><Icon icon="trash" />Remove</button></div>{/each} {#each cookies as cookie (cookie.id)}<div class="entry"><div><strong>{cookie.name || '(unnamed cookie)'}</strong><small>{cookie.domain} · {cookie.path}</small></div><button disabled={busy} aria-label={$t("Remove cookie {name} from {domain} at {path}", { name: cookie.name, domain: cookie.domain, path: cookie.path })} onclick={() => void remove('removeCookie', cookie.id)}><Icon icon="trash" />{$t("Remove")}</button></div>{/each}
{#if data && !cookies.length}<p>No matching cookies.</p>{/if} {#if data && !cookies.length}<p>{$t("No matching cookies.")}</p>{/if}
{:else} {:else}
{#each history as visit (visit.id)}<div class="entry"><div><strong>{visit.title || visit.url}</strong><small>{visit.url}</small><small>{new Date(visit.at).toLocaleString()}</small></div><button disabled={busy} aria-label={`Remove history entry ${visit.title || visit.url}`} onclick={() => void remove('removeHistory', visit.id)}><Icon icon="trash" />Remove</button></div>{/each} {#each history as visit (visit.id)}<div class="entry"><div><strong>{visit.title || visit.url}</strong><small>{visit.url}</small><small>{new Date(visit.at).toLocaleString()}</small></div><button disabled={busy} aria-label={$t("Remove history entry {name}", { name: visit.title || visit.url })} onclick={() => void remove('removeHistory', visit.id)}><Icon icon="trash" />{$t("Remove")}</button></div>{/each}
{#if data && !history.length}<p>No matching history.</p>{/if} {#if data && !history.length}<p>{$t("No matching history.")}</p>{/if}
{/if} {/if}
</div> </div>
</section> </section>
+3 -2
View File
@@ -1,4 +1,5 @@
<script lang="ts"> <script lang="ts">
import { t } from "$lib/i18n";
import { untrack } from "svelte"; import { untrack } from "svelte";
import type { Chrome, OpenBuffer } from "$lib/workspace/types"; import type { Chrome, OpenBuffer } from "$lib/workspace/types";
import { isMarkdownPath, imageFiles, hasFileDrag, imageInsertion, workspaceImageLink } from "$lib/workspace/media"; import { isMarkdownPath, imageFiles, hasFileDrag, imageInsertion, workspaceImageLink } from "$lib/workspace/media";
@@ -275,7 +276,7 @@
<div <div
class="monaco-host" class="monaco-host"
role="application" role="application"
aria-label="Editor" aria-label={$t("Editor")}
bind:this={host} bind:this={host}
ondragover={(event) => { ondragover={(event) => {
if (isMarkdownPath(buffer.relPath) && onInsertImage && hasFileDrag(event.dataTransfer)) { if (isMarkdownPath(buffer.relPath) && onInsertImage && hasFileDrag(event.dataTransfer)) {
@@ -290,7 +291,7 @@
void takeImages(event, event.clipboardData); void takeImages(event, event.clipboardData);
}} }}
></div> ></div>
{#if loadError}<p class="editor-notice" role="alert">{loadError}<button onclick={() => { loadError = null; }}>Dismiss</button></p>{/if} {#if loadError}<p class="editor-notice" role="alert">{loadError}<button onclick={() => { loadError = null; }}>{$t("Dismiss")}</button></p>{/if}
<style> <style>
.monaco-host { .monaco-host {
+14 -13
View File
@@ -1,4 +1,5 @@
<script lang="ts"> <script lang="ts">
import { t } from "$lib/i18n";
import { untrack } from "svelte"; import { untrack } from "svelte";
import { runScopeHandlers, type EditorView } from "@codemirror/view"; import { runScopeHandlers, type EditorView } from "@codemirror/view";
import { SearchQuery, closeSearchPanel, findNext, findPrevious, getSearchQuery, replaceAll, replaceNext, selectMatches, setSearchQuery } from "@codemirror/search"; import { SearchQuery, closeSearchPanel, findNext, findPrevious, getSearchQuery, replaceAll, replaceNext, selectMatches, setSearchQuery } from "@codemirror/search";
@@ -44,34 +45,34 @@
</script> </script>
<!-- svelte-ignore a11y_no_noninteractive_element_interactions (Handle shortcuts from the search controls.) --> <!-- svelte-ignore a11y_no_noninteractive_element_interactions (Handle shortcuts from the search controls.) -->
<section class="rs-find-bar" aria-label="Find and replace" onkeydown={keydown}> <section class="rs-find-bar" aria-label={$t("Find and replace")} onkeydown={keydown}>
<div class="rs-find-row"> <div class="rs-find-row">
<div class="rs-find-field"> <div class="rs-find-field">
<Icon icon="search" /> <Icon icon="search" />
<input type="text" name="search" {...{ "main-field": "true" }} aria-label="Find in document" placeholder="Find in document" <input type="text" name="search" {...{ "main-field": "true" }} aria-label={$t("Find in document")} placeholder={$t("Find in document")}
aria-invalid={searchText !== "" && !query.valid} bind:value={() => searchText, value => { searchText = value; commit(); }} /> aria-invalid={searchText !== "" && !query.valid} bind:value={() => searchText, value => { searchText = value; commit(); }} />
</div> </div>
<div class="rs-find-actions"> <div class="rs-find-actions">
<IconButton icon="up" label="Previous match (Shift+Enter)" onclick={() => findPrevious(view)} disabled={!query.valid} /> <IconButton icon="up" label={$t("Previous match (Shift+Enter)")} onclick={() => findPrevious(view)} disabled={!query.valid} />
<IconButton icon="down" label="Next match (Enter)" onclick={() => findNext(view)} disabled={!query.valid} /> <IconButton icon="down" label={$t("Next match (Enter)")} onclick={() => findNext(view)} disabled={!query.valid} />
<button class="rs-find-button" type="button" onclick={() => selectMatches(view)} disabled={!query.valid}>Select all</button> <button class="rs-find-button" type="button" onclick={() => selectMatches(view)} disabled={!query.valid}>{$t("Select all")}</button>
<IconButton icon="close" label="Close find (Escape)" onclick={() => closeSearchPanel(view)} /> <IconButton icon="close" label={$t("Close find (Escape)")} onclick={() => closeSearchPanel(view)} />
</div> </div>
</div> </div>
<div class="rs-find-options"> <div class="rs-find-options">
<label><input type="checkbox" bind:checked={() => caseSensitive, value => { caseSensitive = value; commit(); }} />Match case</label> <label><input type="checkbox" bind:checked={() => caseSensitive, value => { caseSensitive = value; commit(); }} />{$t("Match case")}</label>
<label><input type="checkbox" bind:checked={() => wholeWord, value => { wholeWord = value; commit(); }} />Whole word</label> <label><input type="checkbox" bind:checked={() => wholeWord, value => { wholeWord = value; commit(); }} />{$t("Whole word")}</label>
<label><input type="checkbox" bind:checked={() => regexp, value => { regexp = value; commit(); }} />Regex</label> <label><input type="checkbox" bind:checked={() => regexp, value => { regexp = value; commit(); }} />{$t("Regex")}</label>
{#if searchText && !query.valid}<span class="rs-find-error" role="status">Invalid expression</span>{/if} {#if searchText && !query.valid}<span class="rs-find-error" role="status">{$t("Invalid expression")}</span>{/if}
</div> </div>
{#if !view.state.readOnly} {#if !view.state.readOnly}
<div class="rs-find-row"> <div class="rs-find-row">
<div class="rs-find-field"> <div class="rs-find-field">
<input type="text" name="replace" aria-label="Replace with" placeholder="Replace with" bind:value={() => replacement, value => { replacement = value; commit(); }} /> <input type="text" name="replace" aria-label={$t("Replace with")} placeholder={$t("Replace with")} bind:value={() => replacement, value => { replacement = value; commit(); }} />
</div> </div>
<div class="rs-find-actions"> <div class="rs-find-actions">
<button class="rs-find-button" type="button" onclick={() => replaceNext(view)} disabled={!query.valid}>Replace</button> <button class="rs-find-button" type="button" onclick={() => replaceNext(view)} disabled={!query.valid}>{$t("Replace")}</button>
<button class="rs-find-button" type="button" onclick={() => replaceAll(view)} disabled={!query.valid}>Replace all</button> <button class="rs-find-button" type="button" onclick={() => replaceAll(view)} disabled={!query.valid}>{$t("Replace all")}</button>
</div> </div>
</div> </div>
{/if} {/if}
+4 -3
View File
@@ -1,4 +1,5 @@
<script lang="ts"> <script lang="ts">
import { t } from "$lib/i18n";
import { pluginHost } from "$lib/plugins/registry"; import { pluginHost } from "$lib/plugins/registry";
import { isSpellingTarget } from "./spellingMenu"; import { isSpellingTarget } from "./spellingMenu";
import { untrack } from "svelte"; import { untrack } from "svelte";
@@ -216,7 +217,7 @@
}), }),
imageDrops, imageDrops,
title.of(noteTitle(markdownTitle(current.relPath), onRenameTitle ? renameTitle : undefined)), title.of(noteTitle(markdownTitle(current.relPath), onRenameTitle ? renameTitle : undefined)),
EditorView.contentAttributes.of({ role: "textbox", "aria-label": "Writing editor", "aria-multiline": "true", spellcheck: "true" }), EditorView.contentAttributes.of({ role: "textbox", "aria-label": $t("Writing editor"), "aria-multiline": "true", spellcheck: "true" }),
EditorView.updateListener.of(update => { EditorView.updateListener.of(update => {
if (update.docChanged || update.selectionSet) { if (update.docChanged || update.selectionSet) {
menu?.close(false); menu?.close(false);
@@ -395,7 +396,7 @@
}); });
</script> </script>
<div class="live-writer" bind:this={host} role="application" aria-label="Markdown writing editor" <div class="live-writer" bind:this={host} role="application" aria-label={$t("Markdown writing editor")}
ondragovercapture={(event) => { ondragovercapture={(event) => {
if (!onInsertImage || !hasFileDrag(event.dataTransfer)) return; if (!onInsertImage || !hasFileDrag(event.dataTransfer)) return;
event.preventDefault(); event.preventDefault();
@@ -403,7 +404,7 @@
}} }}
ondropcapture={(event) => { if (editor) void insertImages(event, editor); }} ondropcapture={(event) => { if (editor) void insertImages(event, editor); }}
></div> ></div>
{#if error}<p class="editor-notice" role="alert">{error}<button onclick={() => { error = ""; }}>Dismiss</button></p>{/if} {#if error}<p class="editor-notice" role="alert">{error}<button onclick={() => { error = ""; }}>{$t("Dismiss")}</button></p>{/if}
<style> <style>
.live-writer { position: absolute; inset: 0; } .live-writer { position: absolute; inset: 0; }
+2 -1
View File
@@ -1,4 +1,5 @@
<script lang="ts"> <script lang="ts">
import { t } from "$lib/i18n";
import { untrack } from "svelte"; import { untrack } from "svelte";
import type { OpenBuffer } from "$lib/workspace/types"; import type { OpenBuffer } from "$lib/workspace/types";
import { workspaceReadDataUrl } from "$lib/workspace/api"; import { workspaceReadDataUrl } from "$lib/workspace/api";
@@ -228,7 +229,7 @@
<div <div
class="writer-host" class="writer-host"
role="application" role="application"
aria-label="Writer" aria-label={$t("Writer")}
bind:this={host} bind:this={host}
ondragover={(event) => { ondragover={(event) => {
if (imageFiles(event.dataTransfer).length > 0) { if (imageFiles(event.dataTransfer).length > 0) {
+10 -9
View File
@@ -1,3 +1,4 @@
import { tr } from '../i18n/index.ts';
import type { editor } from "monaco-editor"; import type { editor } from "monaco-editor";
import { actionMenu, type ActionMenuItem } from "../ui/actionMenu"; import { actionMenu, type ActionMenuItem } from "../ui/actionMenu";
@@ -36,19 +37,19 @@ export function codeMenu(view: editor.IStandaloneCodeEditor, report: (message: s
}; };
const run = (id: string) => { close(); void view.getAction(id)?.run(); }; const run = (id: string) => { close(); void view.getAction(id)?.run(); };
const items: ActionMenuItem[] = [ const items: ActionMenuItem[] = [
{ label: "Undo", icon: "undo", shortcut: "Ctrl+Z", disabled: !model.canUndo(), run: () => { close(); view.trigger("code-menu", "undo", null); } }, { label: tr("Undo"), icon: "undo", shortcut: "Ctrl+Z", disabled: !model.canUndo(), run: () => { close(); view.trigger("code-menu", "undo", null); } },
{ label: "Redo", icon: "redo", shortcut: "Ctrl+Shift+Z", disabled: !model.canRedo(), run: () => { close(); view.trigger("code-menu", "redo", null); } }, { label: tr("Redo"), icon: "redo", shortcut: "Ctrl+Shift+Z", disabled: !model.canRedo(), run: () => { close(); view.trigger("code-menu", "redo", null); } },
{ separator: true }, { separator: true },
{ label: "Change all occurrences", icon: "select", shortcut: "Ctrl+F2", disabled: !view.getAction("editor.action.changeAll")?.isSupported(), run: () => run("editor.action.changeAll") }, { label: tr("Change all occurrences"), icon: "select", shortcut: "Ctrl+F2", disabled: !view.getAction("editor.action.changeAll")?.isSupported(), run: () => run("editor.action.changeAll") },
{ separator: true }, { separator: true },
{ label: "Cut", icon: "cut", shortcut: "Ctrl+X", disabled: !selected, run: () => void clipboard("cut") }, { label: tr("Cut"), icon: "cut", shortcut: "Ctrl+X", disabled: !selected, run: () => void clipboard("cut") },
{ label: "Copy", icon: "copy", shortcut: "Ctrl+C", disabled: !selected, run: () => void clipboard("copy") }, { label: tr("Copy"), icon: "copy", shortcut: "Ctrl+C", disabled: !selected, run: () => void clipboard("copy") },
{ label: "Paste", icon: "paste", shortcut: "Ctrl+V", run: () => void clipboard("paste") }, { label: tr("Paste"), icon: "paste", shortcut: "Ctrl+V", run: () => void clipboard("paste") },
{ label: "Select all", icon: "select", shortcut: "Ctrl+A", run: () => { close(); view.setSelection(model.getFullModelRange()); } }, { label: tr("Select all"), icon: "select", shortcut: "Ctrl+A", run: () => { close(); view.setSelection(model.getFullModelRange()); } },
{ separator: true }, { separator: true },
{ label: "Command palette", icon: "terminal", shortcut: "F1", run: () => run("editor.action.quickCommand") }, { label: tr("Command palette"), icon: "terminal", shortcut: "F1", run: () => run("editor.action.quickCommand") },
]; ];
root = actionMenu(x, y, items, close, "Code text actions"); root = actionMenu(x, y, items, close, tr("Code text actions"));
} }
return { open, close, destroy() { return { open, close, destroy() {
close(false); close(false);
+4 -3
View File
@@ -1,3 +1,4 @@
import { tr } from '../i18n/index.ts';
import type MarkdownIt from "markdown-it"; import type MarkdownIt from "markdown-it";
import type { Token } from "markdown-it"; import type { Token } from "markdown-it";
type MarkdownParser = InstanceType<typeof MarkdownIt>; type MarkdownParser = InstanceType<typeof MarkdownIt>;
@@ -60,15 +61,15 @@ export function footnotes(markdown: MarkdownParser) {
markdown.renderer.rules.note_footnote_definition = () => ""; markdown.renderer.rules.note_footnote_definition = () => "";
markdown.renderer.rules.note_footnote_reference = (tokens, index) => { markdown.renderer.rules.note_footnote_reference = (tokens, index) => {
const { number, reference } = tokens[index].meta as { number: number; reference: number }; const { number, reference } = tokens[index].meta as { number: number; reference: number };
return `<sup class="md-footnote-ref"><a href="#rs-fn-${number}" id="rs-fnref-${number}-${reference}" data-footnote-link aria-label="Footnote ${number}">${number}</a></sup>`; return `<sup class="md-footnote-ref"><a href="#rs-fn-${number}" id="rs-fnref-${number}-${reference}" data-footnote-link aria-label="${markdown.utils.escapeHtml(tr('Footnote {number}', { number }))}">${number}</a></sup>`;
}; };
} }
export function renderFootnotes(markdown: MarkdownParser, env: FootnoteEnvironment): string { export function renderFootnotes(markdown: MarkdownParser, env: FootnoteEnvironment): string {
const notes = [...env.noteFootnotes?.values() ?? []].filter(note => note.number).sort((a, b) => a.number - b.number); const notes = [...env.noteFootnotes?.values() ?? []].filter(note => note.number).sort((a, b) => a.number - b.number);
if (!notes.length) return ""; if (!notes.length) return "";
return '<section class="md-footnotes" aria-label="Footnotes"><ol>' + notes.map(note => { return `<section class="md-footnotes" aria-label="${markdown.utils.escapeHtml(tr('Footnotes'))}"><ol>` + notes.map(note => {
const backlinks = Array.from({ length: note.references }, (_, index) => `<a href="#rs-fnref-${note.number}-${index + 1}" class="md-footnote-back" data-footnote-link aria-label="Back to reference ${note.number}${index ? `, occurrence ${index + 1}` : ""}" title="Back to reference">↩</a>`).join(" "); const backlinks = Array.from({ length: note.references }, (_, index) => `<a href="#rs-fnref-${note.number}-${index + 1}" class="md-footnote-back" data-footnote-link aria-label="${markdown.utils.escapeHtml(index ? tr('Back to reference {number}, occurrence {occurrence}', { number: note.number, occurrence: index + 1 }) : tr('Back to reference {number}', { number: note.number }))}" title="${markdown.utils.escapeHtml(tr('Back to reference'))}">↩</a>`).join(" ");
return `<li id="rs-fn-${note.number}" tabindex="-1">${markdown.renderer.render(note.tokens, markdown.options, env)} ${backlinks}</li>`; return `<li id="rs-fn-${note.number}" tabindex="-1">${markdown.renderer.render(note.tokens, markdown.options, env)} ${backlinks}</li>`;
}).join("") + "</ol></section>"; }).join("") + "</ol></section>";
} }
+3 -2
View File
@@ -1,3 +1,4 @@
import { tr } from '../i18n/index.ts';
import { StateField, type EditorState, type Range } from "@codemirror/state"; import { StateField, type EditorState, type Range } from "@codemirror/state";
import { Decoration, EditorView, WidgetType, keymap } from "@codemirror/view"; import { Decoration, EditorView, WidgetType, keymap } from "@codemirror/view";
import { codeFolding, foldEffect, foldKeymap, foldedRanges, foldService, syntaxTree, unfoldEffect } from "@codemirror/language"; import { codeFolding, foldEffect, foldKeymap, foldedRanges, foldService, syntaxTree, unfoldEffect } from "@codemirror/language";
@@ -29,7 +30,7 @@ export function headingButton(label: string, collapsed: boolean): HTMLButtonElem
button.type = "button"; button.type = "button";
button.className = "rs-heading-toggle"; button.className = "rs-heading-toggle";
button.setAttribute("aria-expanded", String(!collapsed)); button.setAttribute("aria-expanded", String(!collapsed));
const title = `${collapsed ? "Expand" : "Collapse"} ${label || "heading"}`; const title = tr(collapsed ? "Expand {name}" : "Collapse {name}", { name: label || tr("heading") });
button.setAttribute("aria-label", title); button.setAttribute("aria-label", title);
tooltipCleanups.set(button, attachTooltip(button, () => button.getAttribute("aria-label") || "")); tooltipCleanups.set(button, attachTooltip(button, () => button.getAttribute("aria-label") || ""));
const icon = actionIcon("chevron"); const icon = actionIcon("chevron");
@@ -100,7 +101,7 @@ export function readerHeadingFolding(root: HTMLElement, collapsed: Set<string>)
headings.forEach(item => { headings.forEach(item => {
const button = item.heading.querySelector<HTMLButtonElement>(".rs-heading-toggle"); const button = item.heading.querySelector<HTMLButtonElement>(".rs-heading-toggle");
if (button) { if (button) {
const label = `${collapsed.has(item.key) ? "Expand" : "Collapse"} ${item.label}`; const label = tr(collapsed.has(item.key) ? "Expand {name}" : "Collapse {name}", { name: item.label });
button.setAttribute("aria-expanded", String(!collapsed.has(item.key))); button.setAttribute("aria-expanded", String(!collapsed.has(item.key)));
button.setAttribute("aria-label", label); button.setAttribute("aria-label", label);
+21 -20
View File
@@ -1,3 +1,4 @@
import { tr } from '../i18n/index.ts';
import { actionIcon, type ActionIcon } from "../ui/actionIcons"; import { actionIcon, type ActionIcon } from "../ui/actionIcons";
import { attachTooltip } from "../ui/tooltip"; import { attachTooltip } from "../ui/tooltip";
const tooltipCleanups = new WeakMap<HTMLElement, () => void>(); const tooltipCleanups = new WeakMap<HTMLElement, () => void>();
@@ -43,12 +44,12 @@ function button(label: string, icon: ActionIcon, action: () => void) {
function zoomImage(original: HTMLImageElement, trigger: HTMLButtonElement) { function zoomImage(original: HTMLImageElement, trigger: HTMLButtonElement) {
const dialog = document.createElement("dialog"); const dialog = document.createElement("dialog");
dialog.className = "image-lightbox"; dialog.className = "image-lightbox";
dialog.setAttribute("aria-label", "Image zoom"); dialog.setAttribute("aria-label", tr("Image zoom"));
const header = document.createElement("div"); const header = document.createElement("div");
header.className = "image-lightbox-toolbar"; header.className = "image-lightbox-toolbar";
const name = document.createElement("span"); const name = document.createElement("span");
name.className = "image-lightbox-name"; name.className = "image-lightbox-name";
name.textContent = original.dataset.mdSrc || original.alt || "Image"; name.textContent = original.dataset.mdSrc || original.alt || tr("Image");
const viewport = document.createElement("div"); const viewport = document.createElement("div");
viewport.className = "image-lightbox-viewport"; viewport.className = "image-lightbox-viewport";
const image = original.cloneNode() as HTMLImageElement; const image = original.cloneNode() as HTMLImageElement;
@@ -62,14 +63,14 @@ function zoomImage(original: HTMLImageElement, trigger: HTMLButtonElement) {
scale = next; scale = next;
image.style.width = scale ? `${image.naturalWidth * scale}px` : ""; image.style.width = scale ? `${image.naturalWidth * scale}px` : "";
viewport.classList.toggle("is-zoomed", scale > 0); viewport.classList.toggle("is-zoomed", scale > 0);
status.textContent = scale ? `${Math.round(scale * 100)}%` : "Fit"; status.textContent = scale ? `${Math.round(scale * 100)}%` : tr("Fit");
zoomOut.disabled = scale === 0; zoomOut.disabled = scale === 0;
zoomIn.disabled = scale >= 4; zoomIn.disabled = scale >= 4;
} }
const zoomOut = button("Zoom out", "zoom-out", () => resize(scale <= .5 ? 0 : scale / 2)); const zoomOut = button(tr("Zoom out"), "zoom-out", () => resize(scale <= .5 ? 0 : scale / 2));
const zoomIn = button("Zoom in", "zoom-in", () => resize(scale ? Math.min(4, scale * 2) : 1)); const zoomIn = button(tr("Zoom in"), "zoom-in", () => resize(scale ? Math.min(4, scale * 2) : 1));
const fit = button("Fit image", "select", () => resize(0)); const fit = button(tr("Fit image"), "select", () => resize(0));
const close = button("Close image", "close", () => dialog.close()); const close = button(tr("Close image"), "close", () => dialog.close());
header.append(name, zoomOut, status, zoomIn, fit, close); header.append(name, zoomOut, status, zoomIn, fit, close);
viewport.append(image); viewport.append(image);
dialog.append(header, viewport); dialog.append(header, viewport);
@@ -93,17 +94,17 @@ export function imageControls(root: HTMLElement, actions: ImageActions = {}, mea
frame.contentEditable = "false"; frame.contentEditable = "false";
frame.tabIndex = 0; frame.tabIndex = 0;
frame.setAttribute("role", "group"); frame.setAttribute("role", "group");
frame.setAttribute("aria-label", `Image: ${image.alt || image.dataset.mdSrc || "image"}`); frame.setAttribute("aria-label", tr("Image: {name}", { name: image.alt || image.dataset.mdSrc || tr("Image") }));
image.replaceWith(frame); image.replaceWith(frame);
frame.append(image); frame.append(image);
image.draggable = false; image.draggable = false;
const toolbar = document.createElement("span"); const toolbar = document.createElement("span");
toolbar.className = "md-image-actions"; toolbar.className = "md-image-actions";
let closeZoom: (() => void) | undefined; let closeZoom: (() => void) | undefined;
const zoom = button("Zoom in", "zoom-in", () => { closeZoom = zoomImage(image, zoom); }); const zoom = button(tr("Zoom in"), "zoom-in", () => { closeZoom = zoomImage(image, zoom); });
cleanup.push(() => closeZoom?.()); cleanup.push(() => closeZoom?.());
toolbar.append(zoom); toolbar.append(zoom);
if (actions.edit) toolbar.append(button(actions.editing ? "Hide image source" : "Edit image source", "code", actions.editing && actions.done ? actions.done : actions.edit)); if (actions.edit) toolbar.append(button(actions.editing ? tr("Hide image source") : tr("Edit image source"), "code", actions.editing && actions.done ? actions.done : actions.edit));
frame.append(toolbar); frame.append(toolbar);
cleanup.push(() => toolbar.querySelectorAll<HTMLButtonElement>("button").forEach(button => tooltipCleanups.get(button)?.())); cleanup.push(() => toolbar.querySelectorAll<HTMLButtonElement>("button").forEach(button => tooltipCleanups.get(button)?.()));
let menu: HTMLElement | undefined; let menu: HTMLElement | undefined;
@@ -125,19 +126,19 @@ export function imageControls(root: HTMLElement, actions: ImageActions = {}, mea
function openMenu(x: number, y: number) { function openMenu(x: number, y: number) {
closeMenu(false); select(); closeMenu(false); select();
const items: ActionMenuItem[] = [ const items: ActionMenuItem[] = [
{ label: "Copy image", icon: "copy", run: () => void run(() => copyImage(image)) }, { label: tr("Copy image"), icon: "copy", run: () => void run(() => copyImage(image)) },
...(actions.markdown ? [{ label: "Copy Markdown", icon: "code" as const, run: () => void run(() => navigator.clipboard.writeText(actions.markdown!())) }] : []), ...(actions.markdown ? [{ label: tr("Copy Markdown"), icon: "code" as const, run: () => void run(() => navigator.clipboard.writeText(actions.markdown!())) }] : []),
...(actions.swap ? [{ label: "Swap image…", icon: "swap" as const, run: () => void run(() => actions.swap!(image)) }] : []), ...(actions.swap ? [{ label: tr("Swap image…"), icon: "swap" as const, run: () => void run(() => actions.swap!(image)) }] : []),
...(actions.remove ? [{ label: "Remove image", icon: "trash" as const, run: () => void run(actions.remove!) }] : []), ...(actions.remove ? [{ label: tr("Remove image"), icon: "trash" as const, run: () => void run(actions.remove!) }] : []),
{ separator: true }, { separator: true },
{ label: "Zoom in", icon: "zoom-in", run: () => { closeMenu(false); closeZoom = zoomImage(image, zoom); } }, { label: tr("Zoom in"), icon: "zoom-in", run: () => { closeMenu(false); closeZoom = zoomImage(image, zoom); } },
...(actions.edit ? [{ label: "Edit image source", icon: "code" as const, run: () => void run(actions.edit!) }] : []), ...(actions.edit ? [{ label: tr("Edit image source"), icon: "code" as const, run: () => void run(actions.edit!) }] : []),
...(actions.open ? [{ label: "Open in new tab", icon: "external" as const, run: () => void run(() => actions.open!(image)) }] : []), ...(actions.open ? [{ label: tr("Open in new tab"), icon: "external" as const, run: () => void run(() => actions.open!(image)) }] : []),
{ label: "Copy path", icon: "link", run: () => void run(() => navigator.clipboard.writeText(image.dataset.mdSrc || "")) }, { label: tr("Copy path"), icon: "link", run: () => void run(() => navigator.clipboard.writeText(image.dataset.mdSrc || "")) },
...(actions.reveal && !/^https?:/i.test(image.dataset.mdSrc || "") ? [{ label: "Show in Explorer", icon: "external" as const, run: () => void run(() => actions.reveal!(image)) }] : []), ...(actions.reveal && !/^https?:/i.test(image.dataset.mdSrc || "") ? [{ label: tr("Show in Explorer"), icon: "external" as const, run: () => void run(() => actions.reveal!(image)) }] : []),
]; ];
openingMenu = true; openingMenu = true;
try { menu = actionMenu(x, y, items, closeMenu, "Image actions"); } try { menu = actionMenu(x, y, items, closeMenu, tr("Image actions")); }
finally { openingMenu = false; } finally { openingMenu = false; }
} }
frame.addEventListener("mousedown", event => { if (!(event.target as Element).closest("button")) { event.preventDefault(); event.stopPropagation(); select(); } }); frame.addEventListener("mousedown", event => { if (!(event.target as Element).closest("button")) { event.preventDefault(); event.stopPropagation(); select(); } });
+4 -3
View File
@@ -1,3 +1,4 @@
import { tr } from '../i18n/index.ts';
import { EditorView, WidgetType } from "@codemirror/view"; import { EditorView, WidgetType } from "@codemirror/view";
import { isolateHistory } from "@codemirror/commands"; import { isolateHistory } from "@codemirror/commands";
import { imageControls, type ImageActions } from "./imageControls"; import { imageControls, type ImageActions } from "./imageControls";
@@ -48,9 +49,9 @@ export class ImagePreview extends WidgetType {
report: this.context.report, report: this.context.report,
swap: async image => { swap: async image => {
const before = view.state.doc; const before = view.state.doc;
const path = (await requestText("Image path relative to this note, or https URL", image.dataset.mdSrc || ""))?.trim(); const path = (await requestText(tr("Image path relative to this note, or https URL"), image.dataset.mdSrc || ""))?.trim();
if (!path || !dom.isConnected || view.state.doc !== before) return; if (!path || !dom.isConnected || view.state.doc !== before) return;
if (!isRemoteImage(path) && /^[a-z][a-z\d+.-]*:/i.test(path)) throw new Error("Choose a workspace image path or an http/https URL."); if (!isRemoteImage(path) && /^[a-z][a-z\d+.-]*:/i.test(path)) throw new Error(tr("Choose a workspace image path or an http/https URL."));
await this.context.validate?.(path); await this.context.validate?.(path);
if (!dom.isConnected || view.state.doc !== before) return; if (!dom.isConnected || view.state.doc !== before) return;
const target = path.replace(/[<>\s]/g, char => encodeURIComponent(char)); const target = path.replace(/[<>\s]/g, char => encodeURIComponent(char));
@@ -63,7 +64,7 @@ export class ImagePreview extends WidgetType {
if (!dom.querySelector("img")) { if (!dom.querySelector("img")) {
const edit = document.createElement("button"); const edit = document.createElement("button");
edit.type = "button"; edit.className = "image-action"; edit.type = "button"; edit.className = "image-action";
const label = this.editing ? "Hide image source" : "Edit image source"; const label = this.editing ? tr("Hide image source") : tr("Edit image source");
edit.setAttribute("aria-label", label); edit.dataset.editorTooltip = label; edit.setAttribute("aria-label", label); edit.dataset.editorTooltip = label;
edit.append(actionIcon("code")); edit.append(actionIcon("code"));
edit.addEventListener("click", event => { event.preventDefault(); event.stopPropagation(); (this.editing ? actions.done : actions.edit)?.(); }); edit.addEventListener("click", event => { event.preventDefault(); event.stopPropagation(); (this.editing ? actions.done : actions.edit)?.(); });
+7 -6
View File
@@ -1,3 +1,4 @@
import { tr } from '../i18n/index.ts';
import type { ActionMenuItem } from "../ui/actionMenu"; import type { ActionMenuItem } from "../ui/actionMenu";
export type MenuLink = { kind: "md" | "wiki"; target: string }; export type MenuLink = { kind: "md" | "wiki"; target: string };
@@ -15,16 +16,16 @@ export function linkMenuItems(link: MenuLink, actions: DocumentLinkActions, clos
}; };
const external = /^(https?:\/\/|mailto:)/i.test(link.target); const external = /^(https?:\/\/|mailto:)/i.test(link.target);
const items: ActionMenuItem[] = external ? [ const items: ActionMenuItem[] = external ? [
...(actions.browser && /^https?:\/\//i.test(link.target) ? [{ label: "Open link in app browser", icon: "globe" as const, run: run(() => actions.browser!(link.target)) }] : []), ...(actions.browser && /^https?:\/\//i.test(link.target) ? [{ label: tr("Open link in app browser"), icon: "globe" as const, run: run(() => actions.browser!(link.target)) }] : []),
...(actions.defaultBrowser ? [{ label: "Open link in default browser", icon: "external" as const, run: run(() => actions.defaultBrowser!(link.target)) }] : []), ...(actions.defaultBrowser ? [{ label: tr("Open link in default browser"), icon: "external" as const, run: run(() => actions.defaultBrowser!(link.target)) }] : []),
] : []; ] : [];
if (!items.length && actions.open) items.push({ label: external ? "Open link" : "Open in new tab", icon: external ? "external" : "file-plus", run: run(() => actions.open!(link)) }); if (!items.length && actions.open) items.push({ label: external ? tr("Open link") : tr("Open in new tab"), icon: external ? "external" : "file-plus", run: run(() => actions.open!(link)) });
if (!external && actions.workspaceItems) { if (!external && actions.workspaceItems) {
const wrap = (item: ActionMenuItem): ActionMenuItem => "separator" in item ? item : { ...item, run: item.run ? run(item.run) : undefined, children: item.children?.map(wrap) }; const wrap = (item: ActionMenuItem): ActionMenuItem => "separator" in item ? item : { ...item, run: item.run ? run(item.run) : undefined, children: item.children?.map(wrap) };
const workspaceItems = actions.workspaceItems(link).filter(item => !edit || "separator" in item || !["Rename…", "Move file to…", "Open in default app"].includes(item.label)); const workspaceItems = actions.workspaceItems(link).filter(item => !edit || "separator" in item || ![tr("Rename…"), tr("Move file to…"), tr("Open in default app")].includes(item.label));
items.push(...workspaceItems.map(wrap)); items.push(...workspaceItems.map(wrap));
} }
items.push({ label: external ? "Copy URL" : "Copy link target", icon: "link", run: run(() => navigator.clipboard.writeText(link.target)) }); items.push({ label: external ? tr("Copy URL") : tr("Copy link target"), icon: "link", run: run(() => navigator.clipboard.writeText(link.target)) });
if (edit) items.push({ label: "Edit link", icon: "rename", run: () => { close(); edit(); } }); if (edit) items.push({ label: tr("Edit link"), icon: "rename", run: () => { close(); edit(); } });
return items; return items;
} }
+8 -7
View File
@@ -1,3 +1,4 @@
import { tr } from '../i18n/index.ts';
import { StateEffect, StateField, type EditorState, type Range } from "@codemirror/state"; import { StateEffect, StateField, type EditorState, type Range } from "@codemirror/state";
import { Decoration, EditorView, ViewPlugin, WidgetType, type DecorationSet } from "@codemirror/view"; import { Decoration, EditorView, ViewPlugin, WidgetType, type DecorationSet } from "@codemirror/view";
import { syntaxTree, foldedRanges, foldEffect, unfoldEffect } from "@codemirror/language"; import { syntaxTree, foldedRanges, foldEffect, unfoldEffect } from "@codemirror/language";
@@ -40,8 +41,8 @@ class CodeCopy extends WidgetType {
const button = document.createElement("button"); const button = document.createElement("button");
button.type = "button"; button.type = "button";
button.className = "rs-fence-copy writer-code-copy"; button.className = "rs-fence-copy writer-code-copy";
button.setAttribute("aria-label", "Copy code"); button.setAttribute("aria-label", tr("Copy code"));
button.dataset.editorTooltip = "Copy code"; button.dataset.editorTooltip = tr("Copy code");
button.append(actionIcon("copy")); button.append(actionIcon("copy"));
button.onmousedown = event => event.preventDefault(); button.onmousedown = event => event.preventDefault();
button.onclick = async event => { button.onclick = async event => {
@@ -49,11 +50,11 @@ class CodeCopy extends WidgetType {
try { try {
await navigator.clipboard.writeText(this.code); await navigator.clipboard.writeText(this.code);
button.dataset.copied = "true"; button.dataset.copied = "true";
button.dataset.editorTooltip = "Copied"; button.dataset.editorTooltip = tr("Copied");
button.setAttribute("aria-label", "Code copied"); button.setAttribute("aria-label", tr("Code copied"));
} catch { } catch {
button.dataset.editorTooltip = "Could not copy code"; button.dataset.editorTooltip = tr("Could not copy code");
button.setAttribute("aria-label", "Could not copy code"); button.setAttribute("aria-label", tr("Could not copy code"));
} }
}; };
return button; return button;
@@ -86,7 +87,7 @@ class Checkbox extends WidgetType {
box.type = "checkbox"; box.type = "checkbox";
box.checked = this.checked; box.checked = this.checked;
box.className = "writer-checkbox"; box.className = "writer-checkbox";
box.setAttribute("aria-label", this.checked ? "Mark task incomplete" : "Mark task complete"); box.setAttribute("aria-label", this.checked ? tr("Mark task incomplete") : tr("Mark task complete"));
box.addEventListener("mousedown", event => event.preventDefault()); box.addEventListener("mousedown", event => event.preventDefault());
box.addEventListener("click", event => { box.addEventListener("click", event => {
event.stopPropagation(); event.stopPropagation();
+25 -24
View File
@@ -1,3 +1,4 @@
import { tr } from "../i18n/index.ts";
import { actionMenu, type ActionMenuItem } from "../ui/actionMenu"; import { actionMenu, type ActionMenuItem } from "../ui/actionMenu";
import { invoke, isTauri } from "@tauri-apps/api/core"; import { invoke, isTauri } from "@tauri-apps/api/core";
import { wordAt } from "./spellingWord"; import { wordAt } from "./spellingWord";
@@ -89,40 +90,40 @@ export function markdownMenu(editor: MarkdownMenuEditor, actions: TableContextAc
editor.select(selectedLink.targetFrom, selectedLink.targetTo); editor.focus(); editor.select(selectedLink.targetFrom, selectedLink.targetTo); editor.focus();
}), { separator: true as const }] : []), }), { separator: true as const }] : []),
...(editor.undo ? [ ...(editor.undo ? [
{ label: "Undo", icon: "undo" as const, shortcut: "Ctrl+Z", disabled: !editor.canUndo?.(), run: () => { close(); editor.undo?.(); } }, { label: tr("Undo"), icon: "undo" as const, shortcut: "Ctrl+Z", disabled: !editor.canUndo?.(), run: () => { close(); editor.undo?.(); } },
{ label: "Redo", icon: "redo" as const, shortcut: "Ctrl+Shift+Z", disabled: !editor.canRedo?.(), run: () => { close(); editor.redo?.(); } }, { label: tr("Redo"), icon: "redo" as const, shortcut: "Ctrl+Shift+Z", disabled: !editor.canRedo?.(), run: () => { close(); editor.redo?.(); } },
{ separator: true as const }, { separator: true as const },
] : []), ] : []),
{ label: "Add link", icon: "link", run: () => link(false) }, { label: tr("Add link"), icon: "link", run: () => link(false) },
{ label: "Add external link", icon: "external", run: () => link(true) }, { label: tr("Add external link"), icon: "external", run: () => link(true) },
{ separator: true }, { separator: true },
{ label: text ? `Search for “${text.length > 32 ? text.slice(0, 32) + "…" : text}”` : "Search selection", icon: "search", disabled: !text || !actions.onSearch, run: () => { close(); actions.onSearch?.(text); } }, { label: text ? tr("Search for “{text}”", { text: text.length > 32 ? text.slice(0, 32) + "…" : text }) : tr("Search selection"), icon: "search", disabled: !text || !actions.onSearch, run: () => { close(); actions.onSearch?.(text); } },
{ label: "Extract current selection…", icon: "extract", disabled: !text || !actions.onExtract, run: () => void request(async () => { { label: tr("Extract current selection…"), icon: "extract", disabled: !text || !actions.onExtract, run: () => void request(async () => {
const target = await actions.onExtract?.(text, text, valid); const target = await actions.onExtract?.(text, text, valid);
if (target) apply(replacement(selection, `[[${target}|${text.replace(/[\[\]|]/g, "").replace(/\s+/g, " ").trim()}]]`)); if (target) apply(replacement(selection, `[[${target}|${text.replace(/[\[\]|]/g, "").replace(/\s+/g, " ").trim()}]]`));
}) }, }) },
{ label: "Format", icon: "format", children: cellFormats.flatMap(([label, kind]) => [ { label: tr("Format"), icon: "format", children: cellFormats.flatMap(([label, kind]) => [
...(kind === "code" || kind === "clear" ? [{ separator: true } as const] : []), ...(kind === "code" || kind === "clear" ? [{ separator: true } as const] : []),
{ label, icon: kind, disabled: kind === "clear" && !text, run: () => apply(formatText(source, selection, kind)) }, { label: tr(label), icon: kind, disabled: kind === "clear" && !text, run: () => apply(formatText(source, selection, kind)) },
]) }, ]) },
{ label: "Paragraph", icon: "paragraph", children: [ { label: tr("Paragraph"), icon: "paragraph", children: [
paragraph("Bullet list", "bullet", "bullet"), paragraph("Numbered list", "number", "number"), paragraph("Task list", "task", "task"), paragraph(tr("Bullet list"), "bullet", "bullet"), paragraph(tr("Numbered list"), "number", "number"), paragraph(tr("Task list"), "task", "task"),
{ separator: true }, { separator: true },
...([1, 2, 3, 4, 5, 6] as const).map(level => paragraph(`Heading ${level}`, level, "heading")), ...([1, 2, 3, 4, 5, 6] as const).map(level => paragraph(tr("Heading {level}", { level }), level, "heading")),
paragraph("Body", "body", "paragraph"), { separator: true }, paragraph("Quote", "quote", "quote"), paragraph(tr("Body"), "body", "paragraph"), { separator: true }, paragraph(tr("Quote"), "quote", "quote"),
] }, ] },
{ label: "Insert", icon: "insert", children: [ { label: tr("Insert"), icon: "insert", children: [
insert("Footnote", "footnote", "footnote"), insert("Table", "table", "table"), insert("Callout", "callout", "quote"), insert("Horizontal rule", "rule", "rule"), insert(tr("Footnote"), "footnote", "footnote"), insert(tr("Table"), "table", "table"), insert(tr("Callout"), "callout", "quote"), insert(tr("Horizontal rule"), "rule", "rule"),
{ separator: true }, insert("Code block", "code", "code"), insert("Math block", "math", "math"), { separator: true }, insert(tr("Code block"), "code", "code"), insert(tr("Math block"), "math", "math"),
] }, ] },
{ separator: true }, { separator: true },
{ label: "Cut", icon: "cut", disabled: !text, run: () => clipboard("cut") }, { label: tr("Cut"), icon: "cut", disabled: !text, run: () => clipboard("cut") },
{ label: "Copy", icon: "copy", disabled: !text, run: () => clipboard("copy") }, { label: tr("Copy"), icon: "copy", disabled: !text, run: () => clipboard("copy") },
{ label: "Paste", icon: "paste", run: () => clipboard("paste") }, { label: tr("Paste"), icon: "paste", run: () => clipboard("paste") },
{ label: "Paste as plain text", icon: "paste-text", run: () => clipboard("plain") }, { label: tr("Paste as plain text"), icon: "paste-text", run: () => clipboard("plain") },
{ label: "Select all", icon: "select", run: () => { close(); editor.selectAll(); } }, { label: tr("Select all"), icon: "select", run: () => { close(); editor.selectAll(); } },
]; ];
root = actionMenu(x, y, items, close, "Markdown text actions"); root = actionMenu(x, y, items, close, tr("Markdown text actions"));
const opened = root; const opened = root;
const word = spellingOffset === undefined ? null : wordAt(source, spellingOffset); const word = spellingOffset === undefined ? null : wordAt(source, spellingOffset);
if (word && isTauri()) { if (word && isTauri()) {
@@ -130,14 +131,14 @@ export function markdownMenu(editor: MarkdownMenuEditor, actions: TableContextAc
void invoke<{ language: string; words: string[]; misspelled: boolean }>("spelling_suggestions", { word: word.word, languages }).then(result => { void invoke<{ language: string; words: string[]; misspelled: boolean }>("spelling_suggestions", { word: word.word, languages }).then(result => {
if (!result.misspelled || root !== opened || !valid()) return; if (!result.misspelled || root !== opened || !valid()) return;
const suggestions: ActionMenuItem[] = result.words.map(value => ({ label: value, run: () => apply(replacement(word, value)) })); const suggestions: ActionMenuItem[] = result.words.map(value => ({ label: value, run: () => apply(replacement(word, value)) }));
if (!suggestions.length) suggestions.push({ label: "No spelling suggestions", disabled: true }); if (!suggestions.length) suggestions.push({ label: tr("No spelling suggestions"), disabled: true });
suggestions.push({ label: "Add to dictionary", icon: "book", run: () => { suggestions.push({ label: tr("Add to dictionary"), icon: "book", run: () => {
close(); close();
void invoke("spelling_suggestions", { word: word.word, languages: [result.language], add: true }).catch(() => report("Could not add the word to the dictionary.")); void invoke("spelling_suggestions", { word: word.word, languages: [result.language], add: true }).catch(() => report("Could not add the word to the dictionary."));
} }); } });
const focusedLabel = opened.contains(document.activeElement) ? document.activeElement?.querySelector(".action-label")?.textContent : undefined; const focusedLabel = opened.contains(document.activeElement) ? document.activeElement?.querySelector(".action-label")?.textContent : undefined;
opened.remove(); opened.remove();
root = actionMenu(x, y, [...suggestions, { separator: true }, ...items], close, "Markdown text actions"); root = actionMenu(x, y, [...suggestions, { separator: true }, ...items], close, tr("Markdown text actions"));
if (focusedLabel) [...root.querySelectorAll<HTMLButtonElement>(":scope > button")].find(button => button.querySelector(".action-label")?.textContent === focusedLabel)?.focus(); if (focusedLabel) [...root.querySelectorAll<HTMLButtonElement>(":scope > button")].find(button => button.querySelector(".action-label")?.textContent === focusedLabel)?.focus();
}).catch(() => { /* Editing actions remain available without spelling suggestions. */ }); }).catch(() => { /* Editing actions remain available without spelling suggestions. */ });
} }
+4 -3
View File
@@ -1,3 +1,4 @@
import { tr } from '../i18n/index.ts';
import { Decoration, EditorView, WidgetType } from "@codemirror/view"; import { Decoration, EditorView, WidgetType } from "@codemirror/view";
import { actionIcon } from "../ui/actionIcons"; import { actionIcon } from "../ui/actionIcons";
@@ -19,14 +20,14 @@ class NoteTitle extends WidgetType {
const button = document.createElement("button"); const button = document.createElement("button");
button.type = "button"; button.type = "button";
button.className = "note-title-button"; button.className = "note-title-button";
button.setAttribute("aria-label", "Rename note"); button.setAttribute("aria-label", tr("Rename note"));
button.append(document.createTextNode(this.title), actionIcon("rename")); button.append(document.createTextNode(this.title), actionIcon("rename"));
button.dataset.editorTooltip = "Rename note"; button.dataset.editorTooltip = tr("Rename note");
heading.replaceChildren(button); heading.replaceChildren(button);
const input = document.createElement("input"); const input = document.createElement("input");
input.className = "note-title-input"; input.className = "note-title-input";
input.setAttribute("aria-label", "Note filename"); input.setAttribute("aria-label", tr("Note filename"));
input.autocomplete = "off"; input.autocomplete = "off";
input.spellcheck = false; input.spellcheck = false;
input.hidden = true; input.hidden = true;
+5 -4
View File
@@ -1,3 +1,4 @@
import { tr } from '../i18n/index.ts';
import { actionMenu, type ActionMenuItem } from "../ui/actionMenu"; import { actionMenu, type ActionMenuItem } from "../ui/actionMenu";
import { linkMenuItems, type DocumentLinkActions } from "./linkMenu"; import { linkMenuItems, type DocumentLinkActions } from "./linkMenu";
@@ -31,16 +32,16 @@ export function readingMenu(host: HTMLElement, actions: DocumentLinkActions, sea
previousFocus = document.activeElement instanceof HTMLElement && host.contains(document.activeElement) ? document.activeElement : host; previousFocus = document.activeElement instanceof HTMLElement && host.contains(document.activeElement) ? document.activeElement : host;
const items: ActionMenuItem[] = []; const items: ActionMenuItem[] = [];
if (text) items.push( if (text) items.push(
{ label: "Copy", icon: "copy", shortcut: "Ctrl+C", run: () => { close(); void navigator.clipboard.writeText(text).catch(() => report("Clipboard unavailable. Use Ctrl+C to copy.")); } }, { label: tr("Copy"), icon: "copy", shortcut: "Ctrl+C", run: () => { close(); void navigator.clipboard.writeText(text).catch(() => report(tr("Clipboard unavailable. Use Ctrl+C to copy."))); } },
{ label: `Search for “${text.length > 32 ? text.slice(0, 32) + "…" : text}”`, icon: "search", disabled: !search, run: () => { close(false); search?.(text); } }, { label: tr("Search for “{text}”", { text: text.length > 32 ? text.slice(0, 32) + "…" : text }), icon: "search", disabled: !search, run: () => { close(false); search?.(text); } },
); );
if (anchor) { if (anchor) {
if (items.length) items.push({ separator: true }); if (items.length) items.push({ separator: true });
if (anchor.hasAttribute("data-footnote-link")) items.push({ label: "Open link", icon: "link", run: () => { close(false); (anchor as HTMLElement).click(); } }); if (anchor.hasAttribute("data-footnote-link")) items.push({ label: tr("Open link"), icon: "link", run: () => { close(false); (anchor as HTMLElement).click(); } });
else items.push(...linkMenuItems({ kind: anchor.getAttribute("data-kind") === "wiki" ? "wiki" : "md", target: anchor.getAttribute("href") ?? "" }, actions, () => close(false), report)); else items.push(...linkMenuItems({ kind: anchor.getAttribute("data-kind") === "wiki" ? "wiki" : "md", target: anchor.getAttribute("href") ?? "" }, actions, () => close(false), report));
} }
const rect = keyboard ? (range?.getBoundingClientRect() ?? anchor?.getBoundingClientRect() ?? host.getBoundingClientRect()) : null; const rect = keyboard ? (range?.getBoundingClientRect() ?? anchor?.getBoundingClientRect() ?? host.getBoundingClientRect()) : null;
root = actionMenu(rect?.left ?? (event as MouseEvent).clientX, rect?.bottom ?? (event as MouseEvent).clientY, items, close, "Reading actions"); root = actionMenu(rect?.left ?? (event as MouseEvent).clientX, rect?.bottom ?? (event as MouseEvent).clientY, items, close, tr("Reading actions"));
} }
const outside = (event: Event) => { if (root && event.target instanceof Node && !root.contains(event.target)) close(false); }; const outside = (event: Event) => { if (root && event.target instanceof Node && !root.contains(event.target)) close(false); };
const resize = () => close(false); const resize = () => close(false);
+16 -7
View File
@@ -1,3 +1,4 @@
import { tr } from "../i18n/index.ts";
import { invoke, isTauri } from "@tauri-apps/api/core"; import { invoke, isTauri } from "@tauri-apps/api/core";
import { listen } from "@tauri-apps/api/event"; import { listen } from "@tauri-apps/api/event";
import { actionMenu, type ActionMenuItem } from "../ui/actionMenu"; import { actionMenu, type ActionMenuItem } from "../ui/actionMenu";
@@ -87,32 +88,40 @@ export function mountSpellingMenu(): () => void {
const { target, x, y, word } = context; const { target, x, y, word } = context;
const requestRevision = ++revision; const requestRevision = ++revision;
let items = spellingItems(payload.items, id => finish(id, true)); let items = spellingItems(payload.items, id => finish(id, true));
const parent = target.closest<HTMLDialogElement>("dialog[open]") ?? document.body;
const show = () => {
const previous = active?.request === payload.request ? active.root : undefined;
const focusedLabel = previous?.contains(document.activeElement) ? document.activeElement?.querySelector(".action-label")?.textContent : undefined;
previous?.remove();
const root = actionMenu(x, y, items, () => finish(null, true), tr("Spelling actions"), parent);
active = { request: payload.request, root, target };
if (focusedLabel) [...root.querySelectorAll<HTMLButtonElement>(":scope > button")].find(button => button.querySelector(".action-label")?.textContent === focusedLabel)?.focus();
};
if (payload.fallback_spelling) { if (payload.fallback_spelling) {
const readable = (entries: NativeSpellingItem[]): NativeSpellingItem[] => entries.filter(item => item.kind === 3 || item.label.trim()).map(item => ({ ...item, children: readable(item.children) })); const readable = (entries: NativeSpellingItem[]): NativeSpellingItem[] => entries.filter(item => item.kind === 3 || item.label.trim()).map(item => ({ ...item, children: readable(item.children) }));
items = spellingItems(readable(payload.items), id => finish(id, true)); items = spellingItems(readable(payload.items), id => finish(id, true));
show();
if (word) { if (word) {
const languages = [...new Set([target.lang, document.documentElement.lang, ...navigator.languages].filter(Boolean))]; const languages = [...new Set([target.lang, document.documentElement.lang, ...navigator.languages].filter(Boolean))];
try { try {
const result = await invoke<{ language: string; words: string[]; misspelled: boolean }>("spelling_suggestions", { word: word.word, languages }); const result = await invoke<{ language: string; words: string[]; misspelled: boolean }>("spelling_suggestions", { word: word.word, languages });
const suggestions: ActionMenuItem[] = result.words.map(value => ({ label: value, run: () => { finish(); word.replace(value); } })); const suggestions: ActionMenuItem[] = result.words.map(value => ({ label: value, run: () => { finish(); word.replace(value); } }));
if (result.misspelled && !suggestions.length) suggestions.push({ label: "No spelling suggestions", disabled: true }); if (result.misspelled && !suggestions.length) suggestions.push({ label: tr("No spelling suggestions"), disabled: true });
if (result.misspelled) suggestions.push({ label: "Add to dictionary", icon: "book", run: () => { if (result.misspelled) suggestions.push({ label: tr("Add to dictionary"), icon: "book", run: () => {
finish(null, true); finish(null, true);
void invoke("spelling_suggestions", { word: word.word, languages: [result.language], add: true }).catch(error => console.error("Could not add the word", error)); void invoke("spelling_suggestions", { word: word.word, languages: [result.language], add: true }).catch(error => console.error("Could not add the word", error));
} }, { separator: true }); } }, { separator: true });
items = [...suggestions, ...items]; items = [...suggestions, ...items];
} catch { } catch {
items = [{ label: "Spelling suggestions unavailable", disabled: true }, { separator: true }, ...items]; items = [{ label: tr("Spelling suggestions unavailable"), disabled: true }, { separator: true }, ...items];
} }
} }
} }
if (disposed || requestRevision !== revision || !target.isConnected || (payload.fallback_spelling && word && !word.valid())) { if (disposed || requestRevision !== revision || (payload.fallback_spelling && active?.request !== payload.request) || !target.isConnected || (payload.fallback_spelling && word && !word.valid())) {
void invoke("spelling_menu_select", { request: payload.request, command: null }); void invoke("spelling_menu_select", { request: payload.request, command: null });
return; return;
} }
const parent = target.closest<HTMLDialogElement>("dialog[open]") ?? document.body; show();
const root = actionMenu(x, y, items, () => finish(null, true), "Spelling actions", parent);
active = { request: payload.request, root, target };
}).then(async stop => { }).then(async stop => {
if (disposed) { stop(); return; } if (disposed) { stop(); return; }
unlisten = stop; unlisten = stop;
+18 -17
View File
@@ -1,3 +1,4 @@
import { tr } from '../i18n/index.ts';
import { getMarkRange, type Editor, type JSONContent } from "@tiptap/core"; import { getMarkRange, type Editor, type JSONContent } from "@tiptap/core";
import { requestText } from "../workspace/dialogs.svelte"; import { requestText } from "../workspace/dialogs.svelte";
import { extractedCellMarkdown } from "./tableCellMarkdown"; import { extractedCellMarkdown } from "./tableCellMarkdown";
@@ -29,15 +30,15 @@ export function tableTextItems(editor: Editor, actions: TableContextActions, clo
} }
function link(external: boolean) { function link(external: boolean) {
void request(async () => { void request(async () => {
const target = await requestText(external ? "External link URL" : "Link to note (name or workspace path)", external ? "https://" : text); const target = await requestText(external ? tr("External link URL") : tr("Link to note (name or workspace path)"), external ? "https://" : text);
if (!target || !valid()) return; if (!target || !valid()) return;
if (external) { if (external) {
try { try {
const url = new URL(target); const url = new URL(target);
if (!(["http:", "https:"].includes(url.protocol) && url.hostname || url.protocol === "mailto:" && url.pathname.includes("@")) || /\s/.test(target)) throw new Error("Invalid URL"); if (!(["http:", "https:"].includes(url.protocol) && url.hostname || url.protocol === "mailto:" && url.pathname.includes("@")) || /\s/.test(target)) throw new Error("Invalid URL");
} catch { report("Enter a valid http, https, or mailto link."); return; } } catch { report(tr("Enter a valid http, https, or mailto link.")); return; }
} }
if (!external && /[\[\]|\r\n]|^[a-z][a-z\d+.-]*:/i.test(target)) { report("Enter a note name or path without brackets or pipes."); return; } if (!external && /[\[\]|\r\n]|^[a-z][a-z\d+.-]*:/i.test(target)) { report(tr("Enter a note name or path without brackets or pipes.")); return; }
run(() => { run(() => {
const attrs = { href: target, "data-kind": external ? "md" : "wiki" }; const attrs = { href: target, "data-kind": external ? "md" : "wiki" };
if (selection.empty) editor.commands.insertContent({ type: "text", text: target, marks: [{ type: "link", attrs }] }); if (selection.empty) editor.commands.insertContent({ type: "text", text: target, marks: [{ type: "link", attrs }] });
@@ -88,35 +89,35 @@ export function tableTextItems(editor: Editor, actions: TableContextActions, clo
} }
}); });
} }
} catch { report("Clipboard unavailable. Use the keyboard shortcut to copy, cut, or paste."); } } catch { report(tr("Clipboard unavailable. Use the keyboard shortcut to copy, cut, or paste.")); }
}); });
} }
const items: ActionMenuItem[] = [ const items: ActionMenuItem[] = [
...(selectedLink ? [...linkMenuItems(selectedLink, actions.linkActions?.() || {}, close, report, editLink), { separator: true as const }] : []), ...(selectedLink ? [...linkMenuItems(selectedLink, actions.linkActions?.() || {}, close, report, editLink), { separator: true as const }] : []),
{ label: "Add link", icon: "link", run: () => link(false) }, { label: tr("Add link"), icon: "link", run: () => link(false) },
{ label: "Add external link", icon: "external", run: () => link(true) }, { label: tr("Add external link"), icon: "external", run: () => link(true) },
{ separator: true }, { separator: true },
{ label: text ? `Search for “${text.length > 32 ? text.slice(0, 32) + "…" : text}”` : "Search selection", icon: "search", disabled: !text || !actions.onSearch, run: () => { close(); actions.onSearch?.(text); } }, { label: text ? tr("Search for “{text}”", { text: text.length > 32 ? text.slice(0, 32) + "…" : text }) : tr("Search selection"), icon: "search", disabled: !text || !actions.onSearch, run: () => { close(); actions.onSearch?.(text); } },
{ label: "Extract current selection…", icon: "extract", disabled: !text || !actions.onExtract, run: () => void request(async () => { { label: tr("Extract current selection…"), icon: "extract", disabled: !text || !actions.onExtract, run: () => void request(async () => {
const selected = doc.slice(selection.from, selection.to).content.toJSON() as JSONContent[] | null; const selected = doc.slice(selection.from, selection.to).content.toJSON() as JSONContent[] | null;
const markdown = extractedCellMarkdown(selected || []); const markdown = extractedCellMarkdown(selected || []);
const target = await actions.onExtract?.(markdown, text, valid); const target = await actions.onExtract?.(markdown, text, valid);
if (target) run(() => { editor.commands.insertContent({ type: "text", text: text.replace(/\s+/g, " ").trim(), marks: [{ type: "link", attrs: { href: target, "data-kind": "wiki" } }] }); }); if (target) run(() => { editor.commands.insertContent({ type: "text", text: text.replace(/\s+/g, " ").trim(), marks: [{ type: "link", attrs: { href: target, "data-kind": "wiki" } }] }); });
}) }, }) },
{ label: "Format", icon: "format", children: cellFormats.map(([label, kind]) => ({ label, icon: kind, disabled: selection.empty, run: () => run(() => { { label: tr("Format"), icon: "format", children: cellFormats.map(([label, kind]) => ({ label: tr(label), icon: kind, disabled: selection.empty, run: () => run(() => {
if (kind === "clear") editor.commands.unsetAllMarks(); else editor.commands.toggleMark(kind); if (kind === "clear") editor.commands.unsetAllMarks(); else editor.commands.toggleMark(kind);
}) })) }, }) })) },
{ label: "Paragraph", icon: "paragraph", disabled: true, title: "Markdown table cells contain inline text" }, { label: tr("Paragraph"), icon: "paragraph", disabled: true, title: tr("Markdown table cells contain inline text") },
{ label: "Insert", icon: "insert", disabled: true, title: "Use the Row and Column menus to change the table" }, { label: tr("Insert"), icon: "insert", disabled: true, title: tr("Use the Row and Column menus to change the table") },
{ separator: true }, { separator: true },
{ label: "Cut", icon: "cut", disabled: selection.empty, run: () => void clipboard("cut") }, { label: tr("Cut"), icon: "cut", disabled: selection.empty, run: () => void clipboard("cut") },
{ label: "Copy", icon: "copy", disabled: selection.empty, run: () => void clipboard("copy") }, { label: tr("Copy"), icon: "copy", disabled: selection.empty, run: () => void clipboard("copy") },
{ label: "Paste", icon: "paste", run: () => void clipboard("paste") }, { label: tr("Paste"), icon: "paste", run: () => void clipboard("paste") },
{ label: "Paste as plain text", icon: "paste-text", run: () => void clipboard("plain") }, { label: tr("Paste as plain text"), icon: "paste-text", run: () => void clipboard("plain") },
{ label: "Select all", icon: "select", run: () => { close(); editor.commands.selectAll(); editor.view.focus(); } }, { label: tr("Select all"), icon: "select", run: () => { close(); editor.commands.selectAll(); editor.view.focus(); } },
]; ];
return sourceEditing ? [ return sourceEditing ? [
...(selectedLink ? [...linkMenuItems(selectedLink, actions.linkActions?.() || {}, close, report, editLink), { separator: true as const }] : []), ...(selectedLink ? [...linkMenuItems(selectedLink, actions.linkActions?.() || {}, close, report, editLink), { separator: true as const }] : []),
...items.slice(items.findIndex(item => "label" in item && item.label === "Cut")), ...items.slice(items.findIndex(item => "label" in item && item.label === tr("Cut"))),
] : items; ] : items;
} }
+5 -4
View File
@@ -1,3 +1,4 @@
import { tr } from '../i18n/index.ts';
import { Editor, Extension, Mark, getMarkRange } from "@tiptap/core"; import { Editor, Extension, Mark, getMarkRange } from "@tiptap/core";
import { Plugin } from "@tiptap/pm/state"; import { Plugin } from "@tiptap/pm/state";
import { Decoration, DecorationSet } from "@tiptap/pm/view"; import { Decoration, DecorationSet } from "@tiptap/pm/view";
@@ -96,7 +97,7 @@ export function tableControls(root: HTMLElement, view: EditorView, initialSource
cell.removeAttribute("title"); cell.removeAttribute("title");
if (result && cell !== active) cell.innerHTML = formulas.tableFormulaHtml(result); if (result && cell !== active) cell.innerHTML = formulas.tableFormulaHtml(result);
if (cell === active) { if (cell === active) {
formulaStatus.textContent = `${address}${result ? ` = ${result.text}` : " · Type = to calculate"}`; formulaStatus.textContent = `${address}${result ? ` = ${result.text}` : tr(" · Type = to calculate")}`;
formulaHint.textContent = result?.error ? formulas.formulaErrors[result.error] : ""; formulaHint.textContent = result?.error ? formulas.formulaErrors[result.error] : "";
formulaHint.hidden = !formulaHint.textContent; formulaHint.hidden = !formulaHint.textContent;
} }
@@ -136,7 +137,7 @@ export function tableControls(root: HTMLElement, view: EditorView, initialSource
cell.innerHTML = html; cell.innerHTML = html;
cell.classList.remove("is-editing", "is-source-editing"); cell.classList.remove("is-editing", "is-source-editing");
refreshFormulas(); refreshFormulas();
formulaStatus.textContent = "Type = in a cell to calculate"; formulaStatus.textContent = tr("Type = in a cell to calculate");
formulaHint.hidden = true; formulaHint.hidden = true;
view.requestMeasure(); view.requestMeasure();
if (!firstEdit) view.dispatch({ annotations: isolateHistory.of("after") }); if (!firstEdit) view.dispatch({ annotations: isolateHistory.of("after") });
@@ -390,7 +391,7 @@ export function tableControls(root: HTMLElement, view: EditorView, initialSource
wrapper.after(footer); wrapper.after(footer);
for (const kind of ["column", "row"] as const) { for (const kind of ["column", "row"] as const) {
const button = document.createElement("button"); const button = document.createElement("button");
const label = kind === "column" ? "Add column to the right" : "Add row below"; const label = kind === "column" ? tr("Add column to the right") : tr("Add row below");
button.type = "button"; button.type = "button";
button.className = `table-add table-add-${kind}`; button.className = `table-add table-add-${kind}`;
tooltipCleanup.push(attachTooltip(button, () => label)); tooltipCleanup.push(attachTooltip(button, () => label));
@@ -409,7 +410,7 @@ export function tableControls(root: HTMLElement, view: EditorView, initialSource
} }
for (const row of table.rows) for (const cell of row.cells) { for (const row of table.rows) for (const cell of row.cells) {
cell.tabIndex = 0; cell.tabIndex = 0;
cell.setAttribute("aria-label", `${formulas ? formulas.cellAddress(row.rowIndex, cell.cellIndex) + " · " : ""}Row ${row.rowIndex + 1}, column ${cell.cellIndex + 1}`); cell.setAttribute("aria-label", (formulas ? formulas.cellAddress(row.rowIndex, cell.cellIndex) + " · " : "") + tr("Row {row}, column {column}", { row: row.rowIndex + 1, column: cell.cellIndex + 1 }));
cell.addEventListener("focus", () => activate(cell)); cell.addEventListener("focus", () => activate(cell));
} }
selectionControls = tableSelectionControls(root, wrapper, table, view, () => controller.source, finish, change, { get: () => editor, activate, editSource }, actions); selectionControls = tableSelectionControls(root, wrapper, table, view, () => controller.source, finish, change, { get: () => editor, activate, editSource }, actions);
+4 -3
View File
@@ -1,3 +1,4 @@
import { tr } from '../i18n/index.ts';
import type { EditorView } from "@codemirror/view"; import type { EditorView } from "@codemirror/view";
import { actionIcon } from "../ui/actionIcons"; import { actionIcon } from "../ui/actionIcons";
import { moveTableAxis, type TableAxis } from "./tableStructure"; import { moveTableAxis, type TableAxis } from "./tableStructure";
@@ -102,7 +103,7 @@ export function tableDragControls(root: HTMLElement, wrapper: HTMLElement, table
if (!preview || !previewLabel || !drag) return; if (!preview || !previewLabel || !drag) return;
const valid = drag.to !== undefined; const valid = drag.to !== undefined;
preview.classList.toggle("is-invalid-drop", !valid); preview.classList.toggle("is-invalid-drop", !valid);
previewLabel.textContent = `${drag.axis === "row" ? "Row" : "Column"} ${drag.index + 1}${valid ? ` → ${drag.to! + 1}` : " · Release to cancel"}`; previewLabel.textContent = `${drag.axis === "row" ? tr("Row") : tr("Column")} ${drag.index + 1}${valid ? ` → ${drag.to! + 1}` : tr(" · Release to cancel")}`;
const rect = preview.getBoundingClientRect(); const rect = preview.getBoundingClientRect();
const x = Math.max(8, Math.min(drag.x + 16, window.innerWidth - rect.width - 8)); const x = Math.max(8, Math.min(drag.x + 16, window.innerWidth - rect.width - 8));
const y = Math.max(8, Math.min(drag.y + 16, window.innerHeight - rect.height - 8)); const y = Math.max(8, Math.min(drag.y + 16, window.innerHeight - rect.height - 8));
@@ -171,8 +172,8 @@ export function tableDragControls(root: HTMLElement, wrapper: HTMLElement, table
button.type = "button"; button.type = "button";
button.className = `table-drag-handle table-drag-${axis}`; button.className = `table-drag-handle table-drag-${axis}`;
button.dataset.index = String(index); button.dataset.index = String(index);
const label = `Move ${axis} ${index + 1}`; const label = tr(axis === "row" ? "Move row {number}" : "Move column {number}", { number: index + 1 });
const tooltip = `${label} · Drag to reorder · ${axis === "row" ? "↑/↓" : "←/→"} to move`; const tooltip = tr("{label} · Drag to reorder · {keys} to move", { label, keys: axis === "row" ? "↑/↓" : "←/→" });
button.setAttribute("aria-label", label); button.setAttribute("aria-label", label);
tooltipCleanup.push(attachTooltip(button, () => drag ? "" : tooltip)); tooltipCleanup.push(attachTooltip(button, () => drag ? "" : tooltip));
button.append(actionIcon("grip")); button.append(actionIcon("grip"));
+25 -24
View File
@@ -1,3 +1,4 @@
import { tr } from '../i18n/index.ts';
import type { EditorView } from "@codemirror/view"; import type { EditorView } from "@codemirror/view";
import { isolateHistory } from "@codemirror/commands"; import { isolateHistory } from "@codemirror/commands";
import { undo, redo } from "./writerHistory"; import { undo, redo } from "./writerHistory";
@@ -103,9 +104,9 @@ export function tableSelectionControls(root: HTMLElement, wrapper: HTMLElement,
apply((text, selected) => alignTableCells(text, selected, alignment)); apply((text, selected) => alignTableCells(text, selected, alignment));
}; };
const alignmentItems: ActionMenuItem[] = [ const alignmentItems: ActionMenuItem[] = [
{ label: "Align left", icon: "left", run: () => align("left") }, { label: tr("Align left"), icon: "left", run: () => align("left") },
{ label: "Align centre", icon: "center", run: () => align("center") }, { label: tr("Align centre"), icon: "center", run: () => align("center") },
{ label: "Align right", icon: "right", run: () => align("right") }, { label: tr("Align right"), icon: "right", run: () => align("right") },
].map(item => ({ ...item, title: "Alignment applies to the selected Markdown columns" } as ActionMenuItem)); ].map(item => ({ ...item, title: "Alignment applies to the selected Markdown columns" } as ActionMenuItem));
const report = (message: string) => { const report = (message: string) => {
const status = root.querySelector<HTMLElement>(".table-edit-help"); const status = root.querySelector<HTMLElement>(".table-edit-help");
@@ -114,34 +115,34 @@ export function tableSelectionControls(root: HTMLElement, wrapper: HTMLElement,
const items: ActionMenuItem[] = textEditor ? tableTextItems(textEditor, actions, closeMenu, run => { const items: ActionMenuItem[] = textEditor ? tableTextItems(textEditor, actions, closeMenu, run => {
view.dispatch({ annotations: isolateHistory.of("before") }); run(); view.dispatch({ annotations: isolateHistory.of("after") }); view.dispatch({ annotations: isolateHistory.of("before") }); run(); view.dispatch({ annotations: isolateHistory.of("after") });
}, value => { pending = value; }, report, rich.editSource) : [ }, value => { pending = value; }, report, rich.editSource) : [
...(["cut", "copy", "paste"] as const).map(action => ({ label: action[0].toUpperCase() + action.slice(1), icon: action, run: () => void clipboard(action) })), ...(["cut", "copy", "paste"] as const).map(action => ({ label: tr(action[0].toUpperCase() + action.slice(1)), icon: action, run: () => void clipboard(action) })),
sep, sep,
{ label: "Format", icon: "format", children: cellFormats.map(([label, kind]) => ({ label, icon: kind, run: () => format(kind) })) }, { label: tr("Format"), icon: "format", children: cellFormats.map(([label, kind]) => ({ label: tr(label), icon: kind, run: () => format(kind) })) },
...alignmentItems, ...alignmentItems,
sep, { label: "Clear cells", icon: "clear", run: clearCells, title: "Clear selected values and keep the cells." }, sep, { label: tr("Clear cells"), icon: "clear", run: clearCells, title: tr("Clear selected values and keep the cells.") },
{ label: "Delete cells", icon: "trash", run: deleteCells, title: "Delete or Backspace removes full rows or columns. Other selections shift cells left." }, { label: tr("Delete cells"), icon: "trash", run: deleteCells, title: tr("Delete or Backspace removes full rows or columns. Other selections shift cells left.") },
]; ];
if (textEditor) items.push(sep, { label: "Select cell", icon: "select", title: "Select this cell, then use Shift+arrow keys to extend the selection", run: () => { closeMenu(); select(cellRange); } }); if (textEditor) items.push(sep, { label: tr("Select cell"), icon: "select", title: tr("Select this cell, then use Shift+arrow keys to extend the selection"), run: () => { closeMenu(); select(cellRange); } });
items.push(sep, items.push(sep,
{ label: "Row", icon: "row", children: [ { label: tr("Row"), icon: "row", children: [
{ label: "Add row above", icon: "row-before", disabled: row === 0, title: row === 0 ? "The first row is the Markdown header" : undefined, run: () => structural("row", "before") }, { label: tr("Add row above"), icon: "row-before", disabled: row === 0, title: row === 0 ? tr("The first row is the Markdown header") : undefined, run: () => structural("row", "before") },
{ label: "Add row below", icon: "row-after", run: () => structural("row", "after") }, sep, { label: tr("Add row below"), icon: "row-after", run: () => structural("row", "after") }, sep,
{ label: "Move row up", icon: "up", disabled: row <= 1, run: () => structural("row", "previous") }, { label: tr("Move row up"), icon: "up", disabled: row <= 1, run: () => structural("row", "previous") },
{ label: "Move row down", icon: "down", disabled: row === 0 || row === lastRow, run: () => structural("row", "next") }, sep, { label: tr("Move row down"), icon: "down", disabled: row === 0 || row === lastRow, run: () => structural("row", "next") }, sep,
{ label: "Duplicate row", icon: "copy", run: () => structural("row", "duplicate") }, { label: tr("Duplicate row"), icon: "copy", run: () => structural("row", "duplicate") },
{ label: "Delete row", icon: "trash", run: () => structural("row", "delete") }, { label: tr("Delete row"), icon: "trash", run: () => structural("row", "delete") },
] }, ] },
{ label: "Column", icon: "column", children: [ { label: tr("Column"), icon: "column", children: [
{ label: "Add column to the left", icon: "column-before", run: () => structural("column", "before") }, { label: tr("Add column to the left"), icon: "column-before", run: () => structural("column", "before") },
{ label: "Add column to the right", icon: "column-after", run: () => structural("column", "after") }, sep, { label: tr("Add column to the right"), icon: "column-after", run: () => structural("column", "after") }, sep,
{ label: "Move column left", icon: "move-left", disabled: column === 0, run: () => structural("column", "previous") }, { label: tr("Move column left"), icon: "move-left", disabled: column === 0, run: () => structural("column", "previous") },
{ label: "Move column right", icon: "move-right", disabled: column === lastColumn, run: () => structural("column", "next") }, sep, { label: tr("Move column right"), icon: "move-right", disabled: column === lastColumn, run: () => structural("column", "next") }, sep,
...alignmentItems, sep, ...alignmentItems, sep,
{ label: "Duplicate column", icon: "copy", run: () => structural("column", "duplicate") }, { label: tr("Duplicate column"), icon: "copy", run: () => structural("column", "duplicate") },
{ label: "Delete column", icon: "trash", run: () => structural("column", "delete") }, { label: tr("Delete column"), icon: "trash", run: () => structural("column", "delete") },
] }, sep, ] }, sep,
{ label: "Sort by column (A to Z)", icon: "sort-asc", disabled: lastRow < 2, run: () => { range ??= cellRange; apply(text => sortTableColumn(text, column)); } }, { label: tr("Sort by column (A to Z)"), icon: "sort-asc", disabled: lastRow < 2, run: () => { range ??= cellRange; apply(text => sortTableColumn(text, column)); } },
{ label: "Sort by column (Z to A)", icon: "sort-desc", disabled: lastRow < 2, run: () => { range ??= cellRange; apply(text => sortTableColumn(text, column, true)); } }, { label: tr("Sort by column (Z to A)"), icon: "sort-desc", disabled: lastRow < 2, run: () => { range ??= cellRange; apply(text => sortTableColumn(text, column, true)); } },
); );
menu = actionMenu(x, y, items, returnFocus); menu = actionMenu(x, y, items, returnFocus);
} }
+34 -33
View File
@@ -1,3 +1,4 @@
import { tr } from '../i18n/index.ts';
import type { Editor } from "@tiptap/core"; import type { Editor } from "@tiptap/core";
import type { MenuItem } from "../layout/menuTypes"; import type { MenuItem } from "../layout/menuTypes";
@@ -47,93 +48,93 @@ export async function pasteClipboard(editor: Editor): Promise<void> {
export function writerContextItems(editor: Editor): MenuItem[] { export function writerContextItems(editor: Editor): MenuItem[] {
const inTable = editor.isActive("table"); const inTable = editor.isActive("table");
return [ return [
{ kind: "action", label: "Cut", run: () => void cutSelection(editor) }, { kind: "action", label: tr("Cut"), run: () => void cutSelection(editor) },
{ kind: "action", label: "Copy", run: () => void copySelection(editor) }, { kind: "action", label: tr("Copy"), run: () => void copySelection(editor) },
{ kind: "action", label: "Paste", run: () => void pasteClipboard(editor) }, { kind: "action", label: tr("Paste"), run: () => void pasteClipboard(editor) },
{ kind: "sep" }, { kind: "sep" },
{ {
kind: "group", kind: "group",
label: "Style", label: tr("Style"),
items: [ items: [
{ kind: "action", label: "Heading 1", run: () => editor.chain().focus().toggleHeading({ level: 1 }).run() }, { kind: "action", label: tr("Heading {level}", { level: 1 }), run: () => editor.chain().focus().toggleHeading({ level: 1 }).run() },
{ kind: "action", label: "Heading 2", run: () => editor.chain().focus().toggleHeading({ level: 2 }).run() }, { kind: "action", label: tr("Heading {level}", { level: 2 }), run: () => editor.chain().focus().toggleHeading({ level: 2 }).run() },
{ kind: "action", label: "Heading 3", run: () => editor.chain().focus().toggleHeading({ level: 3 }).run() }, { kind: "action", label: tr("Heading {level}", { level: 3 }), run: () => editor.chain().focus().toggleHeading({ level: 3 }).run() },
{ kind: "action", label: "Heading 4", run: () => editor.chain().focus().toggleHeading({ level: 4 }).run() }, { kind: "action", label: tr("Heading {level}", { level: 4 }), run: () => editor.chain().focus().toggleHeading({ level: 4 }).run() },
{ kind: "action", label: "Heading 5", run: () => editor.chain().focus().toggleHeading({ level: 5 }).run() }, { kind: "action", label: tr("Heading {level}", { level: 5 }), run: () => editor.chain().focus().toggleHeading({ level: 5 }).run() },
{ kind: "action", label: "Heading 6", run: () => editor.chain().focus().toggleHeading({ level: 6 }).run() }, { kind: "action", label: tr("Heading {level}", { level: 6 }), run: () => editor.chain().focus().toggleHeading({ level: 6 }).run() },
{ kind: "action", label: "Body", run: () => editor.chain().focus().setParagraph().run() }, { kind: "action", label: tr("Body"), run: () => editor.chain().focus().setParagraph().run() },
{ kind: "action", label: "Quote", run: () => editor.chain().focus().toggleBlockquote().run() }, { kind: "action", label: tr("Quote"), run: () => editor.chain().focus().toggleBlockquote().run() },
{ kind: "sep" }, { kind: "sep" },
{ kind: "action", label: "Bullet list", run: () => editor.chain().focus().toggleBulletList().run() }, { kind: "action", label: tr("Bullet list"), run: () => editor.chain().focus().toggleBulletList().run() },
{ kind: "action", label: "Numbered list", run: () => editor.chain().focus().toggleOrderedList().run() }, { kind: "action", label: tr("Numbered list"), run: () => editor.chain().focus().toggleOrderedList().run() },
{ kind: "action", label: "Task list", run: () => editor.chain().focus().toggleTaskList().run() }, { kind: "action", label: tr("Task list"), run: () => editor.chain().focus().toggleTaskList().run() },
], ],
}, },
{ {
kind: "group", kind: "group",
label: "Format", label: tr("Format"),
items: [ items: [
{ kind: "action", label: "Bold", run: () => editor.chain().focus().toggleBold().run() }, { kind: "action", label: tr("Bold"), run: () => editor.chain().focus().toggleBold().run() },
{ kind: "action", label: "Italic", run: () => editor.chain().focus().toggleItalic().run() }, { kind: "action", label: tr("Italic"), run: () => editor.chain().focus().toggleItalic().run() },
{ kind: "action", label: "Strikethrough", run: () => editor.chain().focus().toggleStrike().run() }, { kind: "action", label: tr("Strikethrough"), run: () => editor.chain().focus().toggleStrike().run() },
{ kind: "action", label: "Highlight", run: () => editor.chain().focus().toggleHighlight().run() }, { kind: "action", label: tr("Highlight"), run: () => editor.chain().focus().toggleHighlight().run() },
{ kind: "action", label: "Code", run: () => editor.chain().focus().toggleCode().run() }, { kind: "action", label: tr("Code"), run: () => editor.chain().focus().toggleCode().run() },
{ kind: "action", label: "Math", run: () => editor.chain().focus().toggleMark("math").run() }, { kind: "action", label: tr("Math"), run: () => editor.chain().focus().toggleMark("math").run() },
{ kind: "action", label: "Comment", run: () => editor.chain().focus().toggleMark("comment").run() }, { kind: "action", label: tr("Comment"), run: () => editor.chain().focus().toggleMark("comment").run() },
{ kind: "sep" }, { kind: "sep" },
{ kind: "action", label: "Clear formatting", run: () => editor.chain().focus().unsetAllMarks().run() }, { kind: "action", label: tr("Clear formatting"), run: () => editor.chain().focus().unsetAllMarks().run() },
], ],
}, },
{ {
kind: "group", kind: "group",
label: "Table", label: tr("Table"),
items: [ items: [
{ {
kind: "action", kind: "action",
label: "Insert table", label: tr("Insert table"),
run: () => editor.chain().focus().insertTable({ rows: 3, cols: 3, withHeaderRow: true }).run(), run: () => editor.chain().focus().insertTable({ rows: 3, cols: 3, withHeaderRow: true }).run(),
}, },
{ kind: "sep" }, { kind: "sep" },
{ {
kind: "action", kind: "action",
label: "Add row above", label: tr("Add row above"),
disabled: !inTable, disabled: !inTable,
run: () => editor.chain().focus().addRowBefore().run(), run: () => editor.chain().focus().addRowBefore().run(),
}, },
{ {
kind: "action", kind: "action",
label: "Add row below", label: tr("Add row below"),
disabled: !inTable, disabled: !inTable,
run: () => editor.chain().focus().addRowAfter().run(), run: () => editor.chain().focus().addRowAfter().run(),
}, },
{ {
kind: "action", kind: "action",
label: "Delete row", label: tr("Delete row"),
disabled: !inTable, disabled: !inTable,
run: () => editor.chain().focus().deleteRow().run(), run: () => editor.chain().focus().deleteRow().run(),
}, },
{ kind: "sep" }, { kind: "sep" },
{ {
kind: "action", kind: "action",
label: "Add column left", label: tr("Add column left"),
disabled: !inTable, disabled: !inTable,
run: () => editor.chain().focus().addColumnBefore().run(), run: () => editor.chain().focus().addColumnBefore().run(),
}, },
{ {
kind: "action", kind: "action",
label: "Add column right", label: tr("Add column right"),
disabled: !inTable, disabled: !inTable,
run: () => editor.chain().focus().addColumnAfter().run(), run: () => editor.chain().focus().addColumnAfter().run(),
}, },
{ {
kind: "action", kind: "action",
label: "Delete column", label: tr("Delete column"),
disabled: !inTable, disabled: !inTable,
run: () => editor.chain().focus().deleteColumn().run(), run: () => editor.chain().focus().deleteColumn().run(),
}, },
{ {
kind: "action", kind: "action",
label: "Delete table", label: tr("Delete table"),
disabled: !inTable, disabled: !inTable,
run: () => editor.chain().focus().deleteTable().run(), run: () => editor.chain().focus().deleteTable().run(),
}, },
+40
View File
@@ -0,0 +1,40 @@
import { derived, get, writable } from 'svelte/store';
import { catalogs, type Locale } from './messages.ts';
export { type Locale } from './messages.ts';
export const LANGUAGE_KEY = 'runestone.language';
export const LANGUAGES: { id: Locale; name: string }[] = [
{ id: 'en', name: 'English' }, { id: 'fr', name: 'Français' },
{ id: 'ja', name: '日本語' }, { id: 'zh-CN', name: '简体中文' },
];
export function normalizeLocale(value: unknown): Locale {
return LANGUAGES.some(item => item.id === value) ? value as Locale : 'en';
}
export const locale = writable<Locale>('en');
export function translate(language: Locale, message: string, values: Record<string, string | number> = {}): string {
const template = language === 'en' || !Object.hasOwn(catalogs[language], message) ? message : catalogs[language][message];
return template.replace(/\{(\w+)\}/g, (match, key: string) => Object.hasOwn(values, key) ? String(values[key]) : match);
}
export const t = derived(locale, language => (message: string, values?: Record<string, string | number>) => translate(language, message, values));
export function tr(message: string, values?: Record<string, string | number>): string {
return translate(get(locale), message, values);
}
function applyLocale(language: Locale) {
locale.set(language);
if (typeof document !== 'undefined') document.documentElement.lang = language;
}
export function setLocale(language: Locale) {
const valid = normalizeLocale(language);
localStorage.setItem(LANGUAGE_KEY, valid);
applyLocale(valid);
}
export function syncLocale() {
const read = () => {
try { applyLocale(normalizeLocale(localStorage.getItem(LANGUAGE_KEY))); }
catch { applyLocale('en'); }
};
const sync = (event: StorageEvent) => { if (event.key === LANGUAGE_KEY || event.key === null) read(); };
read();
window.addEventListener('storage', sync);
window.addEventListener('focus', read);
return () => { window.removeEventListener('storage', sync); window.removeEventListener('focus', read); };
}
File diff suppressed because it is too large Load Diff
+3 -2
View File
@@ -1,4 +1,5 @@
<script lang="ts"> <script lang="ts">
import { t } from "$lib/i18n";
import { loadMarks } from "$lib/workspace/marks"; import { loadMarks } from "$lib/workspace/marks";
import BrowserSlot from "$lib/plugins/BrowserSlot.svelte"; import BrowserSlot from "$lib/plugins/BrowserSlot.svelte";
import type { TreeEntry } from "$lib/workspace/types"; import type { TreeEntry } from "$lib/workspace/types";
@@ -20,10 +21,10 @@
</script> </script>
<div class="pane"> <div class="pane">
<div class="pane-label">Bookmarks</div> <div class="pane-label">{$t("Bookmarks")}</div>
<BrowserSlot kind="bookmarks" /> <BrowserSlot kind="bookmarks" />
{#if bookmarks.length === 0} {#if bookmarks.length === 0}
<p class="placeholder">Right-click a file and choose Bookmark.</p> <p class="placeholder">{$t("Right-click a file and choose Bookmark.")}</p>
{:else} {:else}
<ul> <ul>
{#each bookmarks as rel (rel)} {#each bookmarks as rel (rel)}
+3 -2
View File
@@ -1,4 +1,5 @@
<script lang="ts"> <script lang="ts">
import { t } from "$lib/i18n";
import { tick, untrack } from "svelte"; import { tick, untrack } from "svelte";
import { getCurrentWindow } from "@tauri-apps/api/window"; import { getCurrentWindow } from "@tauri-apps/api/window";
import { pluginHost } from "$lib/plugins/registry"; import { pluginHost } from "$lib/plugins/registry";
@@ -75,12 +76,12 @@
</script> </script>
<svelte:window onkeydown={keydown} /> <svelte:window onkeydown={keydown} />
<div class="browser-window" role="application" aria-label="RuneStone browser"> <div class="browser-window" role="application" aria-label={$t("RuneStone browser")}>
<header class="header" data-tauri-drag-region> <header class="header" data-tauri-drag-region>
<TabBar {tabs} activePath={active} onSelect={select} onClose={close} onCloseTabs={close} <TabBar {tabs} activePath={active} onSelect={select} onClose={close} onCloseTabs={close}
onMove={move} onPin={pinPluginEditor} fileActions={() => []} tabActions={actions} onMove={move} onPin={pinPluginEditor} fileActions={() => []} tabActions={actions}
tabDragData={dragData} onDropTab={(data, index) => void receive(data, index)} /> tabDragData={dragData} onDropTab={(data, index) => void receive(data, index)} />
<IconButton icon="plus" label="New browser tab (Ctrl T)" disabled={!browser?.newTab || opening} onclick={() => void newTab()} /> <IconButton icon="plus" label={$t("New browser tab (Ctrl T)")} disabled={!browser?.newTab || opening} onclick={() => void newTab()} />
<div class="window-drag-space" data-tauri-drag-region></div> <div class="window-drag-space" data-tauri-drag-region></div>
<WindowControls onError={message => error = message} /> <WindowControls onError={message => error = message} />
</header> </header>
+15 -14
View File
@@ -1,4 +1,5 @@
<script lang="ts"> <script lang="ts">
import { t } from "$lib/i18n";
import { pluginHost } from "$lib/plugins/registry"; import { pluginHost } from "$lib/plugins/registry";
import type { GitLineInfo } from "$lib/git/contracts"; import type { GitLineInfo } from "$lib/git/contracts";
import EditorHost from "$lib/editor/EditorHost.svelte"; import EditorHost from "$lib/editor/EditorHost.svelte";
@@ -128,18 +129,18 @@
{#if !buffer || buffer.kind === "empty"} {#if !buffer || buffer.kind === "empty"}
<div class="empty"> <div class="empty">
{#if onCloseSplit}<IconButton icon="close" label="Close split" onclick={onCloseSplit} />{/if} {#if onCloseSplit}<IconButton icon="close" label={$t("Close split")} onclick={onCloseSplit} />{/if}
<div class="welcome-actions"> <div class="welcome-actions">
{#if hasWorkspace} {#if hasWorkspace}
<div class="welcome-row"> <div class="welcome-row">
<button onclick={onNewFile}><Icon icon="file-plus" /> New file <kbd>Ctrl N</kbd></button> <button onclick={onNewFile}><Icon icon="file-plus" /> {$t("New file")} <kbd>Ctrl N</kbd></button>
{#if onNewNote}<button onclick={onNewNote}><Icon icon="pen" /> New note</button>{/if} {#if onNewNote}<button onclick={onNewNote}><Icon icon="pen" /> {$t("New note")}</button>{/if}
<button onclick={onQuickOpen}><Icon icon="search" /> Find file <kbd>Ctrl P</kbd></button> <button onclick={onQuickOpen}><Icon icon="search" /> {$t("Find file")} <kbd>Ctrl P</kbd></button>
</div> </div>
{/if} {/if}
<div class="welcome-row"> <div class="welcome-row">
<button onclick={onOpenWorkspace}><Icon icon="folder-open" /> Open folder <kbd>Ctrl O</kbd></button> <button onclick={onOpenWorkspace}><Icon icon="folder-open" /> {$t("Open folder")} <kbd>Ctrl O</kbd></button>
{#if onOpenBrowser}<button onclick={onOpenBrowser} disabled={browserOpening}><Icon icon="globe" /> {browserOpening ? "Opening browser…" : "Open browser"}</button>{/if} {#if onOpenBrowser}<button onclick={onOpenBrowser} disabled={browserOpening}><Icon icon="globe" /> {browserOpening ? $t("Opening browser…") : $t("Open browser")}</button>{/if}
</div> </div>
</div> </div>
</div> </div>
@@ -153,25 +154,25 @@
</span> </span>
{/if} {/if}
<div class="actions" bind:this={modeControls}> <div class="actions" bind:this={modeControls}>
{#if onCloseSplit}<IconButton icon="close" label="Close split" onclick={onCloseSplit} />{/if} {#if onCloseSplit}<IconButton icon="close" label={$t("Close split")} onclick={onCloseSplit} />{/if}
{#if canPreview} {#if canPreview}
<ModeSwitcher <ModeSwitcher
label="Document view" label={$t("Document view")}
value={documentMode} value={documentMode}
options={[ options={[
{ value: "edit", label: "Edit", icon: "pen" }, { value: "edit", label: $t("Edit"), icon: "pen" },
{ value: "read", label: "Read", icon: "book-open" }, { value: "read", label: $t("Read"), icon: "book-open" },
{ value: "split", label: "Split", icon: "split" }, { value: "split", label: $t("Split"), icon: "split" },
]} ]}
onchange={setDocumentMode} onchange={setDocumentMode}
/> />
{/if} {/if}
<ModeSwitcher <ModeSwitcher
label="Editor layout" label={$t("Editor layout")}
value={chrome} value={chrome}
options={[ options={[
{ value: "Ide", label: "IDE", icon: "code" }, { value: "Ide", label: $t("IDE"), icon: "code" },
{ value: "Writing", label: "Writer", icon: "text" }, { value: "Writing", label: $t("Writer"), icon: "text" },
]} ]}
shortcut=" (Ctrl E)" shortcut=" (Ctrl E)"
onchange={(mode) => { if (mode !== chrome) onToggleChrome?.(); }} onchange={(mode) => { if (mode !== chrome) onToggleChrome?.(); }}
+42 -42
View File
@@ -1,4 +1,5 @@
<script lang="ts"> <script lang="ts">
import { t } from "$lib/i18n";
import { onMount, tick, untrack } from "svelte"; import { onMount, tick, untrack } from "svelte";
import { createNote, noteTemplates, type NoteTemplate } from "$lib/workspace/templates"; import { createNote, noteTemplates, type NoteTemplate } from "$lib/workspace/templates";
import { confirm } from "@tauri-apps/plugin-dialog"; import { confirm } from "@tauri-apps/plugin-dialog";
@@ -19,7 +20,6 @@
import { moveMarks, replayMoveMarks } from "$lib/workspace/treeMoveHistory"; import { moveMarks, replayMoveMarks } from "$lib/workspace/treeMoveHistory";
import { actionEntries, selectionRoots, setSelectedMarks, runTreeActions } from "$lib/workspace/treeActions"; import { actionEntries, selectionRoots, setSelectedMarks, runTreeActions } from "$lib/workspace/treeActions";
import { import {
dropHint,
dropPlaceAt, dropPlaceAt,
joinRel, joinRel,
parentRel, parentRel,
@@ -478,7 +478,7 @@
if (workspaceRoot !== operationRoot || error) return; if (workspaceRoot !== operationRoot || error) return;
} }
} else { } else {
const typed = await requestText("File name, including any extension", "Untitled"); const typed = await requestText($t("File name, including any extension"), "Untitled");
if (!typed) { if (!typed) {
return; return;
} }
@@ -685,10 +685,10 @@
async function deleteEntries(entries: TreeEntry[]) { async function deleteEntries(entries: TreeEntry[]) {
const roots = selectionRoots(entries); const roots = selectionRoots(entries);
const message = entries.length === 1 const message = entries.length === 1
? `Permanently delete ${entries[0].name}${entries[0].kind === "folder" ? " and everything inside it" : ""}?` ? $t(entries[0].kind === "folder" ? "Permanently delete {name} and everything inside it?" : "Permanently delete {name}?", { name: entries[0].name })
: `Permanently delete ${entries.length} selected items${entries.some(entry => entry.kind === "folder") ? " and all contents of selected folders" : ""}?\n\n${roots.map(entry => entry.rel_path).join("\n")}`; : $t(entries.some(entry => entry.kind === "folder") ? "Permanently delete {count} selected items and all contents of selected folders?" : "Permanently delete {count} selected items?", { count: entries.length }) + "\n\n" + roots.map(entry => entry.rel_path).join("\n");
try { try {
if (!await confirm(message, { title: "Delete from disk", kind: "warning" })) return; if (!await confirm(message, { title: $t("Delete from disk"), kind: "warning" })) return;
const result = await runTreeActions(roots, async entry => { const result = await runTreeActions(roots, async entry => {
await workspaceDelete(entry.rel_path); await workspaceDelete(entry.rel_path);
forgetFolder(entry.rel_path); forgetFolder(entry.rel_path);
@@ -696,7 +696,7 @@
}); });
for (const parent of new Set(roots.map(entry => parentRel(entry.rel_path)))) await load(parent); for (const parent of new Set(roots.map(entry => parentRel(entry.rel_path)))) await load(parent);
error = result.failures.length ? result.failures.join("\n") : null; error = result.failures.length ? result.failures.join("\n") : null;
onStatus?.(`Deleted ${result.completed.length} of ${roots.length} items`); onStatus?.($t("Deleted {count} of {total} items", { count: result.completed.length, total: roots.length }));
} catch (err) { } catch (err) {
error = err instanceof Error ? err.message : String(err); error = err instanceof Error ? err.message : String(err);
} }
@@ -713,16 +713,16 @@
return [ return [
{ {
kind: "action", kind: "action",
label: "New file…", label: $t("New file…"),
icon: "file-plus", icon: "file-plus",
run: () => { void createIn(parent, "file"); }, run: () => { void createIn(parent, "file"); },
}, },
...(templates.length || onManageTemplates ? [{ kind: "group" as const, label: "New note", icon: "file-plus" as const, run: () => { void fromTemplate(); }, items: [ ...(templates.length || onManageTemplates ? [{ kind: "group" as const, label: $t("New note"), icon: "file-plus" as const, run: () => { void fromTemplate(); }, items: [
{ kind: "action" as const, label: "Blank note", icon: "file-plus" as const, run: () => { void fromTemplate(); } }, { kind: "action" as const, label: $t("Blank note"), icon: "file-plus" as const, run: () => { void fromTemplate(); } },
...templates.map(template => ({ kind: "action" as const, label: template.name, icon: "file-plus" as const, run: () => { void fromTemplate(template); } })), ...templates.map(template => ({ kind: "action" as const, label: template.name, icon: "file-plus" as const, run: () => { void fromTemplate(template); } })),
...(onManageTemplates ? [{ kind: "sep" as const }, { kind: "action" as const, label: "Manage templates…", icon: "copy" as const, run: onManageTemplates }] : []), ...(onManageTemplates ? [{ kind: "sep" as const }, { kind: "action" as const, label: $t("Manage templates…"), icon: "copy" as const, run: onManageTemplates }] : []),
] }] : [{ kind: "action" as const, label: "New note", icon: "file-plus" as const, run: () => { void fromTemplate(); } }]), ] }] : [{ kind: "action" as const, label: $t("New note"), icon: "file-plus" as const, run: () => { void fromTemplate(); } }]),
{ kind: "action", label: "New folder", icon: "folder-plus", run: () => { void createIn(parent, "folder"); } }, { kind: "action", label: $t("New folder"), icon: "folder-plus", run: () => { void createIn(parent, "folder"); } },
...$pluginDocumentTypes.filter(item => item.type.create).map(({ owner, type }): MenuItem => ({ ...$pluginDocumentTypes.filter(item => item.type.create).map(({ owner, type }): MenuItem => ({
kind: "action", label: type.create!.label, icon: type.icon === "kanban" ? "kanban" : "file-plus", kind: "action", label: type.create!.label, icon: type.icon === "kanban" ? "kanban" : "file-plus",
run: () => { void (async () => { run: () => { void (async () => {
@@ -730,7 +730,7 @@
const typed = await requestText(create.label, create.defaultName); const typed = await requestText(create.label, create.defaultName);
if (typed === null) return; if (typed === null) return;
const name = typed.trim().replace(new RegExp(`\\.${create.extension}$`, "i"), ""); const name = typed.trim().replace(new RegExp(`\\.${create.extension}$`, "i"), "");
if (!name || name.length > 100 || /[<>:"/\\|?*\x00-\x1f]/.test(name) || /[. ]$/.test(name) || /^(con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(name)) { error = "Enter a valid document name."; return; } if (!name || name.length > 100 || /[<>:"/\\|?*\x00-\x1f]/.test(name) || /[. ]$/.test(name) || /^(con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(name)) { error = $t("Enter a valid document name."); return; }
const fileName = `${name}.${create.extension}`; const fileName = `${name}.${create.extension}`;
const path = joinRel(parent, fileName); const path = joinRel(parent, fileName);
try { try {
@@ -746,11 +746,11 @@
function folderActions(parent: string): MenuItem[] { function folderActions(parent: string): MenuItem[] {
return [ return [
{ kind: "action", label: "Open in terminal", icon: "terminal", run: () => { void workspaceOpenTerminal(parent).catch(reason => error = String(reason)); } }, { kind: "action", label: $t("Open in terminal"), icon: "terminal", run: () => { void workspaceOpenTerminal(parent).catch(reason => error = String(reason)); } },
{ kind: "action", label: "Paste", icon: "paste", disabled: !clipboard || clipboard.root !== workspaceRoot || moving, run: () => { void pasteEntries(parent); } }, { kind: "action", label: $t("Paste"), icon: "paste", disabled: !clipboard || clipboard.root !== workspaceRoot || moving, run: () => { void pasteEntries(parent); } },
{ kind: "sep" }, { kind: "sep" },
{ kind: "action", label: undoMoves.at(-1)?.action === "rename" ? "Undo rename" : "Undo file move", icon: "undo", disabled: !undoMoves.length || moving, run: () => { void replayMoves(); } }, { kind: "action", label: undoMoves.at(-1)?.action === "rename" ? $t("Undo rename") : $t("Undo file move"), icon: "undo", disabled: !undoMoves.length || moving, run: () => { void replayMoves(); } },
{ kind: "action", label: redoMoves.at(-1)?.action === "rename" ? "Redo rename" : "Redo file move", icon: "redo", disabled: !redoMoves.length || moving, run: () => { void replayMoves(true); } }, { kind: "action", label: redoMoves.at(-1)?.action === "rename" ? $t("Redo rename") : $t("Redo file move"), icon: "redo", disabled: !redoMoves.length || moving, run: () => { void replayMoves(true); } },
]; ];
} }
@@ -763,7 +763,7 @@
{ kind: "sep" }, { kind: "sep" },
{ {
kind: "action", kind: "action",
label: "Show in Explorer", label: $t("Show in Explorer"),
icon: "folder", icon: "folder",
run: () => { run: () => {
void workspaceReveal("").catch((err) => { void workspaceReveal("").catch((err) => {
@@ -784,25 +784,25 @@
return [ return [
...createItems, ...createItems,
...(!multiple && entry.kind === "file" && /\.md$/i.test(entry.name) && onSaveTemplate ? [ ...(!multiple && entry.kind === "file" && /\.md$/i.test(entry.name) && onSaveTemplate ? [
{ kind: "action" as const, label: "Save as template", icon: "copy" as const, run: () => onSaveTemplate?.(entry) }, { kind: "action" as const, label: $t("Save as template"), icon: "copy" as const, run: () => onSaveTemplate?.(entry) },
] : []), ] : []),
...(!multiple && entry.kind === "file" ? [ ...(!multiple && entry.kind === "file" ? [
{ kind: "action" as const, label: "Open in new tab", icon: "file-plus" as const, run: () => onOpenFile(entry, true) }, { kind: "action" as const, label: $t("Open in new tab"), icon: "file-plus" as const, run: () => onOpenFile(entry, true) },
{ kind: "action" as const, label: "Open in default app", icon: "external" as const, run: () => { void workspaceOpenDefault(entry.rel_path).catch(reason => error = String(reason)); } }, { kind: "action" as const, label: $t("Open in default app"), icon: "external" as const, run: () => { void workspaceOpenDefault(entry.rel_path).catch(reason => error = String(reason)); } },
] : []), ] : []),
...folderActions(entry.kind === "folder" ? entry.rel_path : parentRel(entry.rel_path)), ...folderActions(entry.kind === "folder" ? entry.rel_path : parentRel(entry.rel_path)),
{ kind: "sep" }, { kind: "sep" },
{ kind: "action", label: "Cut", icon: "cut", run: () => { clipboard = { root: workspaceRoot, paths: selectionRoots(entries).map(item => item.rel_path), cut: true }; } }, { kind: "action", label: $t("Cut"), icon: "cut", run: () => { clipboard = { root: workspaceRoot, paths: selectionRoots(entries).map(item => item.rel_path), cut: true }; } },
{ kind: "action", label: "Copy", icon: "copy", run: () => { clipboard = { root: workspaceRoot, paths: selectionRoots(entries).map(item => item.rel_path), cut: false }; } }, { kind: "action", label: $t("Copy"), icon: "copy", run: () => { clipboard = { root: workspaceRoot, paths: selectionRoots(entries).map(item => item.rel_path), cut: false }; } },
{ {
kind: "action", kind: "action",
label: multiple ? `Make copies (${entries.length})` : "Make a copy", label: multiple ? $t("Make copies ({count})", { count: entries.length }) : $t("Make a copy"),
icon: "copy", icon: "copy",
run: () => { void copyEntries(entries); }, run: () => { void copyEntries(entries); },
}, },
{ {
kind: "action", kind: "action",
label: bookmarked ? (multiple ? "Remove bookmarks" : "Remove bookmark") : "Bookmark", label: bookmarked ? (multiple ? $t("Remove bookmarks") : $t("Remove bookmark")) : $t("Bookmark"),
icon: "bookmark", icon: "bookmark",
run: () => { run: () => {
void persistMarks({ void persistMarks({
@@ -814,7 +814,7 @@
{ kind: "sep" }, { kind: "sep" },
{ {
kind: "action", kind: "action",
label: multiple ? "Copy workspace paths" : "Copy workspace path", label: multiple ? $t("Copy workspace paths") : $t("Copy workspace path"),
icon: "copy", icon: "copy",
run: () => { run: () => {
void copyText(entries.map(item => item.rel_path).join("\n"), multiple ? "workspace paths" : "workspace path"); void copyText(entries.map(item => item.rel_path).join("\n"), multiple ? "workspace paths" : "workspace path");
@@ -822,7 +822,7 @@
}, },
{ {
kind: "action", kind: "action",
label: multiple ? "Copy system paths" : "Copy system path", label: multiple ? $t("Copy system paths") : $t("Copy system path"),
icon: "copy", icon: "copy",
run: () => { run: () => {
void (async () => { void (async () => {
@@ -837,7 +837,7 @@
}, },
{ {
kind: "action", kind: "action",
label: "Show in Explorer", label: $t("Show in Explorer"),
icon: "folder", icon: "folder",
run: () => { run: () => {
void (async () => { void (async () => {
@@ -849,7 +849,7 @@
{ kind: "sep" }, { kind: "sep" },
{ {
kind: "action", kind: "action",
label: pinned ? "Unpin" : "Pin", label: pinned ? $t("Unpin") : $t("Pin"),
icon: "pin", icon: "pin",
run: () => { run: () => {
void persistMarks({ void persistMarks({
@@ -860,7 +860,7 @@
}, },
{ {
kind: "action", kind: "action",
label: "Rename", label: $t("Rename"),
icon: "rename", icon: "rename",
disabled: multiple, disabled: multiple,
run: () => { run: () => {
@@ -869,7 +869,7 @@
}, },
{ {
kind: "action", kind: "action",
label: multiple ? `Delete (${entries.length})` : "Delete", label: multiple ? $t("Delete ({count})", { count: entries.length }) : $t("Delete"),
icon: "trash", icon: "trash",
run: () => { void deleteEntries(entries); }, run: () => { void deleteEntries(entries); },
}, },
@@ -881,16 +881,16 @@
<div class="wrap"> <div class="wrap">
<div class="ribbon tree-tools"> <div class="ribbon tree-tools">
<IconButton icon="file-plus" label="New file" onclick={() => void createIn("", "file")} /> <IconButton icon="file-plus" label={$t("New file")} onclick={() => void createIn("", "file")} />
<IconButton icon="folder-plus" label="New folder" onclick={() => void createIn("", "folder")} /> <IconButton icon="folder-plus" label={$t("New folder")} onclick={() => void createIn("", "folder")} />
<IconButton <IconButton
icon="sort" icon="sort"
label={sortMode === "custom" ? "Sort: custom" : sortMode === "name" ? "Sort: name" : "Sort: name Z-A"} label={sortMode === "custom" ? $t("Sort: custom") : sortMode === "name" ? $t("Sort: name") : $t("Sort: name Z-A")}
onclick={cycleSort} onclick={cycleSort}
/> />
<IconButton <IconButton
icon={allCollapsed ? "unfold" : "fold"} icon={allCollapsed ? "unfold" : "fold"}
label={allCollapsed ? "Expand all" : "Collapse all"} label={allCollapsed ? $t("Expand all") : $t("Collapse all")}
onclick={() => { onclick={() => {
if (allCollapsed) { if (allCollapsed) {
void expandAll(); void expandAll();
@@ -905,7 +905,7 @@
class="tree" class="tree"
tabindex="-1" tabindex="-1"
role="navigation" role="navigation"
aria-label="Workspace files" aria-label={$t("Workspace files")}
oncontextmenu={(event) => { oncontextmenu={(event) => {
event.preventDefault(); event.preventDefault();
menu = { x: event.clientX, y: event.clientY, entry: null }; menu = { x: event.clientX, y: event.clientY, entry: null };
@@ -915,10 +915,10 @@
<p class="error">{error}</p> <p class="error">{error}</p>
{/if} {/if}
{#if loading && !childrenMap[""]} {#if loading && !childrenMap[""]}
<p class="muted">Loading…</p> <p class="muted">{$t("Loading…")}</p>
{/if} {/if}
{#if childrenMap[""]} {#if childrenMap[""]}
<ul role="tree" aria-label="Workspace files" aria-multiselectable="true"> <ul role="tree" aria-label={$t("Workspace files")} aria-multiselectable="true">
{#each childrenMap[""] as entry (entry.rel_path)} {#each childrenMap[""] as entry (entry.rel_path)}
<TreeNode <TreeNode
{entry} {entry}
@@ -952,18 +952,18 @@
{#if dragRel && dragPoint} {#if dragRel && dragPoint}
{@const landing = dropTarget ? findEntry(dropTarget.rel) : null} {@const landing = dropTarget ? findEntry(dropTarget.rel) : null}
<div class="drag-ghost" style:left="{dragPoint.x + 12}px" style:top="{dragPoint.y + 12}px"> <div class="drag-ghost" style:left="{dragPoint.x + 12}px" style:top="{dragPoint.y + 12}px">
<span>{dragEntries.length > 1 ? `${dragEntries.length} items` : dragRel.split("/").pop()}</span> <span>{dragEntries.length > 1 ? $t("{count} items", { count: dragEntries.length }) : dragRel.split("/").pop()}</span>
{#if imageLanding} {#if imageLanding}
<span class="hint">{isImagePath(dragRel ?? "") ? "Insert image" : "Insert link"}</span> <span class="hint">{isImagePath(dragRel ?? "") ? $t("Insert image") : $t("Insert link")}</span>
{:else if landing && dropTarget} {:else if landing && dropTarget}
<span class="hint">{dropHint(landing.name, dropTarget.place)}</span> <span class="hint">{$t(dropTarget.place === "inside" ? "Into {name}" : dropTarget.place === "before" ? "Before {name}" : "After {name}", { name: landing.name })}</span>
{/if} {/if}
</div> </div>
{/if} {/if}
{#if menu} {#if menu}
<ContextMenu <ContextMenu
label="File actions" label={$t("File actions")}
x={menu.x} x={menu.x}
y={menu.y} y={menu.y}
items={menuItems(menu.entry)} items={menuItems(menu.entry)}
+7 -6
View File
@@ -1,4 +1,5 @@
<script lang="ts"> <script lang="ts">
import { t } from "$lib/i18n";
import { pluginHost } from "$lib/plugins/registry"; import { pluginHost } from "$lib/plugins/registry";
import { tick, type Snippet } from "svelte"; import { tick, type Snippet } from "svelte";
import { workspaceReadDataUrl } from "$lib/workspace/api"; import { workspaceReadDataUrl } from "$lib/workspace/api";
@@ -112,13 +113,13 @@
} }
} }
button.dataset.copied = "true"; button.dataset.copied = "true";
button.setAttribute("aria-label", "Copied"); button.setAttribute("aria-label", $t("Copied"));
button.title = "Copied"; button.title = $t("Copied");
window.setTimeout(() => { window.setTimeout(() => {
if (button.isConnected) { if (button.isConnected) {
delete button.dataset.copied; delete button.dataset.copied;
button.setAttribute("aria-label", "Copy code"); button.setAttribute("aria-label", $t("Copy code"));
button.title = "Copy code"; button.title = $t("Copy code");
} }
}, 1200); }, 1200);
} }
@@ -181,12 +182,12 @@
<h1 class="document-title">{markdownTitle(noteRel)}</h1> <h1 class="document-title">{markdownTitle(noteRel)}</h1>
{#if onEditBlock} {#if onEditBlock}
{#each sections.filter(section => !editing || section.start < editing.start) as section (section.start)} {#each sections.filter(section => !editing || section.start < editing.start) as section (section.start)}
<div class="md-edit-block" role="button" tabindex="0" aria-label="Edit document block" data-start={section.start} data-end={section.end}>{@html section.html}</div> <div class="md-edit-block" role="button" tabindex="0" aria-label={$t("Edit document block")} data-start={section.start} data-end={section.end}>{@html section.html}</div>
{/each} {/each}
{#if editing && blockEditor} {#if editing && blockEditor}
{@render blockEditor()} {@render blockEditor()}
{#each sections.filter(section => section.start >= editing.end && section.end > editing.end) as section (section.start)} {#each sections.filter(section => section.start >= editing.end && section.end > editing.end) as section (section.start)}
<div class="md-edit-block" role="button" tabindex="0" aria-label="Edit document block" data-start={section.start} data-end={section.end}>{@html section.html}</div> <div class="md-edit-block" role="button" tabindex="0" aria-label={$t("Edit document block")} data-start={section.start} data-end={section.end}>{@html section.html}</div>
{/each} {/each}
{/if} {/if}
{:else} {:else}
+9 -8
View File
@@ -1,4 +1,5 @@
<script lang="ts"> <script lang="ts">
import { t } from "$lib/i18n";
import { tick } from "svelte"; import { tick } from "svelte";
import type { OutlineItem } from "$lib/workspace/outline"; import type { OutlineItem } from "$lib/workspace/outline";
import Icon from "$lib/ui/Icon.svelte"; import Icon from "$lib/ui/Icon.svelte";
@@ -47,27 +48,27 @@
</script> </script>
<!-- svelte-ignore a11y_no_noninteractive_tabindex, a11y_no_noninteractive_element_interactions (The outline accepts focus for pane-local search shortcuts.) --> <!-- svelte-ignore a11y_no_noninteractive_tabindex, a11y_no_noninteractive_element_interactions (The outline accepts focus for pane-local search shortcuts.) -->
<section class="outline" aria-label="Outline" tabindex="0" bind:this={pane} onkeydown={keydown}> <section class="outline" aria-label={$t("Outline")} tabindex="0" bind:this={pane} onkeydown={keydown}>
<div class="pane-label"> <div class="pane-label">
<span>Outline</span> <span>{$t("Outline")}</span>
<IconButton icon="search" label="Find in outline (Ctrl+F)" active={searchOpen} onclick={() => void openSearch()} /> <IconButton icon="search" label={$t("Find in outline (Ctrl+F)")} active={searchOpen} onclick={() => void openSearch()} />
</div> </div>
{#if searchOpen} {#if searchOpen}
<div class="rs-find-bar outline-search"> <div class="rs-find-bar outline-search">
<div class="rs-find-row"> <div class="rs-find-row">
<div class="rs-find-field"> <div class="rs-find-field">
<Icon icon="search" /> <Icon icon="search" />
<input bind:this={searchInput} bind:value={query} aria-label="Find in outline" placeholder="Find in outline" /> <input bind:this={searchInput} bind:value={query} aria-label={$t("Find in outline")} placeholder={$t("Find in outline")} />
</div> </div>
<IconButton icon="close" label="Close outline find (Escape)" onclick={closeSearch} /> <IconButton icon="close" label={$t("Close outline find (Escape)")} onclick={closeSearch} />
</div> </div>
<span class="match-count" role="status">{visibleItems.length} of {items.length} headings or symbols</span> <span class="match-count" role="status">{$t("{visible} of {total} headings or symbols", { visible: visibleItems.length, total: items.length })}</span>
</div> </div>
{/if} {/if}
{#if items.length === 0} {#if items.length === 0}
<p class="placeholder">No headings or symbols in this file.</p> <p class="placeholder">{$t("No headings or symbols in this file.")}</p>
{:else if visibleItems.length === 0} {:else if visibleItems.length === 0}
<p class="placeholder">No matching headings or symbols.</p> <p class="placeholder">{$t("No matching headings or symbols.")}</p>
{:else} {:else}
<ul> <ul>
{#each visibleItems as item (item.line + item.text)} {#each visibleItems as item (item.line + item.text)}
+5 -4
View File
@@ -1,4 +1,5 @@
<script lang="ts"> <script lang="ts">
import { t } from "$lib/i18n";
import { workspaceList } from "$lib/workspace/api"; import { workspaceList } from "$lib/workspace/api";
import type { TreeEntry } from "$lib/workspace/types"; import type { TreeEntry } from "$lib/workspace/types";
import { onMount } from "svelte"; import { onMount } from "svelte";
@@ -33,11 +34,11 @@
}); });
</script> </script>
<dialog class="rs-picker" bind:this={dialog} aria-label={purpose} onpointerdown={(event) => { <dialog class="rs-picker" bind:this={dialog} aria-label={$t(purpose)} onpointerdown={(event) => {
const bounds = dialog.getBoundingClientRect(); const bounds = dialog.getBoundingClientRect();
if (event.target === dialog && (event.clientX < bounds.left || event.clientX > bounds.right || event.clientY < bounds.top || event.clientY > bounds.bottom)) onClose(); if (event.target === dialog && (event.clientX < bounds.left || event.clientX > bounds.right || event.clientY < bounds.top || event.clientY > bounds.bottom)) onClose();
}} oncancel={onClose}> }} oncancel={onClose}>
<input bind:this={input} bind:value={query} oninput={() => selected = 0} aria-label="Find a file" placeholder="Find a note or code file…" onkeydown={(event) => { <input bind:this={input} bind:value={query} oninput={() => selected = 0} aria-label={$t("Find a file")} placeholder={$t("Find a note or code file…")} onkeydown={(event) => {
if (event.key === "ArrowDown" || event.key === "ArrowUp") { if (event.key === "ArrowDown" || event.key === "ArrowUp") {
event.preventDefault(); selected = Math.max(0, Math.min(matches.length - 1, selected + (event.key === "ArrowDown" ? 1 : -1))); event.preventDefault(); selected = Math.max(0, Math.min(matches.length - 1, selected + (event.key === "ArrowDown" ? 1 : -1)));
dialog.querySelector(`[data-index="${selected}"]`)?.scrollIntoView({ block: "nearest" }); dialog.querySelector(`[data-index="${selected}"]`)?.scrollIntoView({ block: "nearest" });
@@ -48,9 +49,9 @@
{#each matches as entry, index (entry.rel_path)} {#each matches as entry, index (entry.rel_path)}
<button class="rs-picker-row" data-index={index} aria-current={selected === index ? 'true' : undefined} onclick={() => pick(entry)}><span class="file-detail"><strong>{entry.name}</strong><span class="rs-picker-hint">{entry.rel_path}</span></span></button> <button class="rs-picker-row" data-index={index} aria-current={selected === index ? 'true' : undefined} onclick={() => pick(entry)}><span class="file-detail"><strong>{entry.name}</strong><span class="rs-picker-hint">{entry.rel_path}</span></span></button>
{/each} {/each}
{#if !matches.length}<p>{loading ? "Finding files…" : "No matching files."}</p>{/if} {#if !matches.length}<p>{loading ? $t("Finding files…") : $t("No matching files.")}</p>{/if}
</div> </div>
<footer>{error || `${files.length} files${loading ? " · indexing…" : ""}`} <span>↑ ↓ select · Enter {actionLabel} · Esc close</span></footer> <footer>{error || `${files.length} files${loading ? $t(" · indexing…") : ""}`} <span>{$t("↑ ↓ select · Enter {action} · Esc close", { action: $t(actionLabel) })}</span></footer>
</dialog> </dialog>
<style> <style>
+4 -3
View File
@@ -1,4 +1,5 @@
<script lang="ts"> <script lang="ts">
import { t } from "$lib/i18n";
import IconButton from "$lib/ui/IconButton.svelte"; import IconButton from "$lib/ui/IconButton.svelte";
import { workspaceSearch, type SearchHit } from "$lib/workspace/api"; import { workspaceSearch, type SearchHit } from "$lib/workspace/api";
import type { TreeEntry } from "$lib/workspace/types"; import type { TreeEntry } from "$lib/workspace/types";
@@ -36,7 +37,7 @@
</script> </script>
<div class="pane"> <div class="pane">
<div class="pane-label">Search</div> <div class="pane-label">{$t("Search")}</div>
<form <form
class="bar" class="bar"
onsubmit={(event) => { onsubmit={(event) => {
@@ -44,8 +45,8 @@
void run(); void run();
}} }}
> >
<input bind:value={query} placeholder="Search files and notes" /> <input bind:value={query} placeholder={$t("Search files and notes")} />
<IconButton icon="search" label="Search workspace" type="submit" /> <IconButton icon="search" label={$t("Search workspace")} type="submit" />
</form> </form>
{#if error} {#if error}
<p class="error">{error}</p> <p class="error">{error}</p>
+50 -33
View File
@@ -1,4 +1,7 @@
<script lang="ts"> <script lang="ts">
import { t, locale, LANGUAGES, setLocale } from "$lib/i18n";
import { showActionMenu } from "$lib/ui/managedActionMenu";
import { onDestroy } from "svelte";
import PluginManager from "$lib/plugins/PluginManager.svelte"; import PluginManager from "$lib/plugins/PluginManager.svelte";
import AppearanceSettings from "$lib/theme/AppearanceSettings.svelte"; import AppearanceSettings from "$lib/theme/AppearanceSettings.svelte";
import BrowserSlot from "$lib/plugins/BrowserSlot.svelte"; import BrowserSlot from "$lib/plugins/BrowserSlot.svelte";
@@ -20,13 +23,23 @@
onSave: (value: AppSettings) => void; onSave: (value: AppSettings) => void;
onClose: () => void; onClose: () => void;
} = $props(); } = $props();
let closeLanguage = () => {};
onDestroy(() => closeLanguage());
function languagePicker(event: MouseEvent) {
closeLanguage();
const anchor = event.currentTarget as HTMLButtonElement;
const bounds = anchor.getBoundingClientRect();
closeLanguage = showActionMenu({ x: bounds.left, y: bounds.bottom + 4, label: $t("Language"), parent: dialog,
items: LANGUAGES.map(item => ({ label: item.name, radio: true, checked: $locale === item.id,
run: () => { try { setLocale(item.id); error = ""; message = $t("Changes saved."); } catch { error = $t("Could not save language settings."); } } })) }).close;
}
type Section = string; type Section = string;
const sections: { id: Section; label: string; icon: IconName; keywords: string }[] = [ const sections: { id: Section; label: string; icon: IconName; keywords: string }[] = $derived([
{ id: "about", label: "Help and about", icon: "help", keywords: "help about version shortcuts keyboard guide" }, { id: "about", label: $t("Help and about"), icon: "help", keywords: "help about version shortcuts keyboard guide" },
{ id: "general", label: "General", icon: "settings", keywords: "auto-save autosave save interval seconds files" }, { id: "general", label: $t("General"), icon: "settings", keywords: "auto-save autosave save interval seconds files language français 日本語 简体中文" },
{ id: "appearance", label: "Appearance", icon: "sun", keywords: "theme colors light dark Claude Sakura Harvest Moon Crimson Pilot Silver Serpent" }, { id: "appearance", label: $t("Appearance"), icon: "sun", keywords: "theme colors light dark Claude Sakura Harvest Moon Crimson Pilot Silver Serpent" },
{ id: "plugins", label: "Plug-ins", icon: "puzzle", keywords: "plugins extensions community" }, { id: "plugins", label: $t("Plug-ins"), icon: "puzzle", keywords: "plugins extensions community" },
]; ]);
let section = $state<Section>(untrack(() => help ? "about" : "general")); let section = $state<Section>(untrack(() => help ? "about" : "general"));
let query = $state(""); let query = $state("");
let seconds = $state<number | undefined>(untrack(() => settings.autosaveSeconds)); let seconds = $state<number | undefined>(untrack(() => settings.autosaveSeconds));
@@ -39,7 +52,7 @@
label: tool.title, icon: "settings" as const, label: tool.title, icon: "settings" as const,
keywords: `${$installedPlugins.plugins.find(row => row.manifest.id === tool.owner)?.manifest.name ?? tool.owner} settings configuration`, keywords: `${$installedPlugins.plugins.find(row => row.manifest.id === tool.owner)?.manifest.name ?? tool.owner} settings configuration`,
}))); })));
const matches = $derived([...sections, ...(browserEnabled ? [{ id: "browser" as const, label: "Browser", icon: "globe" as const, keywords: "browser profiles search cookies cache web privacy" }] : []), ...pluginSections].filter(item => `${item.label} ${item.keywords}`.toLowerCase().includes(query.trim().toLowerCase()))); const matches = $derived([...sections, ...(browserEnabled ? [{ id: "browser" as const, label: $t("Browser"), icon: "globe" as const, keywords: "browser profiles search cookies cache web privacy" }] : []), ...pluginSections].filter(item => `${item.label} ${item.keywords}`.toLowerCase().includes(query.trim().toLowerCase())));
const selected = $derived(matches.find(item => item.id === section) ?? matches[0]); const selected = $derived(matches.find(item => item.id === section) ?? matches[0]);
const selectedPlugin = $derived(pluginSections.find(item => item.id === selected?.id)); const selectedPlugin = $derived(pluginSections.find(item => item.id === selected?.id));
@@ -52,13 +65,13 @@
function apply(value: AppSettings) { function apply(value: AppSettings) {
error = ""; error = "";
try { onSave(value); message = "Changes saved."; } try { onSave(value); message = $t("Changes saved."); }
catch { error = "Could not save these settings. Your previous settings still apply. Try again."; message = ""; } catch { error = $t("Could not save these settings. Your previous settings still apply. Try again."); message = ""; }
} }
function changeInterval() { function changeInterval() {
if (!validAutosaveSeconds(seconds)) { if (!validAutosaveSeconds(seconds)) {
error = "Choose a whole number from 1 to 300 seconds."; error = $t("Choose a whole number from 1 to 300 seconds.");
message = ""; message = "";
return; return;
} }
@@ -80,52 +93,54 @@
<dialog bind:this={dialog} class:help class:standalone aria-labelledby="settings-title" onkeydown={trapFocus} oncancel={event => { if (event.target === dialog) { event.preventDefault(); onClose(); } }}> <dialog bind:this={dialog} class:help class:standalone aria-labelledby="settings-title" onkeydown={trapFocus} oncancel={event => { if (event.target === dialog) { event.preventDefault(); onClose(); } }}>
<header class:window-header={!!windowControls} data-tauri-drag-region={windowControls ? true : undefined}> <header class:window-header={!!windowControls} data-tauri-drag-region={windowControls ? true : undefined}>
<h1 id="settings-title" data-tauri-drag-region={windowControls ? true : undefined}>{help ? "Help and about" : "Settings"}</h1> <h1 id="settings-title" data-tauri-drag-region={windowControls ? true : undefined}>{help ? $t("Help and about") : $t("Settings")}</h1>
{#if windowControls} {#if windowControls}
{@render windowControls()} {@render windowControls()}
{:else} {:else}
<IconButton icon="close" label={help ? "Close help" : "Close settings"} onclick={onClose} /> <IconButton icon="close" label={help ? $t("Close help") : $t("Close settings")} onclick={onClose} />
{/if} {/if}
</header> </header>
<div class="body"> <div class="body">
{#if !help} {#if !help}
<aside> <aside>
<label class="search"><Icon icon="search" /><input aria-label="Search settings" placeholder="Search settings…" bind:value={query} /></label> <label class="search"><Icon icon="search" /><input aria-label={$t("Search settings")} placeholder={$t("Search settings…")} bind:value={query} /></label>
<p class="nav-heading">Preferences</p> <p class="nav-heading">{$t("Preferences")}</p>
<nav aria-label="Settings categories"> <nav aria-label={$t("Settings categories")}>
{#each matches as item} {#each matches as item}
<button class:active={selected?.id === item.id} aria-current={selected?.id === item.id ? "page" : undefined} onclick={() => select(item.id)}><Icon icon={item.icon} />{item.label}</button> <button class:active={selected?.id === item.id} aria-current={selected?.id === item.id ? "page" : undefined} onclick={() => select(item.id)}><Icon icon={item.icon} />{item.label}</button>
{/each} {/each}
</nav> </nav>
<p class="scope">For all workspaces on this device.</p> <p class="scope">{$t("For all workspaces on this device.")}</p>
</aside> </aside>
{/if} {/if}
<div class="content"> <div class="content">
{#if windowError}<p class="error" role="alert">{windowError}</p>{/if} {#if windowError}<p class="error" role="alert">{windowError}</p>{/if}
{#if !selected} {#if !selected}
<h2>No settings found</h2> <h2>{$t("No settings found")}</h2>
<p>Try “save”, “plug-ins”, or “help”.</p> <p>{$t("Try “save”, “plug-ins”, or “help”.")}</p>
<button class="text-button" onclick={() => query = ""}>Clear search</button> <button class="text-button" onclick={() => query = ""}>{$t("Clear search")}</button>
{:else if selected.id === "general"} {:else if selected.id === "general"}
<h2>General</h2> <h2>{$t("General")}</h2>
<p class="intro">Choose how RuneStone saves your work.</p> <p class="intro">{$t("Choose how RuneStone saves your work.")}</p>
<h3>Files</h3> <h3>{$t('Language')}</h3>
<div class="card"><div class="setting-row language-row"><div><label for="language-picker">{$t('Display language')}</label><p>{$t('Choose the language for RuneStone controls.')}</p></div><button id="language-picker" class="text-button language-picker" aria-haspopup="menu" onclick={languagePicker}><Icon icon="globe" />{LANGUAGES.find(item => item.id === $locale)?.name}<Icon icon="chevron-down" /></button></div></div>
<h3>{$t("Files")}</h3>
<div class="card"> <div class="card">
<div class="setting-row"> <div class="setting-row">
<div><label for="show-internal-folder">Show .runestone folder</label><p id="internal-folder-description">Show workspace settings and plugin data in the file tree.</p></div> <div><label for="show-internal-folder">{$t("Show .runestone folder")}</label><p id="internal-folder-description">{$t("Show workspace settings and plugin data in the file tree.")}</p></div>
<input id="show-internal-folder" class="switch" type="checkbox" role="switch" aria-describedby="internal-folder-description" checked={settings.showInternalFolder} onchange={event => apply({ ...settings, showInternalFolder: event.currentTarget.checked })} /> <input id="show-internal-folder" class="switch" type="checkbox" role="switch" aria-describedby="internal-folder-description" checked={settings.showInternalFolder} onchange={event => apply({ ...settings, showInternalFolder: event.currentTarget.checked })} />
</div> </div>
<div class="setting-row"> <div class="setting-row">
<div><label for="autosave-enabled">Auto-save</label><p id="autosave-description">Save changed notes and scripts, including background tabs.</p></div> <div><label for="autosave-enabled">{$t("Auto-save")}</label><p id="autosave-description">{$t("Save changed notes and scripts, including background tabs.")}</p></div>
<input id="autosave-enabled" class="switch" type="checkbox" role="switch" aria-describedby="autosave-description" checked={settings.autosaveEnabled} onchange={event => { apply({ ...settings, autosaveEnabled: event.currentTarget.checked }); event.currentTarget.checked = settings.autosaveEnabled; }} /> <input id="autosave-enabled" class="switch" type="checkbox" role="switch" aria-describedby="autosave-description" checked={settings.autosaveEnabled} onchange={event => { apply({ ...settings, autosaveEnabled: event.currentTarget.checked }); event.currentTarget.checked = settings.autosaveEnabled; }} />
</div> </div>
<div class="setting-row"> <div class="setting-row">
<div><label for="autosave-seconds">Auto-save interval</label><p id="interval-description">Time between saves, even while you type. Choose 1–300 seconds.</p></div> <div><label for="autosave-seconds">{$t("Auto-save interval")}</label><p id="interval-description">{$t("Time between saves, even while you type. Choose 1–300 seconds.")}</p></div>
<div class="interval"><input id="autosave-seconds" type="number" min={MIN_AUTOSAVE_SECONDS} max={MAX_AUTOSAVE_SECONDS} step="1" required disabled={!settings.autosaveEnabled} aria-describedby="interval-description" aria-invalid={!!error} bind:value={seconds} onchange={changeInterval} /><span>seconds</span></div> <div class="interval"><input id="autosave-seconds" type="number" min={MIN_AUTOSAVE_SECONDS} max={MAX_AUTOSAVE_SECONDS} step="1" required disabled={!settings.autosaveEnabled} aria-describedby="interval-description" aria-invalid={!!error} bind:value={seconds} onchange={changeInterval} /><span>{$t("seconds")}</span></div>
</div> </div>
</div> </div>
<p class="note">{settings.autosaveEnabled ? "Only changed files are saved." : "Auto-save is off. Use Ctrl+S to save your changes."} Disk conflicts keep your edits for review.</p> <p class="note">{settings.autosaveEnabled ? $t("Only changed files are saved.") : $t("Auto-save is off. Use Ctrl+S to save your changes.")} {$t("Disk conflicts keep your edits for review.")}</p>
<div class="section-footer"><button class="text-button" onclick={() => { seconds = DEFAULT_SETTINGS.autosaveSeconds; apply({ ...DEFAULT_SETTINGS }); }}>Restore defaults</button><span>Default: every 5 seconds</span></div> <div class="section-footer"><button class="text-button" onclick={() => { seconds = DEFAULT_SETTINGS.autosaveSeconds; apply({ ...DEFAULT_SETTINGS }); }}>{$t("Restore defaults")}</button><span>{$t("Default: every 5 seconds")}</span></div>
{#if error}<p class="error" role="alert">{error}</p>{/if} {#if error}<p class="error" role="alert">{error}</p>{/if}
<p class="saved" role="status">{message}</p> <p class="saved" role="status">{message}</p>
{:else if selected.id === "appearance"} {:else if selected.id === "appearance"}
@@ -137,13 +152,13 @@
{:else if selectedPlugin} {:else if selectedPlugin}
{#key selectedPlugin.id}<PluginSettings owner={selectedPlugin.owner} id={selectedPlugin.view} />{/key} {#key selectedPlugin.id}<PluginSettings owner={selectedPlugin.owner} id={selectedPlugin.view} />{/key}
{:else} {:else}
<div class="brand"><img src="/runestone.svg" alt="" width="88" height="88" /><h2>RuneStone</h2><p>Version {version}</p></div> <div class="brand"><img src="/runestone.svg" alt="" width="88" height="88" /><h2>RuneStone</h2><p>{$t("Version {version}", { version })}</p></div>
<div class="card help-card"> <div class="card help-card">
<details><summary><Icon icon="book-open" /> Get started</summary><div class="help-copy"><p>Use the folder button to open a workspace or create one. Your notes and scripts stay as ordinary files on disk.</p><p>Use the + beside the tabs for a new tab. Press Ctrl+N to create a file, or Ctrl+P to find one.</p><p>Press Ctrl+E to switch between writing and source editing. Use the terminal button to work with a shell beside your files.</p></div></details> <details><summary><Icon icon="book-open" /> {$t("Get started")}</summary><div class="help-copy"><p>{$t("Use the folder button to open a workspace or create one. Your notes and scripts stay as ordinary files on disk.")}</p><p>{$t("Use the + beside the tabs for a new tab. Press Ctrl+N to create a file, or Ctrl+P to find one.")}</p><p>{$t("Press Ctrl+E to switch between writing and source editing. Use the terminal button to work with a shell beside your files.")}</p></div></details>
<details><summary><Icon icon="save" /> Save your work</summary><div class="help-copy"><p>Auto-save saves changed files at the interval in Settings → General. Ctrl+S saves the active file immediately.</p><p>If another app changes a file, RuneStone keeps your edits and offers both versions for review.</p></div></details> <details><summary><Icon icon="save" /> {$t("Save your work")}</summary><div class="help-copy"><p>{$t("Auto-save saves changed files at the interval in Settings → General. Ctrl+S saves the active file immediately.")}</p><p>{$t("If another app changes a file, RuneStone keeps your edits and offers both versions for review.")}</p></div></details>
<details><summary><Icon icon="code" /> Keyboard shortcuts</summary><dl><div><dt>Open a workspace</dt><dd><kbd>Ctrl+O</kbd></dd></div><div><dt>Find a file</dt><dd><kbd>Ctrl+P</kbd></dd></div><div><dt>Save the active file</dt><dd><kbd>Ctrl+S</kbd></dd></div><div><dt>Search the workspace</dt><dd><kbd>Ctrl+Shift+F</kbd></dd></div><div><dt>Open settings</dt><dd><kbd>Ctrl+,</kbd></dd></div><div><dt>Help and about</dt><dd><kbd>F1</kbd></dd></div></dl></details> <details><summary><Icon icon="code" /> {$t("Keyboard shortcuts")}</summary><dl><div><dt>{$t("Open a workspace")}</dt><dd><kbd>Ctrl+O</kbd></dd></div><div><dt>{$t("Find a file")}</dt><dd><kbd>Ctrl+P</kbd></dd></div><div><dt>{$t("Save the active file")}</dt><dd><kbd>Ctrl+S</kbd></dd></div><div><dt>{$t("Search the workspace")}</dt><dd><kbd>Ctrl+Shift+F</kbd></dd></div><div><dt>{$t("Open settings")}</dt><dd><kbd>Ctrl+,</kbd></dd></div><div><dt>{$t("Help and about")}</dt><dd><kbd>F1</kbd></dd></div></dl></details>
</div> </div>
<p class="about-note">RuneStone is under development. Maintained by kwyvern-gh.</p> <p class="about-note">{$t("RuneStone is under development. Maintained by kwyvern-gh.")}</p>
{/if} {/if}
</div> </div>
</div> </div>
@@ -179,6 +194,8 @@
.setting-row + .setting-row { border-top: 1px solid var(--rs-border); } .setting-row + .setting-row { border-top: 1px solid var(--rs-border); }
.setting-row label { font-weight: 500; } .setting-row label { font-weight: 500; }
.setting-row p { margin: 3px 0 0; font-size: var(--rs-settings-description-size); } .setting-row p { margin: 3px 0 0; font-size: var(--rs-settings-description-size); }
.language-row { flex-wrap: wrap; }
.language-picker { display:flex; align-items:center; gap:var(--rs-settings-gap); max-width:100%; }
.switch { appearance: none; width: 38px; height: 22px; flex: 0 0 38px; margin: 0; border-radius: 20px; background: var(--rs-bg-active); border: 1px solid var(--rs-text-dim); cursor: pointer; } .switch { appearance: none; width: 38px; height: 22px; flex: 0 0 38px; margin: 0; border-radius: 20px; background: var(--rs-bg-active); border: 1px solid var(--rs-text-dim); cursor: pointer; }
.switch::before { content: ""; display: block; width: 16px; height: 16px; margin: 2px; background: var(--rs-text); border-radius: 50%; transition: transform .12s; } .switch::before { content: ""; display: block; width: 16px; height: 16px; margin: 2px; background: var(--rs-text); border-radius: 50%; transition: transform .12s; }
.switch:checked { background: var(--rs-accent); border-color: var(--rs-accent); } .switch:checked { background: var(--rs-accent); border-color: var(--rs-accent); }
+15 -14
View File
@@ -1,4 +1,5 @@
<script lang="ts"> <script lang="ts">
import { t } from "$lib/i18n";
import { onDestroy, tick } from "svelte"; import { onDestroy, tick } from "svelte";
import { actionMenu, type ActionMenuItem } from "$lib/ui/actionMenu"; import { actionMenu, type ActionMenuItem } from "$lib/ui/actionMenu";
import { actionIcons } from "$lib/ui/actionIcons"; import { actionIcons } from "$lib/ui/actionIcons";
@@ -122,24 +123,24 @@
children: item.children ? wrapActions(item.children) : undefined }; children: item.children ? wrapActions(item.children) : undefined };
}); });
menu = actionMenu(x, y, [ menu = actionMenu(x, y, [
closing("Close", "one"), closing($t("Close"), "one"),
closing("Close others", "others"), closing($t("Close others"), "others"),
closing("Close tabs after", "after"), closing($t("Close tabs after"), "after"),
closing("Close all", "all"), closing($t("Close all"), "all"),
...(tabs[index].pinned !== undefined ? [ ...(tabs[index].pinned !== undefined ? [
{ separator: true as const }, { separator: true as const },
{ label: tabs[index].pinned ? "Unpin" : "Pin", icon: "pin" as const, run: run(() => onPin(path)) }, { label: tabs[index].pinned ? $t("Unpin") : $t("Pin"), icon: "pin" as const, run: run(() => onPin(path)) },
] : []), ] : []),
...wrapActions(tabActions(tabs[index])), ...wrapActions(tabActions(tabs[index])),
...(path === activePath ? wrapActions(fileActions(tabs[index])) : []), ...(path === activePath ? wrapActions(fileActions(tabs[index])) : []),
{ separator: true }, { separator: true },
{ label: "Move tab", icon: "swap", children: [ { label: $t("Move tab"), icon: "swap", children: [
{ label: "Move tab left", icon: "move-left", disabled: index <= 0, { label: $t("Move tab left"), icon: "move-left", disabled: index <= 0,
run: run(() => { void move(path, index - 1); }) }, run: run(() => { void move(path, index - 1); }) },
{ label: "Move tab right", icon: "move-right", disabled: index === tabs.length - 1, { label: $t("Move tab right"), icon: "move-right", disabled: index === tabs.length - 1,
run: run(() => { void move(path, index + 1); }) }, run: run(() => { void move(path, index + 1); }) },
] }, ] },
], () => closeMenu(true), "Tab actions"); ], () => closeMenu(true), $t("Tab actions"));
menu.classList.add("tab-menu"); menu.classList.add("tab-menu");
} }
@@ -255,7 +256,7 @@
<svelte:window onpointerdown={(event) => { if (menu && !menu.contains(event.target as Node)) closeMenu(); }} onresize={() => closeMenu()} /> <svelte:window onpointerdown={(event) => { if (menu && !menu.contains(event.target as Node)) closeMenu(); }} onresize={() => closeMenu()} />
<div bind:this={bar} class="tabs" class:receiving role="tablist" aria-label="Working tabs" tabindex="-1" <div bind:this={bar} class="tabs" class:receiving role="tablist" aria-label={$t("Working tabs")} tabindex="-1"
ondragover={dragOver} ondrop={dropTab} ondragover={dragOver} ondrop={dropTab}
ondragleave={(event) => { if (!(event.relatedTarget instanceof Node) || !bar.contains(event.relatedTarget)) { receiving = false; dropBefore = dropAfter = null; } }}> ondragleave={(event) => { if (!(event.relatedTarget instanceof Node) || !bar.contains(event.relatedTarget)) { receiving = false; dropBefore = dropAfter = null; } }}>
{#each tabs as tab (tab.id)} {#each tabs as tab (tab.id)}
@@ -270,7 +271,7 @@
aria-controls={tab.panelId} aria-controls={tab.panelId}
aria-describedby={tab.pinned ? `tab-pin-${tab.id}` : undefined} aria-describedby={tab.pinned ? `tab-pin-${tab.id}` : undefined}
aria-keyshortcuts="Alt+Shift+ArrowLeft Alt+Shift+ArrowRight" aria-keyshortcuts="Alt+Shift+ArrowLeft Alt+Shift+ArrowRight"
title={`${tab.title}\n${tab.draggable ? "Drag to reorder or move to another RuneStone window." : "Drag to reorder."} Right-click for tab actions.`} title={`${tab.title}\n${tab.draggable ? $t("Drag to reorder or move to another RuneStone window.") : $t("Drag to reorder.")} ${$t("Right-click for tab actions.")}`}
onclick={() => { if (suppressClick) { suppressClick = false; return; } onSelect(tab.relPath); }} onclick={() => { if (suppressClick) { suppressClick = false; return; } onSelect(tab.relPath); }}
onpointerdown={(event) => { if (!tab.draggable) startDrag(event, tab.relPath); else suppressClick = false; }} onpointerdown={(event) => { if (!tab.draggable) startDrag(event, tab.relPath); else suppressClick = false; }}
draggable={!!tab.draggable} draggable={!!tab.draggable}
@@ -289,12 +290,12 @@
<TabIcon image={tab.iconImage} icon={tab.icon} /> <TabIcon image={tab.iconImage} icon={tab.icon} />
<span class="tab-label">{tab.name}{tab.dirty ? " •" : ""}</span> <span class="tab-label">{tab.name}{tab.dirty ? " •" : ""}</span>
</button> </button>
{#if tab.pinned}<span class="sr-only" id={`tab-pin-${tab.id}`}>Pinned tab</span>{/if} {#if tab.pinned}<span class="sr-only" id={`tab-pin-${tab.id}`}>{$t("Pinned tab")}</span>{/if}
<button <button
class="close" class="close"
type="button" type="button"
aria-label="Close {tab.name}" aria-label={$t("Close {name}", { name: tab.name })}
title="Close {tab.name}" title={$t("Close {name}", { name: tab.name })}
onclick={() => onClose(tab.relPath)} onclick={() => onClose(tab.relPath)}
onmousedown={onMiddleDown} onmousedown={onMiddleDown}
onmouseup={(event) => onMiddleUp(event, tab.relPath)} onmouseup={(event) => onMiddleUp(event, tab.relPath)}
+13 -12
View File
@@ -1,4 +1,5 @@
<script lang="ts"> <script lang="ts">
import { t } from "$lib/i18n";
import { onMount } from "svelte"; import { onMount } from "svelte";
import { confirm } from "@tauri-apps/plugin-dialog"; import { confirm } from "@tauri-apps/plugin-dialog";
import { isTauri } from "@tauri-apps/api/core"; import { isTauri } from "@tauri-apps/api/core";
@@ -18,7 +19,7 @@
async function refresh() { templates = await noteTemplates(); window.dispatchEvent(new Event("runestone-templates-changed")); } async function refresh() { templates = await noteTemplates(); window.dispatchEvent(new Event("runestone-templates-changed")); }
onMount(() => { dialog.showModal(); void refresh(); }); onMount(() => { dialog.showModal(); void refresh(); });
async function create() { async function create() {
const name = await requestText("Template name", "New template"); const name = await requestText($t("Template name"), $t("New template"));
if (!name) return; if (!name) return;
busy = true; error = ""; busy = true; error = "";
try { const path = await saveNoteTemplate(name, ""); await refresh(); edit({ path, name: path.split("/").at(-1)!.replace(/\.md$/i, "") }); } try { const path = await saveNoteTemplate(name, ""); await refresh(); edit({ path, name: path.split("/").at(-1)!.replace(/\.md$/i, "") }); }
@@ -26,10 +27,10 @@
finally { busy = false; } finally { busy = false; }
} }
async function rename(template: NoteTemplate) { async function rename(template: NoteTemplate) {
const name = await requestText("Template name", template.name); const name = await requestText($t("Template name"), template.name);
if (!name) return; if (!name) return;
const title = name.trim().replace(/\.md$/i, ""); const title = name.trim().replace(/\.md$/i, "");
if (!title || /[<>:"/\\|?*\x00-\x1f]/.test(title) || /[. ]$/.test(title)) { error = "Enter a valid template name."; return; } if (!title || /[<>:"/\\|?*\x00-\x1f]/.test(title) || /[. ]$/.test(title)) { error = $t("Enter a valid template name."); return; }
const path = `${TEMPLATE_FOLDER}/${title}.md`; const path = `${TEMPLATE_FOLDER}/${title}.md`;
if (path === template.path) return; if (path === template.path) return;
busy = true; error = ""; busy = true; error = "";
@@ -38,8 +39,8 @@
finally { busy = false; } finally { busy = false; }
} }
async function remove(template: NoteTemplate) { async function remove(template: NoteTemplate) {
const message = `Delete the template “${template.name}”? Existing notes stay unchanged.`; const message = $t("Delete the template “{name}”? Existing notes stay unchanged.", { name: template.name });
const accepted = isTauri() ? await confirm(message, { title: "Delete template", kind: "warning" }) : window.confirm(message); const accepted = isTauri() ? await confirm(message, { title: $t("Delete template"), kind: "warning" }) : window.confirm(message);
if (!accepted) return; if (!accepted) return;
busy = true; error = ""; busy = true; error = "";
try { await workspaceDelete(template.path); onDeleted(template.path); await refresh(); } try { await workspaceDelete(template.path); onDeleted(template.path); await refresh(); }
@@ -49,17 +50,17 @@
</script> </script>
<dialog bind:this={dialog} aria-labelledby="templates-title" oncancel={event => { event.preventDefault(); if (!busy) onClose(); }}> <dialog bind:this={dialog} aria-labelledby="templates-title" oncancel={event => { event.preventDefault(); if (!busy) onClose(); }}>
<header><h2 id="templates-title">Document templates</h2><IconButton icon="close" label="Close templates" disabled={busy} onclick={onClose} /></header> <header><h2 id="templates-title">{$t("Document templates")}</h2><IconButton icon="close" label={$t("Close templates")} disabled={busy} onclick={onClose} /></header>
<p>Templates belong to this workspace. Edit a template to change future notes.</p> <p>{$t("Templates belong to this workspace. Edit a template to change future notes.")}</p>
<button class="new" disabled={busy} onclick={() => void create()}><Icon icon="file-plus" /> New template</button> <button class="new" disabled={busy} onclick={() => void create()}><Icon icon="file-plus" /> {$t("New template")}</button>
<div class="list"> <div class="list">
{#each templates as template (template.path)} {#each templates as template (template.path)}
<div class="row"><span title={template.name}>{template.name}</span><div class="actions"> <div class="row"><span title={template.name}>{template.name}</span><div class="actions">
<IconButton icon="pen" label={`Edit ${template.name}`} disabled={busy} onclick={() => edit(template)} /> <IconButton icon="pen" label={$t("Edit {name}", { name: template.name })} disabled={busy} onclick={() => edit(template)} />
<button class="rename" aria-label={`Rename ${template.name}`} title={`Rename ${template.name}`} disabled={busy} onclick={() => void rename(template)}><Icon icon="text" /> Rename</button> <button class="rename" aria-label={$t("Rename {name}", { name: template.name })} title={$t("Rename {name}", { name: template.name })} disabled={busy} onclick={() => void rename(template)}><Icon icon="text" /> {$t("Rename")}</button>
<IconButton icon="trash" label={`Delete ${template.name}`} disabled={busy} onclick={() => void remove(template)} /> <IconButton icon="trash" label={$t("Delete {name}", { name: template.name })} disabled={busy} onclick={() => void remove(template)} />
</div></div> </div></div>
{:else}<p>No templates yet. Create one or use Save as template on a note.</p>{/each} {:else}<p>{$t("No templates yet. Create one or use Save as template on a note.")}</p>{/each}
</div> </div>
{#if error}<p role="alert">{error}</p>{/if} {#if error}<p role="alert">{error}</p>{/if}
</dialog> </dialog>
+2 -1
View File
@@ -1,4 +1,5 @@
<script lang="ts"> <script lang="ts">
import { t } from "$lib/i18n";
import { dialogs, finishText } from "$lib/workspace/dialogs.svelte"; import { dialogs, finishText } from "$lib/workspace/dialogs.svelte";
let element: HTMLDialogElement | undefined = $state(); let element: HTMLDialogElement | undefined = $state();
let input: HTMLInputElement | undefined = $state(); let input: HTMLInputElement | undefined = $state();
@@ -17,7 +18,7 @@
<form onsubmit={(event) => { event.preventDefault(); finishText(dialogs.text?.value.trim() || null); }}> <form onsubmit={(event) => { event.preventDefault(); finishText(dialogs.text?.value.trim() || null); }}>
<label for="text-request">{dialogs.text.title}</label> <label for="text-request">{dialogs.text.title}</label>
<input id="text-request" bind:this={input} bind:value={dialogs.text.value} autocomplete="off" /> <input id="text-request" bind:this={input} bind:value={dialogs.text.value} autocomplete="off" />
<div><button type="button" onclick={() => finishText(null)}>Cancel</button><button type="submit" disabled={!dialogs.text.value.trim()}>Continue</button></div> <div><button type="button" onclick={() => finishText(null)}>{$t("Cancel")}</button><button type="submit" disabled={!dialogs.text.value.trim()}>{$t("Continue")}</button></div>
</form> </form>
</dialog> </dialog>
{/if} {/if}
+2 -1
View File
@@ -1,4 +1,5 @@
<script lang="ts"> <script lang="ts">
import { t } from "$lib/i18n";
import type { TreeEntry } from "$lib/workspace/types"; import type { TreeEntry } from "$lib/workspace/types";
import type { DropTarget } from "$lib/workspace/treeDrop"; import type { DropTarget } from "$lib/workspace/treeDrop";
import type { SelectionModifiers, TreeSelectionEdges } from "$lib/workspace/treeSelection"; import type { SelectionModifiers, TreeSelectionEdges } from "$lib/workspace/treeSelection";
@@ -133,7 +134,7 @@
{#if isRenaming} {#if isRenaming}
<input <input
class="rename" class="rename"
aria-label="File or folder name, including any extension" aria-label={$t("File or folder name, including any extension")}
value={renameDraft} value={renameDraft}
use:focusSelect use:focusSelect
onclick={(event) => event.stopPropagation()} onclick={(event) => event.stopPropagation()}
+72 -71
View File
@@ -1,4 +1,5 @@
<script lang="ts"> <script lang="ts">
import { t } from "$lib/i18n";
import TerminalSlot from "$lib/plugins/TerminalSlot.svelte"; import TerminalSlot from "$lib/plugins/TerminalSlot.svelte";
import PluginTools from "$lib/plugins/PluginTools.svelte"; import PluginTools from "$lib/plugins/PluginTools.svelte";
import PluginAccessMenu from "$lib/plugins/PluginAccessMenu.svelte"; import PluginAccessMenu from "$lib/plugins/PluginAccessMenu.svelte";
@@ -75,7 +76,7 @@
if (openingSettings) return; if (openingSettings) return;
openingSettings = true; openingSettings = true;
try { await invoke("settings_open_window"); } try { await invoke("settings_open_window"); }
catch (reason) { error = `Could not open settings: ${String(reason)}`; } catch (reason) { error = $t("Could not open settings: {error}", { error: String(reason) }); }
finally { openingSettings = false; } finally { openingSettings = false; }
} }
let settings = $state<AppSettings>({ ...DEFAULT_SETTINGS }); let settings = $state<AppSettings>({ ...DEFAULT_SETTINGS });
@@ -86,7 +87,7 @@
let tabs = $state<OpenBuffer[]>([]); let tabs = $state<OpenBuffer[]>([]);
let activePath = $state<string | null>(null); let activePath = $state<string | null>(null);
const buffer = $derived(tabs.find((tab) => tab.relPath === activePath) ?? null); const buffer = $derived(tabs.find((tab) => tab.relPath === activePath) ?? null);
let status = $state("Open a workspace folder"); let status = $state($t("Open a workspace folder"));
let error = $state<string | null>(null); let error = $state<string | null>(null);
let refreshToken = $state(0); let refreshToken = $state(0);
let view = $state<Chrome>("Writing"); let view = $state<Chrome>("Writing");
@@ -277,7 +278,7 @@
async function terminalAction(action: Exclude<ReturnType<Contributions["terminal"]["shortcut"]>, null | "toggle">) { async function terminalAction(action: Exclude<ReturnType<Contributions["terminal"]["shortcut"]>, null | "toggle">) {
if (!terminalEnabled) return; if (!terminalEnabled) return;
if (!workspace) { error = "Open a workspace to start a terminal."; return; } if (!workspace) { error = $t("Open a workspace to start a terminal."); return; }
const started = terminalStarted; const started = terminalStarted;
terminalStarted = true; terminalOpen = true; terminalStarted = true; terminalOpen = true;
if (bottomHeight < 220) bottomHeight = 260; if (bottomHeight < 220) bottomHeight = 260;
@@ -374,7 +375,7 @@
focusLine = null; focusLine = null;
documents?.select(relPath); documents?.select(relPath);
focusDocumentPane(documentPanes.active, true); focusDocumentPane(documentPanes.active, true);
status = documents?.active?.kind === "empty" ? "New tab" : relPath; status = documents?.active?.kind === "empty" ? $t("New tab") : relPath;
} }
function selectWorkingTab(path: string) { function selectWorkingTab(path: string) {
@@ -403,7 +404,7 @@
const tab = workingTabs.find(tab => tab.id === item.id); const tab = workingTabs.find(tab => tab.id === item.id);
const actions = tab && "plugin" in tab ? pluginTabActions(tab.plugin) : []; const actions = tab && "plugin" in tab ? pluginTabActions(tab.plugin) : [];
if (actions.some(action => "label" in action && /(?:move|open).*new window/i.test(action.label))) return actions; if (actions.some(action => "label" in action && /(?:move|open).*new window/i.test(action.label))) return actions;
return tab ? [{ label: "Open in new window", icon: "external", disabled: !desktop || !workspace, run: () => { void detachTab(tab); } }, ...actions] : []; return tab ? [{ label: $t("Open in new window"), icon: "external", disabled: !desktop || !workspace, run: () => { void detachTab(tab); } }, ...actions] : [];
} }
async function detachTab(item: WorkbenchTab, keepSource = false) { async function detachTab(item: WorkbenchTab, keepSource = false) {
const tab = workingTabs.find(tab => tab.id === item.id); const tab = workingTabs.find(tab => tab.id === item.id);
@@ -451,7 +452,7 @@
focusLine = null; focusLine = null;
documents.newTab(); documents.newTab();
terminalMaximized = false; terminalMaximized = false;
status = "New tab"; status = $t("New tab");
error = null; error = null;
} }
@@ -471,7 +472,7 @@
if ("buffer" in target) { if ("buffer" in target) {
if (!tab || (scope !== "one" && tab.pinned)) continue; if (!tab || (scope !== "one" && tab.pinned)) continue;
const contents = tab.contents; const contents = tab.contents;
if (contents !== tab.saved && !await confirm(`Discard unsaved edits in ${tab.name}?`, { title: "Close document", kind: "warning" })) break; if (contents !== tab.saved && !await confirm($t("Discard unsaved edits in {name}?", { name: tab.name }), { title: $t("Close document"), kind: "warning" })) break;
if (documents !== current || switching || tab.contents !== contents) break; if (documents !== current || switching || tab.contents !== contents) break;
if (scope !== "one" && tab.pinned) continue; if (scope !== "one" && tab.pinned) continue;
} }
@@ -491,7 +492,7 @@
try { try {
const text = system ? await workspaceAbsPath(path) : path; const text = system ? await workspaceAbsPath(path) : path;
await navigator.clipboard.writeText(text); await navigator.clipboard.writeText(text);
status = system ? "Copied system path" : "Copied workspace path"; status = system ? $t("Copied system path") : $t("Copied workspace path");
} catch (err) { error = String(err); } } catch (err) { error = String(err); }
} }
@@ -500,21 +501,21 @@
const items: ActionMenuItem[] = []; const items: ActionMenuItem[] = [];
if (tab.kind === "text" && isMarkdownPath(tab.relPath)) { if (tab.kind === "text" && isMarkdownPath(tab.relPath)) {
items.push( items.push(
{ label: "Save as template", icon: "copy", run: () => { void saveTemplate({ name: tab.name, rel_path: tab.relPath, kind: "file" }); } }, { label: $t("Save as template"), icon: "copy", run: () => { void saveTemplate({ name: tab.name, rel_path: tab.relPath, kind: "file" }); } },
{ label: reading ? "Editing view" : "Reading view", icon: "book", run: () => activeEditor()?.toggleReadingView() }, { label: reading ? $t("Editing view") : $t("Reading view"), icon: "book", run: () => activeEditor()?.toggleReadingView() },
{ label: isIde ? "Writing mode" : "Source mode", icon: "code", run: toggleChrome }, { label: isIde ? $t("Writing mode") : $t("Source mode"), icon: "code", run: toggleChrome },
); );
} }
items.push({ separator: true }, items.push({ separator: true },
{ label: "Rename…", icon: "rename", run: () => { void renameActive(); } }, { label: $t("Rename…"), icon: "rename", run: () => { void renameActive(); } },
); );
if (tab.kind === "text") items.push({ label: "Save a copy…", icon: "copy", run: () => { void saveCopy(); } }); if (tab.kind === "text") items.push({ label: $t("Save a copy…"), icon: "copy", run: () => { void saveCopy(); } });
items.push({ separator: true }, items.push({ separator: true },
{ label: "Copy path", icon: "copy", children: [ { label: $t("Copy path"), icon: "copy", children: [
{ label: "Workspace path", icon: "copy", run: () => { void copyTabPath(tab.relPath, false); } }, { label: $t("Workspace path"), icon: "copy", run: () => { void copyTabPath(tab.relPath, false); } },
{ label: "System path", icon: "copy", run: () => { void copyTabPath(tab.relPath, true); } }, { label: $t("System path"), icon: "copy", run: () => { void copyTabPath(tab.relPath, true); } },
] }, ] },
{ label: "Show in system explorer", icon: "folder", run: () => { void workspaceReveal(tab.relPath).catch(err => { error = String(err); }); } }, { label: $t("Show in system explorer"), icon: "folder", run: () => { void workspaceReveal(tab.relPath).catch(err => { error = String(err); }); } },
); );
return items; return items;
} }
@@ -595,7 +596,7 @@
if (!workspace || !current || !note) return null; if (!workspace || !current || !note) return null;
const folder = note.relPath.slice(0, note.relPath.lastIndexOf("/") + 1); const folder = note.relPath.slice(0, note.relPath.lastIndexOf("/") + 1);
const suggested = label.replace(/[<>:"/\\|?*\r\n]/g, " ").trim().slice(0, 60) || "Extracted selection"; const suggested = label.replace(/[<>:"/\\|?*\r\n]/g, " ").trim().slice(0, 60) || "Extracted selection";
const name = await requestText("Extract selection to a new note (workspace relative path)", `${folder}${suggested}.md`); const name = await requestText($t("Extract selection to a new note (workspace relative path)"), `${folder}${suggested}.md`);
if (!name || documents !== current || !valid() || saving || switching) return null; if (!name || documents !== current || !valid() || saving || switching) return null;
const rel = name.replaceAll("\\", "/").replace(/\.md$/i, "") + ".md"; const rel = name.replaceAll("\\", "/").replace(/\.md$/i, "") + ".md";
saving = true; saving = true;
@@ -603,7 +604,7 @@
await workspaceCreate(rel, "file"); await workspaceCreate(rel, "file");
await workspaceWrite(rel, markdown + "\n", ""); await workspaceWrite(rel, markdown + "\n", "");
refreshToken++; refreshToken++;
status = `Extracted selection to ${rel}`; status = $t("Extracted selection to {path}", { path: rel });
return `/${rel}`; return `/${rel}`;
} catch (err) { error = String(err); return null; } } catch (err) { error = String(err); return null; }
finally { saving = false; } finally { saving = false; }
@@ -616,7 +617,7 @@
saving = true; saving = true;
try { try {
await current.save(tab.id); await current.save(tab.id);
status = `Saved ${tab.relPath}`; status = $t("Saved {path}", { path: tab.relPath });
error = null; error = null;
} catch (err) { } catch (err) {
error = String(err); error = String(err);
@@ -631,9 +632,9 @@
try { try {
const result = await current.autosave(); const result = await current.autosave();
if (documents !== current) return; if (documents !== current) return;
if (result.saved.length) status = `Autosaved ${result.saved.length} ${result.saved.length === 1 ? "file" : "files"}`; if (result.saved.length) status = result.saved.length === 1 ? $t("Autosaved 1 file") : $t("Autosaved {count} files", { count: result.saved.length });
if (result.failed.length) { if (result.failed.length) {
error = result.failed.map(({ path, error }) => `Could not autosave ${path}: ${String(error)}`).join("\n"); error = result.failed.map(({ path, error }) => $t("Could not autosave {path}: {error}", { path, error: String(error) })).join("\n");
await current.refresh(); await current.refresh();
} }
} finally { saving = false; } } finally { saving = false; }
@@ -641,7 +642,7 @@
async function saveCopy(tab = buffer) { async function saveCopy(tab = buffer) {
if (!tab || tab.kind !== "text") return; if (!tab || tab.kind !== "text") return;
const name = await requestText("Save a copy as (workspace relative path)", tab.relPath.replace(/(\.[^./]+)?$/, " copy$1")); const name = await requestText($t("Save a copy as (workspace relative path)"), tab.relPath.replace(/(\.[^./]+)?$/, " copy$1"));
if (!name) return; if (!name) return;
try { try {
await workspaceCreate(name, "file"); await workspaceCreate(name, "file");
@@ -655,7 +656,7 @@
if (!workspace) { if (!workspace) {
return; return;
} }
const name = await requestText("New file path relative to the workspace", "Untitled.md"); const name = await requestText($t("New file path relative to the workspace"), "Untitled.md");
if (!name) { if (!name) {
return; return;
} }
@@ -673,12 +674,12 @@
} }
async function saveTemplate(entry: TreeEntry) { async function saveTemplate(entry: TreeEntry) {
const name = await requestText("Template name", entry.name.replace(/\.md$/i, "")); const name = await requestText($t("Template name"), entry.name.replace(/\.md$/i, ""));
if (!name) return; if (!name) return;
try { try {
const contents = documents?.buffers.find(tab => tab.relPath === entry.rel_path)?.contents ?? await workspaceRead(entry.rel_path); const contents = documents?.buffers.find(tab => tab.relPath === entry.rel_path)?.contents ?? await workspaceRead(entry.rel_path);
await saveNoteTemplate(name, contents); await saveNoteTemplate(name, contents);
status = `Saved template: ${name}`; status = $t("Saved template: {name}", { name });
} catch (reason) { error = String(reason); } } catch (reason) { error = String(reason); }
} }
@@ -697,9 +698,9 @@
const close = () => { menu.remove(); window.removeEventListener("pointerdown", outside); anchor?.focus(); }; const close = () => { menu.remove(); window.removeEventListener("pointerdown", outside); anchor?.focus(); };
const outside = (event: PointerEvent) => { if (!menu.contains(event.target as Node)) close(); }; const outside = (event: PointerEvent) => { if (!menu.contains(event.target as Node)) close(); };
const menu = actionMenu(event.clientX, event.clientY, [ const menu = actionMenu(event.clientX, event.clientY, [
{ label: "Blank note", icon: "file-plus", run: () => { close(); void create(); } }, { label: $t("Blank note"), icon: "file-plus", run: () => { close(); void create(); } },
...templates.map(template => ({ label: template.name, icon: "file-plus" as const, run: () => { close(); void create(template); } })), ...templates.map(template => ({ label: template.name, icon: "file-plus" as const, run: () => { close(); void create(template); } })),
], close, "New note"); ], close, $t("New note"));
window.addEventListener("pointerdown", outside); window.addEventListener("pointerdown", outside);
} }
@@ -806,7 +807,7 @@
current.rename(from, plan.to); current.rename(from, plan.to);
if (documents !== current) return; if (documents !== current) return;
refreshToken += 1; refreshToken += 1;
status = `Renamed to ${plan.to}`; status = $t("Renamed to {path}", { path: plan.to });
error = null; error = null;
} }
@@ -816,7 +817,7 @@
} }
const current = documents; const current = documents;
const from = activePath; const from = activePath;
const typed = await requestText("Rename to", from.split("/").pop() ?? from); const typed = await requestText($t("Rename to"), from.split("/").pop() ?? from);
if (typed == null || documents !== current || switching) { if (typed == null || documents !== current || switching) {
return; return;
} }
@@ -833,7 +834,7 @@
current?.rename(from, plan.to); current?.rename(from, plan.to);
if (documents !== current) return; if (documents !== current) return;
refreshToken += 1; refreshToken += 1;
status = `Renamed to ${plan.to}`; status = $t("Renamed to {path}", { path: plan.to });
error = null; error = null;
} catch (err) { } catch (err) {
error = err instanceof Error ? err.message : String(err); error = err instanceof Error ? err.message : String(err);
@@ -852,13 +853,13 @@
const found = files.find(file => file.rel_path === path && file.kind === "file"); const found = files.find(file => file.rel_path === path && file.kind === "file");
if (found) return found; if (found) return found;
} }
throw new Error(`Could not find ${link.target} in the workspace.`); throw new Error($t("Could not find {path} in the workspace.", { path: link.target }));
}; };
const run = (action: (file: TreeEntry) => void | Promise<void>) => () => { const run = (action: (file: TreeEntry) => void | Promise<void>) => () => {
void entry().then(file => { if (valid()) return action(file); }).catch(reason => { error = String(reason); }); void entry().then(file => { if (valid()) return action(file); }).catch(reason => { error = String(reason); });
}; };
async function rename(file: TreeEntry, move = false) { async function rename(file: TreeEntry, move = false) {
const typed = await requestText(move ? "Move file to (workspace path, including filename)" : "New file name", move ? file.rel_path : file.name); const typed = await requestText(move ? $t("Move file to (workspace path, including filename)") : $t("New file name"), move ? file.rel_path : file.name);
if (!typed || !valid()) return; if (!typed || !valid()) return;
let to = typed.trim().replaceAll("\\", "/"); let to = typed.trim().replaceAll("\\", "/");
if (move) { if (move) {
@@ -877,31 +878,31 @@
applyPathRename(file.rel_path, to); applyPathRename(file.rel_path, to);
await saveMarks(moveMarks(marks, file.rel_path, to)); await saveMarks(moveMarks(marks, file.rel_path, to));
refreshToken++; refreshToken++;
status = `Moved to ${to}`; status = $t("Moved to {path}", { path: to });
} }
return [ return [
{ label: "Open to the right", icon: "split-right", run: run(file => openToRight(file, sourcePane)) }, { label: $t("Open to the right"), icon: "split-right", run: run(file => openToRight(file, sourcePane)) },
{ label: "Open in new window", icon: "external", disabled: !desktop, run: run(async file => { { label: $t("Open in new window"), icon: "external", disabled: !desktop, run: run(async file => {
await openFile(file, undefined, "new"); await openFile(file, undefined, "new");
if (!valid()) return; if (!valid()) return;
const tab = workingTabs.find(tab => tab.relPath === file.rel_path); const tab = workingTabs.find(tab => tab.relPath === file.rel_path);
if (tab) await detachTab(tab, true); if (tab) await detachTab(tab, true);
}) }, }) },
{ label: "Copy path", icon: "copy", children: [ { label: $t("Copy path"), icon: "copy", children: [
{ label: "Workspace path", icon: "copy", run: run(file => copyTabPath(file.rel_path, false)) }, { label: $t("Workspace path"), icon: "copy", run: run(file => copyTabPath(file.rel_path, false)) },
{ label: "System path", icon: "copy", run: run(file => copyTabPath(file.rel_path, true)) }, { label: $t("System path"), icon: "copy", run: run(file => copyTabPath(file.rel_path, true)) },
] }, ] },
{ label: "Rename…", icon: "rename", run: run(file => rename(file)) }, { label: $t("Rename…"), icon: "rename", run: run(file => rename(file)) },
{ label: "Move file to…", icon: "folder", run: run(file => rename(file, true)) }, { label: $t("Move file to…"), icon: "folder", run: run(file => rename(file, true)) },
{ label: "Bookmark", icon: "bookmark", run: run(async file => { { label: $t("Bookmark"), icon: "bookmark", run: run(async file => {
const marks = await loadMarks(); const marks = await loadMarks();
if (!valid()) return; if (!valid()) return;
if (!marks.bookmarks.includes(file.rel_path)) await saveMarks({ ...marks, bookmarks: [...marks.bookmarks, file.rel_path] }); if (!marks.bookmarks.includes(file.rel_path)) await saveMarks({ ...marks, bookmarks: [...marks.bookmarks, file.rel_path] });
refreshToken++; status = `Bookmarked ${file.name}`; refreshToken++; status = $t("Bookmarked {name}", { name: file.name });
}) }, }) },
{ label: "Open in default app", icon: "external", run: run(file => workspaceOpenDefault(file.rel_path)) }, { label: $t("Open in default app"), icon: "external", run: run(file => workspaceOpenDefault(file.rel_path)) },
{ label: "Show in system explorer", icon: "folder", run: run(file => workspaceReveal(file.rel_path)) }, { label: $t("Show in system explorer"), icon: "folder", run: run(file => workspaceReveal(file.rel_path)) },
{ label: "Reveal file in navigation", icon: "folder", run: run(async file => { closePluginSidebar(); leftView = "files"; leftOpen = true; await tick(); await fileTree?.revealPath(file.rel_path); }) }, { label: $t("Reveal file in navigation"), icon: "folder", run: run(async file => { closePluginSidebar(); leftView = "files"; leftOpen = true; await tick(); await fileTree?.revealPath(file.rel_path); }) },
]; ];
} }
@@ -922,7 +923,7 @@
return; return;
} catch { /* Try the workspace-root candidate after the note-relative path. */ } } catch { /* Try the workspace-root candidate after the note-relative path. */ }
} }
error = `Could not open ${target}`; error = $t("Could not open {path}", { path: target });
} }
function onPointerMove(event: PointerEvent) { function onPointerMove(event: PointerEvent) {
@@ -1028,7 +1029,7 @@
closing = true; closing = true;
try { try {
const message = [hasDirty ? "Unsaved edits will be discarded." : "", terminalStarted ? "Terminal sessions will end." : ""].filter(Boolean).join("\n"); const message = [hasDirty ? "Unsaved edits will be discarded." : "", terminalStarted ? "Terminal sessions will end." : ""].filter(Boolean).join("\n");
if (await confirm(`${message}\nClose RuneStone?`, { title: "Close workspace", kind: "warning" })) await getCurrentWindow().destroy(); if (await confirm(`${message}\n${$t("Close RuneStone?")}`, { title: $t("Close workspace"), kind: "warning" })) await getCurrentWindow().destroy();
} finally { closing = false; } } finally { closing = false; }
}).then(register).catch(err => error = String(err)); }).then(register).catch(err => error = String(err));
const focus = () => { void documents?.refresh(); refreshToken++; }; const focus = () => { void documents?.refresh(); refreshToken++; };
@@ -1061,7 +1062,7 @@
class:left-open={!transferredWindow && leftOpen} class:left-open={!transferredWindow && leftOpen}
class:right-open={!transferredWindow && rightOpen} class:right-open={!transferredWindow && rightOpen}
role="application" role="application"
aria-label="RuneStone workbench" aria-label={$t("RuneStone workbench")}
style:--left="{leftWidth}px" style:--left="{leftWidth}px"
style:--right="{rightWidth}px" style:--right="{rightWidth}px"
style:--bottom="{bottomHeight}px" style:--bottom="{bottomHeight}px"
@@ -1075,19 +1076,19 @@
{#if !transferredWindow} {#if !transferredWindow}
<IconButton <IconButton
icon="files" icon="files"
label="Files" label={$t("Files")}
active={leftOpen && !$pluginSidebar && leftView === "files"} active={leftOpen && !$pluginSidebar && leftView === "files"}
onclick={() => selectLeft("files")} onclick={() => selectLeft("files")}
/> />
<IconButton <IconButton
icon="search" icon="search"
label="Search" label={$t("Search")}
active={leftOpen && !$pluginSidebar && leftView === "search"} active={leftOpen && !$pluginSidebar && leftView === "search"}
onclick={() => selectLeft("search")} onclick={() => selectLeft("search")}
/> />
<IconButton <IconButton
icon="bookmark" icon="bookmark"
label="Bookmarks" label={$t("Bookmarks")}
active={leftOpen && !$pluginSidebar && leftView === "bookmarks"} active={leftOpen && !$pluginSidebar && leftView === "bookmarks"}
onclick={() => selectLeft("bookmarks")} onclick={() => selectLeft("bookmarks")}
/> />
@@ -1107,19 +1108,19 @@
fileActions={workingTabFileActions} tabActions={workingTabActions} onMove={moveWorkingTab} fileActions={workingTabFileActions} tabActions={workingTabActions} onMove={moveWorkingTab}
onDetach={(tab) => { void detachTab(tab); }} onDetach={(tab) => { void detachTab(tab); }}
tabDragData={workingTabDragData} onDropTab={(data, index) => void receiveTab(data, index)} /> tabDragData={workingTabDragData} onDropTab={(data, index) => void receiveTab(data, index)} />
<IconButton icon="plus" label="New tab (Ctrl T)" onclick={newTab} /> <IconButton icon="plus" label={$t("New tab (Ctrl T)")} onclick={newTab} />
{#if desktop}<div class="window-drag-space" data-tauri-drag-region></div>{/if} {#if desktop}<div class="window-drag-space" data-tauri-drag-region></div>{/if}
</div> </div>
<div class="header-right" data-tauri-drag-region> <div class="header-right" data-tauri-drag-region>
{#if browserContribution?.newTab}<IconButton icon="globe" label="New browser tab" disabled={browserOpening} onclick={() => void openBrowser()} />{/if} {#if browserContribution?.newTab}<IconButton icon="globe" label={$t("New browser tab")} disabled={browserOpening} onclick={() => void openBrowser()} />{/if}
<PluginAccessMenu surface="open" compact /> <PluginAccessMenu surface="open" compact />
<PluginTools /> <PluginTools />
<PluginAccessMenu surface="commands" compact /> <PluginAccessMenu surface="commands" compact />
<IconButton icon="save" label="Save" disabled={editorPluginVisible || !dirty || saving} onclick={() => void save()} /> <IconButton icon="save" label={$t("Save")} disabled={editorPluginVisible || !dirty || saving} onclick={() => void save()} />
{#if terminalEnabled}<IconButton icon="terminal" label="Terminal" active={terminalOpen} onclick={toggleTerminal} />{/if} {#if terminalEnabled}<IconButton icon="terminal" label={$t("Terminal")} active={terminalOpen} onclick={toggleTerminal} />{/if}
{#if !transferredWindow}<IconButton {#if !transferredWindow}<IconButton
icon="panel-right" icon="panel-right"
label={rightOpen ? "Hide outline" : "Show outline"} label={rightOpen ? $t("Hide outline") : $t("Show outline")}
active={rightOpen} active={rightOpen}
onclick={() => (rightOpen = !rightOpen)} onclick={() => (rightOpen = !rightOpen)}
/>{/if} />{/if}
@@ -1127,7 +1128,7 @@
</div> </div>
</header> </header>
{#if !transferredWindow}<nav class="plugin-ribbon" aria-label="Plugin shortcuts" hidden={ribbonNavigation.length === 0}> {#if !transferredWindow}<nav class="plugin-ribbon" aria-label={$t("Plugin shortcuts")} hidden={ribbonNavigation.length === 0}>
{#each ribbonNavigation as item (`${item.owner}:${item.id}`)} {#each ribbonNavigation as item (`${item.owner}:${item.id}`)}
<IconButton <IconButton
icon={item.icon === "list" || item.icon === "kanban" || item.icon === "globe" || item.icon === "git" ? item.icon : "puzzle"} icon={item.icon === "list" || item.icon === "kanban" || item.icon === "globe" || item.icon === "git" ? item.icon : "puzzle"}
@@ -1147,7 +1148,7 @@
{/if} {/if}
<div class="native-left" class:sidebar-covered={!!$pluginSidebar}> <div class="native-left" class:sidebar-covered={!!$pluginSidebar}>
{#if !workspace} {#if !workspace}
{#if leftView === "bookmarks"}<BrowserSlot kind="bookmarks" />{:else}<p class="placeholder">No folder is open.</p>{/if} {#if leftView === "bookmarks"}<BrowserSlot kind="bookmarks" />{:else}<p class="placeholder">{$t("No folder is open.")}</p>{/if}
{:else} {:else}
<div class="left-stack"> <div class="left-stack">
<div class="left-layer" class:shown={leftView === "files"}> <div class="left-layer" class:shown={leftView === "files"}>
@@ -1183,12 +1184,12 @@
</div> </div>
<div class="left-footer"> <div class="left-footer">
<div class="footer-start" bind:this={workspaceAnchor}> <div class="footer-start" bind:this={workspaceAnchor}>
<IconButton icon="folder-open" label="Open folder" onclick={chooseWorkspace} /> <IconButton icon="folder-open" label={$t("Open folder")} onclick={chooseWorkspace} />
<span class="ws">{workspace ? workspace.name : "No workspace"}</span> <span class="ws">{workspace ? workspace.name : $t("No workspace")}</span>
</div> </div>
<div class="footer-actions"> <div class="footer-actions">
<IconButton icon="help" label="Help and about (F1)" onclick={() => preferences = "help"} /> <IconButton icon="help" label={$t("Help and about (F1)")} onclick={() => preferences = "help"} />
<IconButton icon="settings" label="Settings (Ctrl+,)" onclick={() => void openSettings()} /> <IconButton icon="settings" label={$t("Settings (Ctrl+,)")} onclick={() => void openSettings()} />
</div> </div>
</div> </div>
</aside> </aside>
@@ -1231,15 +1232,15 @@
onpointerdowncapture={() => focusDocumentPane(pane.id)} onpointerdowncapture={() => focusDocumentPane(pane.id)}
onfocusin={() => focusDocumentPane(pane.id)}> onfocusin={() => focusDocumentPane(pane.id)}>
{#if pane.buffer?.diskError} {#if pane.buffer?.diskError}
<div class="conflict" role="alert"><span>{pane.buffer.diskError}</span><button onclick={() => void saveCopy(pane.buffer)}>Save a copy</button><button onclick={() => void documents?.refresh()}>Retry</button></div> <div class="conflict" role="alert"><span>{pane.buffer.diskError}</span><button onclick={() => void saveCopy(pane.buffer)}>{$t("Save a copy")}</button><button onclick={() => void documents?.refresh()}>{$t("Retry")}</button></div>
{:else if pane.buffer?.diskContents != null} {:else if pane.buffer?.diskContents != null}
<div class="conflict" role="alert"> <div class="conflict" role="alert">
<span>This file changed on disk. Your edits are preserved. Review both versions before saving.</span> <span>{$t("This file changed on disk. Your edits are preserved. Review both versions before saving.")}</span>
<button onclick={() => { if (pane.buffer) documents?.resolve(pane.buffer.id, true); }}>Use disk version</button> <button onclick={() => { if (pane.buffer) documents?.resolve(pane.buffer.id, true); }}>{$t("Use disk version")}</button>
<button onclick={() => { if (pane.buffer) documents?.resolve(pane.buffer.id, false); }}>Keep my edits</button> <button onclick={() => { if (pane.buffer) documents?.resolve(pane.buffer.id, false); }}>{$t("Keep my edits")}</button>
<button onclick={() => void saveCopy(pane.buffer)}>Save a copy</button> <button onclick={() => void saveCopy(pane.buffer)}>{$t("Save a copy")}</button>
</div> </div>
<details class="disk-review"><summary>View disk version</summary><pre>{pane.buffer.diskContents}</pre></details> <details class="disk-review"><summary>{$t("View disk version")}</summary><pre>{pane.buffer.diskContents}</pre></details>
{/if} {/if}
<EditorPane <EditorPane
bind:this={paneComponents[pane.id]} bind:this={paneComponents[pane.id]}
@@ -1290,7 +1291,7 @@
getSelection={() => selectedEditorText(buffer?.id)} onConfigureTasks={configureTasks} /> getSelection={() => selectedEditorText(buffer?.id)} onConfigureTasks={configureTasks} />
{/key} {/key}
{:else} {:else}
<p class="placeholder">Open a workspace to start the terminal.</p> <p class="placeholder">{$t("Open a workspace to start the terminal.")}</p>
{/if} {/if}
</section> </section>
{/if} {/if}
@@ -1322,7 +1323,7 @@
{#if workspace} {#if workspace}
<span>{workspace.watch_mode} watch</span> <span>{workspace.watch_mode} watch</span>
{/if} {/if}
<span>{isIde ? "IDE" : "Writer"}</span> <span>{isIde ? $t("IDE") : $t("Writer")}</span>
</footer> </footer>
</div> </div>
+49 -23
View File
@@ -1,7 +1,9 @@
<script lang="ts"> <script lang="ts">
import { t, tr } from "$lib/i18n";
import { tick } from "svelte"; import { tick } from "svelte";
import Icon from "$lib/ui/Icon.svelte"; import Icon from "$lib/ui/Icon.svelte";
import { pickWorkspaceFolder, workspaceRecent } from "$lib/workspace/api"; import { attachTooltip } from "$lib/ui/tooltip";
import { pickWorkspaceFolder, workspaceRecent, workspaceForget } from "$lib/workspace/api";
let { currentRoot, anchor, onOpen }: { let { currentRoot, anchor, onOpen }: {
currentRoot?: string; anchor?: HTMLElement; currentRoot?: string; anchor?: HTMLElement;
@@ -19,21 +21,26 @@
let parent = $state(""); let parent = $state("");
let returnFocus: HTMLElement | null = null; let returnFocus: HTMLElement | null = null;
const folderName = (path: string) => path.replace(/[\\/]+$/, "").split(/[\\/]/).pop() || path; const folderName = (path: string) => path.replace(/[\\/]+$/, "").split(/[\\/]/).pop() || path;
const destination = $derived(parent ? `${parent.replace(/[\\/]+$/, "")}${parent.includes("\\") ? "\\" : "/"}${name.trim()}` : "Choose where to create your workspace."); const removeTooltip = (node: HTMLElement) => ({ destroy: attachTooltip(node, () => tr("Remove from recent workspaces")) });
const destination = $derived(parent ? `${parent.replace(/[\\/]+$/, "")}${parent.includes("\\") ? "\\" : "/"}${name.trim()}` : $t("Choose where to create your workspace."));
export async function show() { export async function show() {
if (busy || creating) return; if (busy || creating) return;
if (menu.matches(":popover-open")) { menu.hidePopover(); return; } if (menu.matches(":popover-open")) { menu.hidePopover(); return; }
returnFocus = document.activeElement instanceof HTMLElement ? document.activeElement : null; returnFocus = document.activeElement instanceof HTMLElement ? document.activeElement : null;
error = ""; loading = true; error = ""; loading = true;
const keyboard = anchor?.matches(":focus-visible") ?? false;
menu.showPopover(); menu.showPopover();
position(); position();
menu.querySelector<HTMLButtonElement>("button")?.focus(); menu.focus();
try { recent = await workspaceRecent(); } try { recent = await workspaceRecent(); }
catch (err) { error = `Could not load recent workspaces: ${String(err)}`; } catch (err) { error = tr("Could not load recent workspaces: {error}", { error: String(err) }); }
finally { loading = false; } finally { loading = false; }
await tick(); await tick();
if (menu.matches(":popover-open")) { position(); menu.querySelector<HTMLButtonElement>("button")?.focus(); } if (menu.matches(":popover-open")) {
position();
if (keyboard) (menu.querySelector<HTMLButtonElement>('button[aria-current="true"]') ?? menu.querySelector<HTMLButtonElement>("button"))?.focus();
}
} }
function position() { function position() {
@@ -44,12 +51,25 @@
function close() { menu.hidePopover(); returnFocus?.focus(); } function close() { menu.hidePopover(); returnFocus?.focus(); }
async function forget(path: string) {
if (busy) return;
busy = true; error = "";
const index = recent.indexOf(path);
try { recent = await workspaceForget(path); }
catch (err) { error = tr("Could not remove workspace from recent workspaces: {error}", { error: String(err) }); }
finally { busy = false; }
await tick();
position();
const rows = menu.querySelectorAll<HTMLButtonElement>(".workspace-row");
(rows[Math.min(index, rows.length - 1)] ?? menu.querySelector<HTMLButtonElement>("footer button"))?.focus();
}
async function open(path: string) { async function open(path: string) {
if (busy) return; if (busy) return;
if (path === currentRoot) { close(); return; } if (path === currentRoot) { close(); return; }
busy = true; error = ""; busy = true; error = "";
try { if (await onOpen(path)) close(); } try { if (await onOpen(path)) close(); }
catch (err) { error = `Could not open workspace: ${String(err)}`; } catch (err) { error = tr("Could not open workspace: {error}", { error: String(err) }); }
finally { busy = false; } finally { busy = false; }
} }
@@ -70,7 +90,7 @@
function cancel() { if (!busy) { creating = false; returnFocus?.focus(); } } function cancel() { if (!busy) { creating = false; returnFocus?.focus(); } }
async function chooseLocation() { async function chooseLocation() {
busy = true; error = ""; busy = true; error = "";
try { const path = await pickWorkspaceFolder("Choose a location for the new workspace"); if (path) parent = path; } try { const path = await pickWorkspaceFolder(tr("Choose a location for the new workspace")); if (path) parent = path; }
catch (err) { error = String(err); } catch (err) { error = String(err); }
finally { busy = false; } finally { busy = false; }
} }
@@ -93,38 +113,41 @@
</script> </script>
<svelte:window onresize={() => { if (menu?.matches(":popover-open")) position(); }} /> <svelte:window onresize={() => { if (menu?.matches(":popover-open")) position(); }} />
<div bind:this={menu} popover="auto" class="workspace-menu rs-picker" role="dialog" aria-label="Workspaces" tabindex="-1" onkeydown={navigate}> <div bind:this={menu} popover="auto" class="workspace-menu rs-picker" role="dialog" aria-label={$t("Workspaces")} tabindex="-1" onkeydown={navigate}>
<h2>Recent workspaces</h2> <h2>{$t("Recent workspaces")}</h2>
<div class="recent" aria-busy={loading || busy}> <div class="recent" aria-busy={loading || busy}>
{#if loading}<p>Loading workspaces…</p> {#if loading}<p>{$t("Loading workspaces…")}</p>
{:else if !recent.length}<p>No recent workspaces yet.</p>{/if} {:else if !recent.length}<p>{$t("No recent workspaces yet.")}</p>{/if}
{#each recent as path} {#each recent as path (path)}
<div class="workspace-entry">
<button class="workspace-row rs-picker-row" aria-current={path === currentRoot ? "true" : undefined} disabled={busy} onclick={() => open(path)}> <button class="workspace-row rs-picker-row" aria-current={path === currentRoot ? "true" : undefined} disabled={busy} onclick={() => open(path)}>
<span class="rs-picker-icon"><Icon icon="folder-open" /></span> <span class="rs-picker-icon"><Icon icon="folder-open" /></span>
<span class="details"><span>{folderName(path)}</span><small>{path}</small></span> <span class="details"><span>{folderName(path)}</span><small>{path}</small></span>
{#if path === currentRoot}<span class="current-label">Current</span>{/if} {#if path === currentRoot}<span class="current-label">{$t("Current")}</span>{/if}
</button> </button>
<button class="workspace-remove rs-picker-row" aria-label={$t("Remove {path} from recent workspaces", { path })} use:removeTooltip disabled={busy} onclick={() => forget(path)}><Icon icon="close" /></button>
</div>
{/each} {/each}
</div> </div>
{#if error}<p class="error" role="alert">{error}</p>{/if} {#if error}<p class="error" role="alert">{error}</p>{/if}
<footer> <footer>
<button class="rs-picker-row" disabled={busy} onclick={newWorkspace}><span class="rs-picker-icon"><Icon icon="folder-plus" /></span> New workspace…</button> <button class="rs-picker-row" disabled={busy} onclick={newWorkspace}><span class="rs-picker-icon"><Icon icon="folder-plus" /></span> {$t("New workspace…")}</button>
<button class="rs-picker-row" disabled={busy} onclick={browse}><span class="rs-picker-icon"><Icon icon="folder-open" /></span> Open another folder…</button> <button class="rs-picker-row" disabled={busy} onclick={browse}><span class="rs-picker-icon"><Icon icon="folder-open" /></span> {$t("Open another folder…")}</button>
</footer> </footer>
</div> </div>
{#if creating} {#if creating}
<dialog bind:this={dialog} aria-labelledby="new-workspace-title" oncancel={(event) => { event.preventDefault(); cancel(); }}> <dialog bind:this={dialog} aria-labelledby="new-workspace-title" oncancel={(event) => { event.preventDefault(); cancel(); }}>
<form onsubmit={(event) => { event.preventDefault(); void create(); }}> <form onsubmit={(event) => { event.preventDefault(); void create(); }}>
<h2 id="new-workspace-title"><Icon icon="folder-plus" /> New workspace</h2> <h2 id="new-workspace-title"><Icon icon="folder-plus" /> {$t("New workspace")}</h2>
<p>Create a folder for your notes and files, then open it in a new window.</p> <p>{$t("Create a folder for your notes and files, then open it in a new window.")}</p>
<label for="workspace-name">Workspace name</label> <label for="workspace-name">{$t("Workspace name")}</label>
<input id="workspace-name" bind:this={input} bind:value={name} oninput={() => error = ""} placeholder="My workspace" autocomplete="off" required disabled={busy} /> <input id="workspace-name" bind:this={input} bind:value={name} oninput={() => error = ""} placeholder={$t("My workspace")} autocomplete="off" required disabled={busy} />
<div class="location-label"><label for="workspace-location">Location</label><button type="button" disabled={busy} onclick={chooseLocation}><Icon icon="folder-open" /> Browse…</button></div> <div class="location-label"><label for="workspace-location">{$t("Location")}</label><button type="button" disabled={busy} onclick={chooseLocation}><Icon icon="folder-open" /> {$t("Browse…")}</button></div>
<input id="workspace-location" value={parent} readonly placeholder="Choose a parent folder" /> <input id="workspace-location" value={parent} readonly placeholder={$t("Choose a parent folder")} />
<small class="destination">{parent ? "Will create: " : ""}{destination}</small> <small class="destination">{parent ? $t("Will create: {path}", { path: destination }) : destination}</small>
{#if error}<p class="error" role="alert">{error}</p>{/if} {#if error}<p class="error" role="alert">{error}</p>{/if}
<div class="actions"><button type="button" disabled={busy} onclick={cancel}>Cancel</button><button class="primary" type="submit" disabled={busy || !name.trim() || !parent}>{busy ? "Please wait…" : "Create workspace"}</button></div> <div class="actions"><button type="button" disabled={busy} onclick={cancel}>{$t("Cancel")}</button><button class="primary" type="submit" disabled={busy || !name.trim() || !parent}>{busy ? $t("Please wait…") : $t("Create workspace")}</button></div>
</form> </form>
</dialog> </dialog>
{/if} {/if}
@@ -140,6 +163,9 @@
form button:focus-visible, input:focus-visible { outline: 2px solid var(--rs-accent); outline-offset: -2px; } form button:focus-visible, input:focus-visible { outline: 2px solid var(--rs-accent); outline-offset: -2px; }
form button:disabled { opacity: .5; } form button:disabled { opacity: .5; }
.workspace-row, footer button { width: 100%; } .workspace-row, footer button { width: 100%; }
.workspace-entry { display: flex; align-items: stretch; }
.workspace-entry .workspace-row { flex: 1; min-width: 0; }
.workspace-entry .workspace-remove { width: 30px; flex: 0 0 30px; justify-content: center; padding-inline: 0; }
.details { min-width: 0; display: flex; flex: 1; flex-direction: column; gap: 3px; } .details { min-width: 0; display: flex; flex: 1; flex-direction: column; gap: 3px; }
small { font-size: 11px; color: var(--rs-text-dim); overflow-wrap: anywhere; } small { font-size: 11px; color: var(--rs-text-dim); overflow-wrap: anywhere; }
.current-label { font-size: 11px; color: var(--rs-accent); } .current-label { font-size: 11px; color: var(--rs-accent); }
+6 -6
View File
@@ -1,6 +1,8 @@
<script lang="ts"> <script lang="ts">
import { t } from "$lib/i18n";
import { untrack } from "svelte"; import { untrack } from "svelte";
import Icon from "$lib/ui/Icon.svelte"; import Icon from "$lib/ui/Icon.svelte";
import { attachTooltip } from "$lib/ui/tooltip";
import ContextMenu from "$lib/layout/ContextMenu.svelte"; import ContextMenu from "$lib/layout/ContextMenu.svelte";
import type { MenuItem } from "$lib/layout/menuTypes"; import type { MenuItem } from "$lib/layout/menuTypes";
import { installedPlugins, pluginTools, pluginNavigation, openPluginView, runPluginCommand } from "./external"; import { installedPlugins, pluginTools, pluginNavigation, openPluginView, runPluginCommand } from "./external";
@@ -9,7 +11,8 @@
let position = $state<{ x: number; y: number } | null>(null); let position = $state<{ x: number; y: number } | null>(null);
let error = $state(""); let error = $state("");
let pointerWasOpen = false; let pointerWasOpen = false;
const label = $derived(surface === "open" ? "Plug-in views" : "Commands"); const label = $derived(surface === "open" ? $t("Plug-in views") : $t("Commands"));
function tooltip(node: HTMLElement) { return { destroy: attachTooltip(node, () => compact ? label : "") }; }
const tools = $derived($pluginTools.filter(tool => tool.surface === surface const tools = $derived($pluginTools.filter(tool => tool.surface === surface
&& tool.owner !== "runestone.browser" && tool.owner !== "runestone.browser"
&& !(surface === "open" && tool.kind === "view" && $pluginNavigation.some(item => item.owner === tool.owner && item.id === tool.id && item.placement === "sidebar")))); && !(surface === "open" && tool.kind === "view" && $pluginNavigation.some(item => item.owner === tool.owner && item.id === tool.id && item.placement === "sidebar"))));
@@ -27,22 +30,19 @@
</script> </script>
{#if tools.length} {#if tools.length}
<button class="access-button" class:compact bind:this={anchor} aria-label={label} aria-haspopup="menu" aria-expanded={position !== null} title={label} <button class="access-button" class:compact bind:this={anchor} use:tooltip aria-label={label} aria-haspopup="menu" aria-expanded={position !== null}
onpointerdown={() => pointerWasOpen = position !== null} onpointerdown={() => pointerWasOpen = position !== null}
onclick={event => { const close = event.detail > 0 ? pointerWasOpen : position !== null; const bounds = anchor!.getBoundingClientRect(); position = close ? null : { x: bounds.left, y: bounds.bottom + 4 }; }}> onclick={event => { const close = event.detail > 0 ? pointerWasOpen : position !== null; const bounds = anchor!.getBoundingClientRect(); position = close ? null : { x: bounds.left, y: bounds.bottom + 4 }; }}>
<Icon icon={surface === "open" ? "puzzle" : "code"} />{#if !compact}<span>{label}</span>{/if} <Icon icon={surface === "open" ? "puzzle" : "code"} />{#if !compact}<span>{label}</span>{/if}
{#if compact}<span class="access-tooltip" role="tooltip">{label}</span>{/if}
</button> </button>
{/if} {/if}
{#if position && tools.length}<ContextMenu {...position} {items} {label} onClose={() => position = null} />{/if} {#if position && tools.length}<ContextMenu {...position} {items} {label} onClose={() => position = null} />{/if}
{#if error}<p class="error" role="alert">{error}<button onclick={() => error = ""}>Dismiss</button></p>{/if} {#if error}<p class="error" role="alert">{error}<button onclick={() => error = ""}>{$t("Dismiss")}</button></p>{/if}
<style> <style>
.access-button { display: flex; align-items: center; gap: 6px; white-space: nowrap; min-height: 32px; padding: 5px 8px; border: 0; border-radius: var(--rs-control-radius); background: transparent; color: var(--rs-text); } .access-button { display: flex; align-items: center; gap: 6px; white-space: nowrap; min-height: 32px; padding: 5px 8px; border: 0; border-radius: var(--rs-control-radius); background: transparent; color: var(--rs-text); }
.access-button:hover, .access-button[aria-expanded="true"] { background: var(--rs-bg-active); } .access-button:hover, .access-button[aria-expanded="true"] { background: var(--rs-bg-active); }
.access-button:focus-visible { outline: 2px solid var(--rs-accent); outline-offset: -2px; } .access-button:focus-visible { outline: 2px solid var(--rs-accent); outline-offset: -2px; }
.access-button.compact { position: relative; width: 28px; height: 28px; min-height: 28px; padding: 5px; } .access-button.compact { position: relative; width: 28px; height: 28px; min-height: 28px; padding: 5px; }
.access-tooltip { display: none; position: absolute; top: calc(100% + 6px); right: 0; padding: 5px 8px; border-radius: var(--rs-control-radius); background: var(--rs-bg-elevated); border: 1px solid var(--rs-border); z-index: 60; pointer-events: none; }
.access-button:is(:hover, :focus-visible) .access-tooltip { display: block; }
.error { position: fixed; top: 48px; right: 12px; z-index: 60; max-width: 420px; padding: 12px; background: var(--rs-bg); color: var(--rs-error); border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); } .error { position: fixed; top: 48px; right: 12px; z-index: 60; max-width: 420px; padding: 12px; background: var(--rs-bg); color: var(--rs-error); border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); }
</style> </style>
+42 -41
View File
@@ -1,4 +1,5 @@
<script lang="ts"> <script lang="ts">
import { t } from "$lib/i18n";
import { onDestroy } from "svelte"; import { onDestroy } from "svelte";
import { invoke, isTauri } from "@tauri-apps/api/core"; import { invoke, isTauri } from "@tauri-apps/api/core";
import Icon from "$lib/ui/Icon.svelte"; import Icon from "$lib/ui/Icon.svelte";
@@ -54,7 +55,7 @@
async function install(enabled: boolean) { async function install(enabled: boolean) {
await run(async () => { await run(async () => {
const result = await invoke<{ name: string; error: string | null }[]>("plugins_install", { tokens: selected, enabled }); const result = await invoke<{ name: string; error: string | null }[]>("plugins_install", { tokens: selected, enabled });
message = result.filter(item => !item.error).map(item => `${item.name} installed${enabled ? " and enabled" : ""}.`).join(" "); message = result.filter(item => !item.error).map(item => $t(enabled ? "{name} installed and enabled." : "{name} installed.", { name: item.name })).join(" ");
error = result.filter(item => item.error).map(item => `${item.name}: ${item.error}`).join("\n"); error = result.filter(item => item.error).map(item => `${item.name}: ${item.error}`).join("\n");
await invoke("plugins_cancel", { tokens: candidates.map(item => item.token) }); await invoke("plugins_cancel", { tokens: candidates.map(item => item.token) });
candidates = []; selected = []; await refreshPlugins(); previous?.focus(); candidates = []; selected = []; await refreshPlugins(); previous?.focus();
@@ -74,7 +75,7 @@
async function toggle(id: string, enabled: boolean, hash?: string) { async function toggle(id: string, enabled: boolean, hash?: string) {
await run(async () => { await run(async () => {
await setPluginEnabled(id, enabled, hash); await setPluginEnabled(id, enabled, hash);
message = "Changes saved."; message = $t("Changes saved.");
}); });
} }
async function prepare(plugin: InstalledPlugin) { async function prepare(plugin: InstalledPlugin) {
@@ -84,7 +85,7 @@
if (!plan) return; if (!plan) return;
const current = plan; const current = plan;
await run(async () => { await run(async () => {
try { await invoke("plugins_remove", { token: current.token }); message = `${current.plugin.manifest.name} uninstalled. Settings and workspace documents were kept.`; } try { await invoke("plugins_remove", { token: current.token }); message = $t("{name} uninstalled. Settings and workspace documents were kept.", { name: current.plugin.manifest.name }); }
finally { plan = null; await refreshPlugins(); previous?.focus(); } finally { plan = null; await refreshPlugins(); previous?.focus(); }
}); });
} }
@@ -100,91 +101,91 @@
} }
</script> </script>
<h2>Plug-ins</h2> <h2>{$t("Plug-ins")}</h2>
<p>Install a plugin ZIP file or get a release from a Git repository link.</p> <p>{$t("Install a plugin ZIP file or get a release from a Git repository link.")}</p>
<div class="toolbar"> <div class="toolbar">
<button disabled={!desktop || busy} onclick={() => choose()}><Icon icon="file-plus" />Install plugin ZIP</button> <button disabled={!desktop || busy} onclick={() => choose()}><Icon icon="file-plus" />{$t("Install plugin ZIP")}</button>
<button disabled={!desktop || busy} onclick={() => { error = ""; gitForm = true; }}><Icon icon="link" />Install from Git link</button> <button disabled={!desktop || busy} onclick={() => { error = ""; gitForm = true; }}><Icon icon="link" />{$t("Install from Git link")}</button>
<IconButton icon="folder-open" label="Open plugins folder" disabled={!desktop || busy} onclick={() => reveal()} /> <IconButton icon="folder-open" label={$t("Open plugins folder")} disabled={!desktop || busy} onclick={() => reveal()} />
<button disabled={!desktop || busy} onclick={() => run(refreshPlugins)}><Icon icon="refresh" />Refresh</button> <button disabled={!desktop || busy} onclick={() => run(refreshPlugins)}><Icon icon="refresh" />{$t("Refresh")}</button>
</div> </div>
{#if $installedPlugins.root}<p class="path">{$installedPlugins.root}</p>{/if} {#if $installedPlugins.root}<p class="path">{$installedPlugins.root}</p>{/if}
{#if !desktop}<p>Installation requires the RuneStone desktop app.</p>{/if} {#if !desktop}<p>{$t("Installation requires the RuneStone desktop app.")}</p>{/if}
{#if $pluginServiceError}<p class="error" role="alert">{$pluginServiceError}</p>{/if} {#if $pluginServiceError}<p class="error" role="alert">{$pluginServiceError}</p>{/if}
<h3>Installed plugins</h3> <h3>{$t("Installed plugins")}</h3>
<p class="note">Plugins run with RuneStone's access. Only enable code you trust.</p> <p class="note">{$t("Plugins run with RuneStone's access. Only enable code you trust.")}</p>
{#if !external.length}<p>No plugins installed.</p>{/if} {#if !external.length}<p>{$t("No plugins installed.")}</p>{/if}
{#each external as plugin (plugin.manifest.id)} {#each external as plugin (plugin.manifest.id)}
<div class="card"> <div class="card">
<div class="row"> <div class="row">
<div class="plugin-copy"><label for={`external-${plugin.manifest.id}`}>{plugin.manifest.name}</label><p>{plugin.manifest.description}</p><small>{plugin.manifest.author} · {plugin.manifest.version} · Full app access</small> <div class="plugin-copy"><label for={`external-${plugin.manifest.id}`}>{plugin.manifest.name}</label><p>{plugin.manifest.description}</p><small>{plugin.manifest.author} · {plugin.manifest.version} · {$t("Full app access")}</small>
<div class="status"> <div class="status">
<span class="badge">{plugin.manifest.id === "runestone.browser" ? "Included with RuneStone" : plugin.removal ? "Removal incomplete" : plugin.enabled ? "Enabled" : "Disabled"}</span> <span class="badge">{plugin.manifest.id === "runestone.browser" ? $t("Included with RuneStone") : plugin.removal ? $t("Removal incomplete") : plugin.enabled ? $t("Enabled") : $t("Disabled")}</span>
<span class="note"> <span class="note">
{#if plugin.installedAt != null} {#if plugin.installedAt != null}
Installed <time datetime={new Date(plugin.installedAt).toISOString()}>{installDateFormat.format(plugin.installedAt)}</time> {$t("Installed")} <time datetime={new Date(plugin.installedAt).toISOString()}>{installDateFormat.format(plugin.installedAt)}</time>
{:else} {:else}
Install date unknown {$t("Install date unknown")}
{/if} {/if}
</span> </span>
</div> </div>
</div> </div>
<div class="controls"> <div class="controls">
<input id={`external-${plugin.manifest.id}`} type="checkbox" role="switch" checked={plugin.manifest.id === "runestone.browser" || plugin.enabled} disabled={busy || plugin.removal || plugin.manifest.id === "runestone.browser"} onchange={event => { const value = event.currentTarget.checked; event.currentTarget.checked = plugin.enabled; void toggle(plugin.manifest.id, value, plugin.hash); }} /> <input id={`external-${plugin.manifest.id}`} type="checkbox" role="switch" checked={plugin.manifest.id === "runestone.browser" || plugin.enabled} disabled={busy || plugin.removal || plugin.manifest.id === "runestone.browser"} onchange={event => { const value = event.currentTarget.checked; event.currentTarget.checked = plugin.enabled; void toggle(plugin.manifest.id, value, plugin.hash); }} />
<IconButton icon="folder-open" label="Show files" disabled={busy || plugin.removal} onclick={() => reveal(plugin.manifest.id)} /> <IconButton icon="folder-open" label={$t("Show files")} disabled={busy || plugin.removal} onclick={() => reveal(plugin.manifest.id)} />
{#if plugin.removal} {#if plugin.removal}
<button disabled={busy} onclick={() => run(async () => { await invoke("plugins_retry_remove", { id: plugin.manifest.id }); await refreshPlugins(); message = "Plugin file cleanup completed."; })}><Icon icon="refresh" />Retry cleanup</button> <button disabled={busy} onclick={() => run(async () => { await invoke("plugins_retry_remove", { id: plugin.manifest.id }); await refreshPlugins(); message = $t("Plugin file cleanup completed."); })}><Icon icon="refresh" />{$t("Retry cleanup")}</button>
{:else} {:else}
<span class="danger"><IconButton icon="trash" label="Uninstall" disabled={busy} onclick={() => prepare(plugin)} /></span> <span class="danger"><IconButton icon="trash" label={$t("Uninstall")} disabled={busy} onclick={() => prepare(plugin)} /></span>
{/if} {/if}
</div> </div>
</div> </div>
{#if plugin.manifest.id === "runestone.browser"}<p class="note">Browser is now built in. You can remove this old package. Your browser profiles and bookmarks stay available.</p>{/if} {#if plugin.manifest.id === "runestone.browser"}<p class="note">{$t("Browser is now built in. You can remove this old package. Your browser profiles and bookmarks stay available.")}</p>{/if}
{#if plugin.error || $externalErrors[plugin.manifest.id]}<p class="error" role="alert">{plugin.error || $externalErrors[plugin.manifest.id]}</p>{/if} {#if plugin.error || $externalErrors[plugin.manifest.id]}<p class="error" role="alert">{plugin.error || $externalErrors[plugin.manifest.id]}</p>{/if}
</div> </div>
{/each} {/each}
{#if $restartPlugins.length}<p class="note" role="status">Restart RuneStone to clear all code from plugins that stopped in this window.</p>{/if} {#if $restartPlugins.length}<p class="note" role="status">{$t("Restart RuneStone to clear all code from plugins that stopped in this window.")}</p>{/if}
{#if error}<p class="error" role="alert">{error}</p>{/if} {#if error}<p class="error" role="alert">{error}</p>{/if}
{#if message}<p class="saved" role="status">{message}</p>{/if} {#if message}<p class="saved" role="status">{message}</p>{/if}
{#if candidates.length || plan || gitForm} {#if candidates.length || plan || gitForm}
<dialog bind:this={modal} aria-labelledby="plugin-dialog-title" onkeydown={trap} oncancel={event => { event.preventDefault(); event.stopPropagation(); void cancel(); }}> <dialog bind:this={modal} aria-labelledby="plugin-dialog-title" onkeydown={trap} oncancel={event => { event.preventDefault(); event.stopPropagation(); void cancel(); }}>
{#if gitForm} {#if gitForm}
<h2 id="plugin-dialog-title">Install from Git link</h2> <h2 id="plugin-dialog-title">{$t("Install from Git link")}</h2>
<p>Get a Gitea release ZIP, then review it before installation. Git-link installation is an experimental feature.</p> <p>{$t("Get a Gitea release ZIP, then review it before installation. Git-link installation is an experimental feature.")}</p>
<form onsubmit={event => { event.preventDefault(); if (!busy) void fromGit(); }}> <form onsubmit={event => { event.preventDefault(); if (!busy) void fromGit(); }}>
<label class="field">Repository link<input type="url" required bind:value={gitUrl} disabled={busy} placeholder="https://host/owner/repository" /></label> <label class="field">{$t("Repository link")}<input type="url" required bind:value={gitUrl} disabled={busy} placeholder="https://host/owner/repository" /></label>
<label class="field">Release tag (optional)<input bind:value={gitTag} disabled={busy} placeholder="Latest release" maxlength="200" /></label> <label class="field">{$t("Release tag (optional)")}<input bind:value={gitTag} disabled={busy} placeholder={$t("Latest release")} maxlength="200" /></label>
<label class="field">Access token (optional)<input type="password" bind:value={gitToken} disabled={busy} autocomplete="off" /></label> <label class="field">{$t("Access token (optional)")}<input type="password" bind:value={gitToken} disabled={busy} autocomplete="off" /></label>
<p class="note">Private repositories need a token with read access. RuneStone does not save the token.</p> <p class="note">{$t("Private repositories need a token with read access. RuneStone does not save the token.")}</p>
{#if gitUrl.trim().startsWith("http:")}<p class="note">HTTP sends the token and package without encryption. Use it only for a trusted local server.</p>{/if} {#if gitUrl.trim().startsWith("http:")}<p class="note">{$t("HTTP sends the token and package without encryption. Use it only for a trusted local server.")}</p>{/if}
{#if error}<p class="error" role="alert">{error}</p>{/if} {#if error}<p class="error" role="alert">{error}</p>{/if}
<footer><button type="button" bind:this={cancelButton} disabled={busy} onclick={() => cancel()}>Cancel</button><button type="submit" disabled={busy || !gitUrl.trim()}><Icon icon="link" />{busy ? "Downloading…" : "Review release"}</button></footer> <footer><button type="button" bind:this={cancelButton} disabled={busy} onclick={() => cancel()}>{$t("Cancel")}</button><button type="submit" disabled={busy || !gitUrl.trim()}><Icon icon="link" />{busy ? $t("Downloading…") : $t("Review release")}</button></footer>
</form> </form>
{:else if plan} {:else if plan}
<h2 id="plugin-dialog-title">{`Uninstall ${plan.plugin.manifest.name}?`}</h2> <h2 id="plugin-dialog-title">{$t("Uninstall {name}?", { name: plan.plugin.manifest.name })}</h2>
<p>{plan.plugin.manifest.author} · {plan.plugin.manifest.version}</p> <p>{plan.plugin.manifest.author} · {plan.plugin.manifest.version}</p>
<p class="path">{plan.plugin.path}</p> <p class="path">{plan.plugin.path}</p>
<p>This stops the plugin in every window and permanently deletes its installed folder. Settings, source packages, and workspace documents stay intact.</p> <p>{$t("This stops the plugin in every window and permanently deletes its installed folder. Settings, source packages, and workspace documents stay intact.")}</p>
{#if error}<p class="error" role="alert">{error}</p>{/if} {#if error}<p class="error" role="alert">{error}</p>{/if}
<footer> <footer>
<button bind:this={cancelButton} disabled={busy} onclick={() => cancel()}>Cancel</button> <button bind:this={cancelButton} disabled={busy} onclick={() => cancel()}>{$t("Cancel")}</button>
<button disabled={busy} onclick={async () => { const current = plan; await cancel(); if (current) await toggle(current.plugin.manifest.id, false); }}>Disable instead</button> <button disabled={busy} onclick={async () => { const current = plan; await cancel(); if (current) await toggle(current.plugin.manifest.id, false); }}>{$t("Disable instead")}</button>
<button class="danger" disabled={busy} onclick={event => { if (event.detail < 2) void remove(); }}>{busy ? "Removing…" : "Uninstall and delete files"}</button> <button class="danger" disabled={busy} onclick={event => { if (event.detail < 2) void remove(); }}>{busy ? $t("Removing…") : $t("Uninstall and delete files")}</button>
</footer> </footer>
{:else} {:else}
<h2 id="plugin-dialog-title">Review plugin installation</h2> <h2 id="plugin-dialog-title">{$t("Review plugin installation")}</h2>
<p>Plugins run with RuneStone's access. Only enable code you trust.</p> <p>{$t("Plugins run with RuneStone's access. Only enable code you trust.")}</p>
{#each candidates as candidate (candidate.token)} {#each candidates as candidate (candidate.token)}
<div class="candidate"> <div class="candidate">
<label><input type="checkbox" bind:group={selected} value={candidate.token} disabled={busy || !!candidate.error} />{candidate.manifest?.name ?? "Invalid package"}</label> <label><input type="checkbox" bind:group={selected} value={candidate.token} disabled={busy || !!candidate.error} />{candidate.manifest?.name ?? $t("Invalid package")}</label>
{#if candidate.manifest}<p>{candidate.manifest.author} · {candidate.manifest.version}</p><p>{candidate.manifest.description}</p><p class="path">Destination: {$installedPlugins.root}\{candidate.manifest.id}</p>{/if} {#if candidate.manifest}<p>{candidate.manifest.author} · {candidate.manifest.version}</p><p>{candidate.manifest.description}</p><p class="path">{$t("Destination: {path}", { path: `${$installedPlugins.root}\\${candidate.manifest.id}` })}</p>{/if}
<p class="path">Source: {candidate.source}</p> <p class="path">{$t("Source: {path}", { path: candidate.source })}</p>
{#if candidate.error}<p class="error">{candidate.error}</p>{/if} {#if candidate.error}<p class="error">{candidate.error}</p>{/if}
</div> </div>
{/each} {/each}
{#if error}<p class="error" role="alert">{error}</p>{/if} {#if error}<p class="error" role="alert">{error}</p>{/if}
<footer><button bind:this={cancelButton} disabled={busy} onclick={() => cancel()}>Cancel</button><button disabled={busy || !selected.length} onclick={() => install(false)}>Install</button><button disabled={busy || !selected.length} onclick={() => install(true)}>Install and enable</button></footer> <footer><button bind:this={cancelButton} disabled={busy} onclick={() => cancel()}>{$t("Cancel")}</button><button disabled={busy || !selected.length} onclick={() => install(false)}>{$t("Install")}</button><button disabled={busy || !selected.length} onclick={() => install(true)}>{$t("Install and enable")}</button></footer>
{/if} {/if}
</dialog> </dialog>
{/if} {/if}
+3 -2
View File
@@ -1,4 +1,5 @@
<script lang="ts"> <script lang="ts">
import { t } from "$lib/i18n";
import IconButton from "$lib/ui/IconButton.svelte"; import IconButton from "$lib/ui/IconButton.svelte";
import { pluginView, mountPluginView } from "./external"; import { pluginView, mountPluginView } from "./external";
@@ -22,10 +23,10 @@
}); });
</script> </script>
{#if error && $pluginView?.placement !== "dialog"}<p class="error" role="alert">{error}<button onclick={() => error = ""}>Dismiss</button></p>{/if} {#if error && $pluginView?.placement !== "dialog"}<p class="error" role="alert">{error}<button onclick={() => error = ""}>{$t("Dismiss")}</button></p>{/if}
{#if $pluginView?.placement === "dialog"} {#if $pluginView?.placement === "dialog"}
<dialog bind:this={dialog} aria-label={$pluginView.title} oncancel={event => { event.preventDefault(); pluginView.set(null); }}> <dialog bind:this={dialog} aria-label={$pluginView.title} oncancel={event => { event.preventDefault(); pluginView.set(null); }}>
<header><h2>{$pluginView.title}</h2><IconButton icon="close" label="Close plugin view" onclick={() => pluginView.set(null)} /></header> <header><h2>{$pluginView.title}</h2><IconButton icon="close" label={$t("Close plugin view")} onclick={() => pluginView.set(null)} /></header>
{#if error}<p class="error" role="alert">{error}</p>{/if} {#if error}<p class="error" role="alert">{error}</p>{/if}
<div class="plugin-content" bind:this={host}></div> <div class="plugin-content" bind:this={host}></div>
</dialog> </dialog>
+1 -1
View File
@@ -3,7 +3,7 @@ import type { PluginCommand, PluginView } from "./sdk.ts";
export type PluginTool = { export type PluginTool = {
owner: string; id: string; title: string; kind: "command" | "view"; owner: string; id: string; title: string; kind: "command" | "view";
surface: "commands" | "open" | "settings"; surface: "commands" | "open" | "settings";
icon?: PluginView["icon"]; icon?: PluginCommand["icon"];
}; };
export function pluginAccess(owner: string, commands: Iterable<PluginCommand>, views: Iterable<PluginView>): PluginTool[] { export function pluginAccess(owner: string, commands: Iterable<PluginCommand>, views: Iterable<PluginView>): PluginTool[] {
+2 -2
View File
@@ -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-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-sidebar-bg', 'var(--rs-image-sidebar-bg)');
body.style.setProperty('--rs-workarea-editor-bg', 'var(--rs-image-editor-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-surface-opacity', 'var(--rs-surface-opacity, 82%)');
body.style.setProperty('--rs-workarea-plugin-bg', 'transparent'); 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-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-image', frame.previous ? image(frame.previous).image : 'none');
body.style.setProperty('--rs-background-previous-position', frame.previous?.position ?? frame.position); body.style.setProperty('--rs-background-previous-position', frame.previous?.position ?? frame.position);
+1
View File
@@ -254,6 +254,7 @@ async function activate(row: InstalledPlugin, builtin?: PluginModule) {
workspace: { workspace: {
list: path => workspaceList(path ?? ""), read: workspaceRead, list: path => workspaceList(path ?? ""), read: workspaceRead,
listMarkdown: () => invoke<string[]>("workspace_list_markdown"), listMarkdown: () => invoke<string[]>("workspace_list_markdown"),
readMany: paths => invoke<{ path: string; source?: string; error?: string }[]>("workspace_read_many", { paths }),
readBytes: workspaceReadBytes, readBytes: workspaceReadBytes,
write: async (path, source, expected) => { canWrite(path); await workspaceWrite(path, source, expected); notifyPluginWorkspace(); }, write: async (path, source, expected) => { canWrite(path); await workspaceWrite(path, source, expected); notifyPluginWorkspace(); },
subscribe: listener => { workspaceListeners.add(listener); return () => { workspaceListeners.delete(listener); }; }, subscribe: listener => { workspaceListeners.add(listener); return () => { workspaceListeners.delete(listener); }; },
+3
View File
@@ -4,6 +4,7 @@ import { registerCompletionInput } from "../completion/input.ts";
import { showActionMenu } from "../ui/managedActionMenu.ts"; import { showActionMenu } from "../ui/managedActionMenu.ts";
import { backgroundHub } from "./backgrounds.ts"; import { backgroundHub } from "./backgrounds.ts";
import type { BackgroundFiles } from "./backgroundContracts.ts"; import type { BackgroundFiles } from "./backgroundContracts.ts";
import { pluginTranslation } from "./translation.ts";
import type { Dispose, PluginApi, PluginCommand, PluginModule, PluginView, PluginDocumentType, PluginDocumentContext } from "./sdk.ts"; import type { Dispose, PluginApi, PluginCommand, PluginModule, PluginView, PluginDocumentType, PluginDocumentContext } from "./sdk.ts";
export function deadline<T>(work: Promise<T>, milliseconds = 5000): Promise<T> { export function deadline<T>(work: Promise<T>, milliseconds = 5000): Promise<T> {
@@ -54,6 +55,7 @@ export class ExternalSession {
}; };
const api: PluginApi = { const api: PluginApi = {
id: this.id, signal: this.controller.signal, id: this.id, signal: this.controller.signal,
i18n: pluginTranslation(() => this.check(), off => { this.contributions.push(off); }),
...(this.services.backgrounds ? { backgrounds: { ...(this.services.backgrounds ? { backgrounds: {
version: 1 as const, version: 1 as const,
chooseFolder: () => this.backgroundRequest(() => this.services.backgrounds!.chooseFolder()), chooseFolder: () => this.backgroundRequest(() => this.services.backgrounds!.chooseFolder()),
@@ -139,6 +141,7 @@ export class ExternalSession {
list: path => { this.check(); return this.services.workspace.list(path); }, list: path => { this.check(); return this.services.workspace.list(path); },
...(this.services.workspace.listMarkdown ? { listMarkdown: () => { this.check(); return this.services.workspace.listMarkdown!(); } } : {}), ...(this.services.workspace.listMarkdown ? { listMarkdown: () => { this.check(); return this.services.workspace.listMarkdown!(); } } : {}),
read: path => { this.check(); return this.services.workspace.read(path); }, 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.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.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); } } : {}), ...(this.services.workspace.create ? { create: (path: string, contents: string) => { this.check(); return this.services.workspace.create!(path, contents); } } : {}),
+4 -1
View File
@@ -1,10 +1,11 @@
import type { Contributions } from "./contracts.ts"; import type { Contributions } from "./contracts.ts";
import type { CompletionApi } from "../completion/contracts.ts"; import type { CompletionApi } from "../completion/contracts.ts";
import type { ActionMenuItem } from "../ui/actionMenu.ts"; import type { ActionMenuItem } from "../ui/actionMenu.ts";
import type { ActionIcon } from "../ui/actionIcons.ts";
export type { BackgroundFrame, BackgroundApi } from "./backgroundContracts.ts"; export type { BackgroundFrame, BackgroundApi } from "./backgroundContracts.ts";
/** Package API v1. Compiled plugins export activate(api). */ /** Package API v1. Compiled plugins export activate(api). */
export type Dispose = () => void | Promise<void>; export type Dispose = () => void | Promise<void>;
export interface PluginCommand { id: string; title: string; icon?: PluginView["icon"]; category?: "open" | "action"; run: () => void | Promise<void> } export interface PluginCommand { id: string; title: string; icon?: ActionIcon | PluginView["icon"]; category?: "open" | "action"; run: () => void | Promise<void> }
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<void>; mount: (container: HTMLElement, context?: { surface: "settings" | "view" }) => void | Dispose | Promise<void | Dispose> } 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<void>; mount: (container: HTMLElement, context?: { surface: "settings" | "view" }) => void | Dispose | Promise<void | Dispose> }
export interface PluginViewOpenOptions { split: "right" | "down"; relativeTo: string } export interface PluginViewOpenOptions { split: "right" | "down"; relativeTo: string }
export interface PluginDocumentContext { id: string; path: string } export interface PluginDocumentContext { id: string; path: string }
@@ -19,6 +20,7 @@ export interface PluginDocumentType {
mount(container: HTMLElement, document: PluginDocumentContext): void | Dispose | Promise<void | Dispose>; mount(container: HTMLElement, document: PluginDocumentContext): void | Dispose | Promise<void | Dispose>;
} }
export interface PluginApi { export interface PluginApi {
i18n?: import("./translation.ts").PluginTranslation;
backgrounds?: import("./backgroundContracts.ts").BackgroundApi; backgrounds?: import("./backgroundContracts.ts").BackgroundApi;
ui?: { showActionMenu(options: import("../ui/managedActionMenu.ts").MenuOptions): { close(): void } }; ui?: { showActionMenu(options: import("../ui/managedActionMenu.ts").MenuOptions): { close(): void } };
git?: import("../git/contracts.ts").GitApi; git?: import("../git/contracts.ts").GitApi;
@@ -44,6 +46,7 @@ export interface PluginApi {
list(path?: string): Promise<{ name: string; rel_path: string; kind: string }[]>; list(path?: string): Promise<{ name: string; rel_path: string; kind: string }[]>;
listMarkdown?(): Promise<string[]>; listMarkdown?(): Promise<string[]>;
read(path: string): Promise<string>; read(path: string): Promise<string>;
readMany?(paths: string[]): Promise<{ path: string; source?: string; error?: string }[]>;
readBytes?(path: string): Promise<Uint8Array>; readBytes?(path: string): Promise<Uint8Array>;
readOptional?(path: string): Promise<string | null>; readOptional?(path: string): Promise<string | null>;
create?(path: string, contents: string): Promise<void>; create?(path: string, contents: string): Promise<void>;
+30
View File
@@ -0,0 +1,30 @@
import { get } from 'svelte/store';
import { locale, translate, type Locale } from '../i18n/index.ts';
export type PluginCatalogs = Partial<Record<Locale, Record<string, string>>>;
export interface PluginTranslation {
readonly locale: Locale;
t(message: string, values?: Record<string, string | number>, 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;
},
};
}
+54 -37
View File
@@ -1,4 +1,5 @@
<script lang="ts"> <script lang="ts">
import { t } from "$lib/i18n";
import { onMount, onDestroy } from 'svelte'; import { onMount, onDestroy } from 'svelte';
import { invoke, isTauri } from '@tauri-apps/api/core'; import { invoke, isTauri } from '@tauri-apps/api/core';
import { customThemes, installTheme, parseCustomTheme, removeTheme, type CustomTheme } from './customThemes'; import { customThemes, installTheme, parseCustomTheme, removeTheme, type CustomTheme } from './customThemes';
@@ -18,37 +19,37 @@
let closePicker = () => {}; let closePicker = () => {};
const themes = $derived([...BUILTIN_THEMES, ...installed.map(theme => ({ id: `custom:${theme.id}` as ThemeName, name: theme.name }))].flatMap(theme => const themes = $derived([...BUILTIN_THEMES, ...installed.map(theme => ({ id: `custom:${theme.id}` as ThemeName, name: theme.name }))].flatMap(theme =>
themeModes(theme.id).map(mode => ({ themeModes(theme.id).map(mode => ({
theme: theme.id, mode, name: themeModes(theme.id).length === 1 ? theme.name : `${theme.name} ${mode === 'light' ? 'Light' : 'Dark'}`, theme: theme.id, mode, name: themeModes(theme.id).length === 1 ? theme.name : `${theme.name} ${mode === 'light' ? $t('Light') : $t('Dark')}`,
})))); }))));
onDestroy(() => closePicker()); onDestroy(() => closePicker());
function picker(event: MouseEvent) { function picker(event: MouseEvent) {
closePicker(); closePicker();
const anchor = event.currentTarget as HTMLButtonElement; const anchor = event.currentTarget as HTMLButtonElement;
const bounds = anchor.getBoundingClientRect(); const bounds = anchor.getBoundingClientRect();
closePicker = showActionMenu({ x: bounds.left, y: bounds.bottom + 4, label: 'Color theme', parent: anchor.closest('dialog') ?? undefined, closePicker = showActionMenu({ x: bounds.left, y: bounds.bottom + 4, label: $t('Color theme'), parent: anchor.closest('dialog') ?? undefined,
items: themes.map(choice => ({ label: choice.name, radio: true, checked: choice.theme === appearance.theme && choice.mode === appearance.mode, items: themes.map(choice => ({ label: choice.name, radio: true, checked: choice.theme === appearance.theme && choice.mode === appearance.mode,
run: () => change({ ...appearance, theme: choice.theme, mode: choice.mode }) })) }).close; run: () => change({ ...appearance, theme: choice.theme, mode: choice.mode }) })) }).close;
} }
const positionLabels = ['Center', 'Top left', 'Top center', 'Top right', 'Center left', 'Center right', 'Bottom left', 'Bottom center', 'Bottom right']; const positionLabels = $derived([$t('Center'), $t('Top left'), $t('Top center'), $t('Top right'), $t('Center left'), $t('Center right'), $t('Bottom left'), $t('Bottom center'), $t('Bottom right')]);
const sizeLabels = ['Fill', 'Fit', 'Actual size']; const sizeLabels = $derived([$t('Fill'), $t('Fit'), $t('Actual size')]);
function backgroundPicker(event: MouseEvent, field: 'position' | 'size') { function backgroundPicker(event: MouseEvent, field: 'position' | 'size') {
closePicker(); closePicker();
const anchor = event.currentTarget as HTMLButtonElement; const anchor = event.currentTarget as HTMLButtonElement;
const bounds = anchor.getBoundingClientRect(); const bounds = anchor.getBoundingClientRect();
const values = field === 'position' ? BACKGROUND_POSITIONS : BACKGROUND_SIZES; const values = field === 'position' ? BACKGROUND_POSITIONS : BACKGROUND_SIZES;
const labels = field === 'position' ? positionLabels : sizeLabels; const labels = field === 'position' ? positionLabels : sizeLabels;
closePicker = showActionMenu({ x: bounds.left, y: bounds.bottom + 4, label: field === 'position' ? 'Image position' : 'Image size', parent: anchor.closest('dialog') ?? undefined, closePicker = showActionMenu({ x: bounds.left, y: bounds.bottom + 4, label: field === 'position' ? $t('Image position') : $t('Image size'), parent: anchor.closest('dialog') ?? undefined,
items: values.map((value, index) => ({ label: labels[index], radio: true, checked: value === appearance.newTabBackground?.[field], items: values.map((value, index) => ({ label: labels[index], radio: true, checked: value === appearance.newTabBackground?.[field],
run: () => change({ ...appearance, newTabBackground: { ...appearance.newTabBackground, [field]: value } }) })) }).close; run: () => change({ ...appearance, newTabBackground: { ...appearance.newTabBackground, [field]: value } }) })) }).close;
} }
onMount(() => { onMount(() => {
const read = () => { try { installed = customThemes(); appearance = parseAppearance(localStorage.getItem(APPEARANCE_KEY)); } catch { error = 'Could not read appearance settings.'; } }; const read = () => { try { installed = customThemes(); appearance = parseAppearance(localStorage.getItem(APPEARANCE_KEY)); } catch { error = $t('Could not read appearance settings.'); } };
read(); window.addEventListener('storage', read); window.addEventListener('focus', read); read(); window.addEventListener('storage', read); window.addEventListener('focus', read);
return () => { window.removeEventListener('storage', read); window.removeEventListener('focus', read); }; return () => { window.removeEventListener('storage', read); window.removeEventListener('focus', read); };
}); });
function change(next: Appearance) { function change(next: Appearance) {
try { saveAppearance(next); appearance = normalizeAppearance(next); error = ''; return true; } try { saveAppearance(next); appearance = normalizeAppearance(next); error = ''; return true; }
catch { error = 'Could not save appearance settings.'; return false; } catch { error = $t('Could not save appearance settings.'); return false; }
} }
function changeOverlay(input: HTMLInputElement) { function changeOverlay(input: HTMLInputElement) {
const percent = input.valueAsNumber; const percent = input.valueAsNumber;
@@ -59,14 +60,14 @@
backgroundRevision++; backgroundRevision++;
const old = appearance.newTabBackground?.imageId; const old = appearance.newTabBackground?.imageId;
if (change({ ...appearance, newTabBackground: undefined }) && old) { if (change({ ...appearance, newTabBackground: undefined }) && old) {
try { await removeBackgroundImage(old); } catch { error = 'Could not remove the saved image from storage.'; } try { await removeBackgroundImage(old); } catch { error = $t('Could not remove the saved image from storage.'); }
} }
} }
async function importTheme(file?: File) { async function importTheme(file?: File) {
if (!file) return; if (!file) return;
try { try {
if (file.size > 65536) throw new Error('Choose a theme smaller than 64 KiB.'); if (file.size > 65536) throw new Error($t('Choose a theme smaller than 64 KiB.'));
const theme = parseCustomTheme(JSON.parse(await file.text())); const theme = parseCustomTheme(JSON.parse(await file.text()), appearance.mode);
installTheme(theme); installed = customThemes(); installTheme(theme); installed = customThemes();
change({ ...appearance, theme: `custom:${theme.id}` }); change({ ...appearance, theme: `custom:${theme.id}` });
} catch (reason) { error = String(reason); } } catch (reason) { error = String(reason); }
@@ -76,7 +77,7 @@
if (!file) return; if (!file) return;
const revision = ++backgroundRevision; const revision = ++backgroundRevision;
try { try {
if (!['image/png', 'image/jpeg', 'image/webp', 'image/gif'].includes(file.type)) throw new Error('Choose a PNG, JPEG, WebP, or GIF image.'); if (!['image/png', 'image/jpeg', 'image/webp', 'image/gif'].includes(file.type)) throw new Error($t('Choose a PNG, JPEG, WebP, or GIF image.'));
const imageId = await saveBackgroundImage(file); const imageId = await saveBackgroundImage(file);
if (revision !== backgroundRevision) { await removeBackgroundImage(imageId); return; } if (revision !== backgroundRevision) { await removeBackgroundImage(imageId); return; }
const old = appearance.newTabBackground?.imageId; const old = appearance.newTabBackground?.imageId;
@@ -90,59 +91,65 @@
if (exporting) return; if (exporting) return;
exporting = true; error = ''; status = ''; exporting = true; error = ''; status = '';
try { try {
const source = exportAppearanceTheme(appearance.theme); const source = exportAppearanceTheme(appearance.theme, appearance.mode);
const contents = JSON.stringify(source, null, 2) + '\n'; const contents = JSON.stringify(source, null, 2) + '\n';
if (isTauri()) { if (isTauri()) {
const path = await invoke<string | null>('theme_export', { contents, defaultName: source.id + '.json' }); const path = await invoke<string | null>('theme_export', { contents, defaultName: source.id + '.json' });
status = path ? `Theme saved to ${path}` : 'Export canceled.'; status = path ? $t('Theme saved to {path}', { path }) : $t('Export canceled.');
} else { } else {
const url = URL.createObjectURL(new Blob([contents], { type: 'application/json' })); const url = URL.createObjectURL(new Blob([contents], { type: 'application/json' }));
const link = document.createElement('a'); link.href = url; link.download = source.id + '.json'; const link = document.createElement('a'); link.href = url; link.download = source.id + '.json';
document.body.append(link); link.click(); link.remove(); document.body.append(link); link.click(); link.remove();
setTimeout(() => URL.revokeObjectURL(url), 1000); setTimeout(() => URL.revokeObjectURL(url), 1000);
status = 'Theme download started.'; status = $t('Theme download started.');
} }
} catch (reason) { error = `Could not export the theme: ${String(reason)}`; } } catch (reason) { error = $t('Could not export the theme: {error}', { error: String(reason) }); }
finally { exporting = false; } finally { exporting = false; }
} }
</script> </script>
<h2>Appearance</h2> <h2>{$t("Appearance")}</h2>
<p>Choose a color theme variant.</p> <p>{$t("Choose a color theme variant.")}</p>
<div class="card"> <div class="card">
<div class="setting-row"><span>Color theme</span><button class="picker" aria-label="Color theme" aria-haspopup="menu" onclick={event => picker(event)}>{themes.find(theme => theme.theme === appearance.theme && theme.mode === appearance.mode)?.name ?? 'RuneStone Dark'}<Icon icon="chevron-down" /></button></div> <div class="setting-row"><span>{$t("Color theme")}</span><button class="picker" aria-label={$t("Color theme")} aria-haspopup="menu" onclick={event => picker(event)}>{themes.find(theme => theme.theme === appearance.theme && theme.mode === appearance.mode)?.name ?? 'RuneStone Dark'}<Icon icon="chevron-down" /></button></div>
</div> </div>
<div class="theme-preview" role="img" aria-label="Color theme preview"> <div class="theme-preview" role="img" aria-label={$t("Color theme preview")}>
<div class="preview-sidebar" aria-hidden="true"><span></span><span></span><span></span></div> <div class="preview-sidebar" aria-hidden="true"><span></span><span></span><span></span></div>
<div class="preview-document" aria-hidden="true"><strong>RuneStone</strong><span class="preview-prose">A place for your ideas.</span><span class="preview-selection">Selected text</span><span class="preview-link">Link</span><code class="preview-code"><span class="preview-keyword">const</span> name = <span class="preview-string">"RuneStone"</span>;<br /><span class="preview-function">show</span>(name, <span class="preview-number">42</span>);</code></div> <div class="preview-document" aria-hidden="true"><strong>RuneStone</strong><span class="preview-prose">{$t("A place for your ideas.")}</span><span class="preview-selection">{$t("Selected text")}</span><span class="preview-link">{$t("Link")}</span><code class="preview-code"><span class="preview-keyword">const</span> name = <span class="preview-string">"RuneStone"</span>;<br /><span class="preview-function">show</span>(name, <span class="preview-number">42</span>);</code></div>
</div> </div>
<div class="theme-actions"> <div class="theme-actions">
<input bind:this={themeInput} type="file" accept=".json,application/json" aria-label="Theme JSON file" hidden onchange={event => { void importTheme(event.currentTarget.files?.[0]); }} /> <input bind:this={themeInput} type="file" accept=".json,application/json" aria-label={$t("Theme JSON file")} hidden onchange={event => { void importTheme(event.currentTarget.files?.[0]); }} />
<button onclick={() => themeInput.click()}>Install theme</button> <button onclick={() => themeInput.click()}>{$t("Install theme")}</button>
<button disabled={exporting} onclick={() => void exportTemplate()}>{exporting ? 'Exporting…' : 'Export theme template'}</button> <button disabled={exporting} onclick={() => void exportTemplate()}>{exporting ? $t('Exporting…') : $t('Export theme template')}</button>
{#if appearance.theme.startsWith('custom:')}<IconButton icon="trash" label="Remove custom theme" onclick={() => { {#if appearance.theme.startsWith('custom:')}<IconButton icon="trash" label={$t("Remove custom theme")} onclick={() => {
try { removeTheme(appearance.theme.slice(7)); installed = customThemes(); change({ ...appearance, theme: 'default' }); } try { removeTheme(appearance.theme.slice(7)); installed = customThemes(); change({ ...appearance, theme: 'default' }); }
catch { error = 'Could not remove this theme.'; } catch { error = 'Could not remove this theme.'; }
}} />{/if} }} />{/if}
</div> </div>
<p>Edit the exported JSON colors, then choose Install theme. Each theme has light and dark colors.</p> <p>{$t("Edit the exported JSON colors and fonts, then choose Install theme. The template contains one color palette and font families.")}</p>
{#if appearance.theme === 'sakura'}<p>Sakura uses a light appearance.</p>{/if} {#if appearance.theme === 'sakura'}<p>{$t("Sakura uses a light appearance.")}</p>{/if}
<h3>Background image</h3> <h3>{$t("Transparency")}</h3>
<div class="background-preview" aria-label="Background image preview"><span>Background</span></div> <div class="card">
<label><span>{$t("Transparent surfaces")}</span><input type="checkbox" role="switch" checked={appearance.transparency?.enabled !== false} onchange={event => change({ ...appearance, transparency: { amount: appearance.transparency?.amount ?? 18, enabled: event.currentTarget.checked } })} /></label>
<div class="setting-row"><label for="surface-transparency">{$t("Transparency amount")}</label><div class="overlay-controls"><input id="surface-transparency" type="range" min="0" max="100" step="1" disabled={appearance.transparency?.enabled === false} value={appearance.transparency?.amount ?? 18} oninput={event => change({ ...appearance, transparency: { enabled: true, amount: event.currentTarget.valueAsNumber } })} /><output for="surface-transparency">{appearance.transparency?.amount ?? 18}%</output></div></div>
</div>
<p>{$t("Turn off transparency to use opaque surfaces and reduce compositing work. Text and icons remain opaque.")}</p>
<h3>{$t("Background image")}</h3>
<div class="background-preview" aria-label={$t("Background image preview")}><span>{$t("Background")}</span></div>
{#if appearance.newTabBackground} {#if appearance.newTabBackground}
<div class="card"> <div class="card">
<div class="setting-row"><span>Image position</span><button class="picker" aria-label="Image position" aria-haspopup="menu" onclick={event => backgroundPicker(event, 'position')}>{positionLabels[BACKGROUND_POSITIONS.indexOf(appearance.newTabBackground.position ?? 'center')]}<Icon icon="chevron-down" /></button></div> <div class="setting-row"><span>{$t("Image position")}</span><button class="picker" aria-label={$t("Image position")} aria-haspopup="menu" onclick={event => backgroundPicker(event, 'position')}>{positionLabels[BACKGROUND_POSITIONS.indexOf(appearance.newTabBackground.position ?? 'center')]}<Icon icon="chevron-down" /></button></div>
<div class="setting-row"><span>Image size</span><button class="picker" aria-label="Image size" aria-haspopup="menu" onclick={event => backgroundPicker(event, 'size')}>{sizeLabels[BACKGROUND_SIZES.indexOf(appearance.newTabBackground.size ?? 'cover')]}<Icon icon="chevron-down" /></button></div> <div class="setting-row"><span>{$t("Image size")}</span><button class="picker" aria-label={$t("Image size")} aria-haspopup="menu" onclick={event => backgroundPicker(event, 'size')}>{sizeLabels[BACKGROUND_SIZES.indexOf(appearance.newTabBackground.size ?? 'cover')]}<Icon icon="chevron-down" /></button></div>
<div class="setting-row"><span>Image overlay</span><div class="overlay-controls"><input type="range" aria-label="Image overlay" min="-100" max="100" value={Math.round((appearance.newTabBackground.overlay ?? 0) * 100)} oninput={event => changeOverlay(event.currentTarget)} /><label class="overlay-value"><input type="number" aria-label="Image overlay percentage" min="-100" max="100" step="1" value={Math.round((appearance.newTabBackground.overlay ?? 0) * 100)} oninput={event => changeOverlay(event.currentTarget)} onblur={event => { event.currentTarget.value = String(Math.round((appearance.newTabBackground?.overlay ?? 0) * 100)); }} /><span>%</span></label></div></div> <div class="setting-row"><span>{$t("Image overlay")}</span><div class="overlay-controls"><input type="range" aria-label={$t("Image overlay")} min="-100" max="100" value={Math.round((appearance.newTabBackground.overlay ?? 0) * 100)} oninput={event => changeOverlay(event.currentTarget)} /><label class="overlay-value"><input type="number" aria-label={$t("Image overlay percentage")} min="-100" max="100" step="1" value={Math.round((appearance.newTabBackground.overlay ?? 0) * 100)} oninput={event => changeOverlay(event.currentTarget)} onblur={event => { event.currentTarget.value = String(Math.round((appearance.newTabBackground?.overlay ?? 0) * 100)); }} /><span>%</span></label></div></div>
</div> </div>
<p>Move left to lighten the image or right to darken it.</p> <p>{$t("Move left to lighten the image or right to darken it.")}</p>
{/if} {/if}
<div class="theme-actions"> <div class="theme-actions">
<input bind:this={backgroundInput} type="file" accept="image/png,image/jpeg,image/webp,image/gif" aria-label="Background image file" hidden onchange={event => void importBackground(event.currentTarget.files?.[0])} /> <input bind:this={backgroundInput} type="file" accept="image/png,image/jpeg,image/webp,image/gif" aria-label={$t("Background image file")} hidden onchange={event => void importBackground(event.currentTarget.files?.[0])} />
<button onclick={() => backgroundInput.click()}>Choose image…</button> <button onclick={() => backgroundInput.click()}>{$t("Choose image…")}</button>
{#if appearance.newTabBackground}<button onclick={() => void removeBackground()}>Remove image</button>{/if} {#if appearance.newTabBackground}<button onclick={() => void removeBackground()}>{$t("Remove image")}</button>{/if}
<button disabled={!appearance.newTabBackground} onclick={() => void removeBackground()}>Reset background</button> <button disabled={!appearance.newTabBackground} onclick={() => void removeBackground()}>{$t("Reset background")}</button>
</div> </div>
<p>PNG, JPEG, WebP, or GIF, up to 50 MiB. The image applies to new tabs on this device.</p> <p>{$t("PNG, JPEG, WebP, or GIF, up to 50 MiB. The image applies to new tabs on this device.")}</p>
{#if status}<p role="status">{status}</p>{/if} {#if status}<p role="status">{status}</p>{/if}
{#if error}<p role="alert">{error}</p>{/if} {#if error}<p role="alert">{error}</p>{/if}
<style> <style>
@@ -170,6 +177,16 @@
.preview-number{color:var(--rs-syntax-number,var(--rs-special))} .preview-number{color:var(--rs-syntax-number,var(--rs-special))}
.overlay-controls{display:flex;align-items:center;flex-wrap:wrap;gap:var(--rs-settings-gap);max-width:100%} .overlay-controls{display:flex;align-items:center;flex-wrap:wrap;gap:var(--rs-settings-gap);max-width:100%}
.overlay-controls input[type=range]{width:160px;max-width:100%;min-width:0} .overlay-controls input[type=range]{width:160px;max-width:100%;min-width:0}
input[type=checkbox]{accent-color:var(--rs-accent)}
.overlay-controls input[type=range]{appearance:none;background:transparent;height:var(--rs-settings-control-height);margin:0;cursor:pointer}
.overlay-controls input[type=range]::-webkit-slider-runnable-track{height:6px;background:var(--rs-bg-active);border:1px solid var(--rs-text-dim);border-radius:var(--rs-control-radius)}
.overlay-controls input[type=range]::-webkit-slider-thumb{appearance:none;width:18px;height:18px;margin-top:-7px;background:var(--rs-accent);border:2px solid var(--rs-text-strong);border-radius:50%}
.overlay-controls input[type=range]::-moz-range-track{height:4px;background:var(--rs-bg-active);border:1px solid var(--rs-text-dim);border-radius:var(--rs-control-radius)}
.overlay-controls input[type=range]::-moz-range-thumb{width:14px;height:14px;background:var(--rs-accent);border:2px solid var(--rs-text-strong);border-radius:50%}
.overlay-controls input[type=range]:focus-visible{outline:2px solid var(--rs-accent);outline-offset:2px;border-radius:var(--rs-control-radius)}
.overlay-controls input[type=range]:disabled{cursor:default}
.overlay-controls input[type=range]:disabled::-webkit-slider-thumb{background:var(--rs-text-dim)}
.overlay-controls input[type=range]:disabled::-moz-range-thumb{background:var(--rs-text-dim)}
.overlay-value{padding:0;gap:4px;flex-wrap:nowrap} .overlay-value{padding:0;gap:4px;flex-wrap:nowrap}
.overlay-value input{width:64px;min-height:var(--rs-settings-control-height);box-sizing:border-box;padding:4px 6px;background:var(--rs-bg);color:var(--rs-text);border:1px solid var(--rs-border);border-radius:var(--rs-control-radius);font:inherit} .overlay-value input{width:64px;min-height:var(--rs-settings-control-height);box-sizing:border-box;padding:4px 6px;background:var(--rs-bg);color:var(--rs-text);border:1px solid var(--rs-border);border-radius:var(--rs-control-radius);font:inherit}
.overlay-value input:focus-visible{outline:2px solid var(--rs-accent);outline-offset:2px} .overlay-value input:focus-visible{outline:2px solid var(--rs-accent);outline-offset:2px}
+3 -1
View File
@@ -1,8 +1,10 @@
<script lang="ts"> <script lang="ts">
import { syncLocale } from '$lib/i18n';
import { onMount } from 'svelte'; import { onMount } from 'svelte';
import { APPEARANCE_KEY, applyAppearance, parseAppearance } from './appearance'; import { APPEARANCE_KEY, applyAppearance, parseAppearance } from './appearance';
import { CUSTOM_THEMES_KEY } from './customThemes'; import { CUSTOM_THEMES_KEY } from './customThemes';
onMount(() => { onMount(() => {
const stopLocale = syncLocale();
const read = () => { const read = () => {
try { try {
const raw = localStorage.getItem(APPEARANCE_KEY); const raw = localStorage.getItem(APPEARANCE_KEY);
@@ -17,7 +19,7 @@
read(); read();
window.addEventListener('storage', sync); window.addEventListener('storage', sync);
window.addEventListener('focus', read); window.addEventListener('focus', read);
return () => { window.removeEventListener('storage', sync); window.removeEventListener('focus', read); }; return () => { stopLocale(); window.removeEventListener('storage', sync); window.removeEventListener('focus', read); };
}); });
</script> </script>
+62 -19
View File
@@ -1,4 +1,4 @@
import { customThemes, type CustomTheme } from './customThemes.ts'; import { customThemes, FONT_ROLES, type ThemeFonts, type ThemeColors, type CustomTheme } from './customThemes.ts';
import { readBackgroundImage } from './backgroundImages.ts'; import { readBackgroundImage } from './backgroundImages.ts';
import { characterTheme, characterSyntax, SYNTAX_ROLES } from './characterThemes.ts'; import { characterTheme, characterSyntax, SYNTAX_ROLES } from './characterThemes.ts';
export const APPEARANCE_KEY = 'runestone.appearance'; export const APPEARANCE_KEY = 'runestone.appearance';
@@ -11,17 +11,22 @@ export const BUILTIN_THEMES = [
const LEGACY_THEME_IDS: Record<string, typeof THEMES[number]> = { holo: 'harvest-moon', asuka: 'crimson-pilot', malfoid: 'silver-serpent' }; const LEGACY_THEME_IDS: Record<string, typeof THEMES[number]> = { holo: 'harvest-moon', asuka: 'crimson-pilot', malfoid: 'silver-serpent' };
export function themeModes(theme: string): readonly ('light' | 'dark')[] { export function themeModes(theme: string): readonly ('light' | 'dark')[] {
const character = characterTheme(theme); const character = characterTheme(theme);
return character ? [character.mode] : theme === 'sakura' ? ['light'] : ['light', 'dark']; return theme.startsWith('custom:') ? [customThemeMode(customThemes().find(item => `custom:${item.id}` === theme)?.colors)] : character ? [character.mode] : theme === 'sakura' ? ['light'] : ['light', 'dark'];
} }
export type ThemeName = typeof THEMES[number] | `custom:${string}`; export type ThemeName = typeof THEMES[number] | `custom:${string}`;
export const BACKGROUND_POSITIONS = ['center', 'top left', 'top', 'top right', 'left', 'right', 'bottom left', 'bottom', 'bottom right'] as const; export const BACKGROUND_POSITIONS = ['center', 'top left', 'top', 'top right', 'left', 'right', 'bottom left', 'bottom', 'bottom right'] as const;
export const BACKGROUND_SIZES = ['cover', 'contain', 'auto'] as const; export const BACKGROUND_SIZES = ['cover', 'contain', 'auto'] as const;
export type Appearance = { theme: ThemeName; mode: 'light' | 'dark'; newTabBackground?: { image?: string; imageId?: string; overlay?: number; position?: typeof BACKGROUND_POSITIONS[number]; size?: typeof BACKGROUND_SIZES[number] } }; export type Appearance = { transparency?: { enabled: boolean; amount: number }; theme: ThemeName; mode: 'light' | 'dark'; newTabBackground?: { image?: string; imageId?: string; overlay?: number; position?: typeof BACKGROUND_POSITIONS[number]; size?: typeof BACKGROUND_SIZES[number] } };
export const DEFAULT_APPEARANCE: Appearance = { theme: 'default', mode: 'dark' }; export const DEFAULT_APPEARANCE: Appearance = { theme: 'default', mode: 'dark' };
export function normalizeAppearance(value: { theme?: unknown; mode?: unknown; newTabBackground?: unknown } | null): Appearance { export function normalizeAppearance(value: { theme?: unknown; mode?: unknown; newTabBackground?: unknown; transparency?: unknown } | null): Appearance {
const savedTheme = typeof value?.theme === 'string' && Object.hasOwn(LEGACY_THEME_IDS, value.theme) ? LEGACY_THEME_IDS[value.theme] : value?.theme; const savedTheme = typeof value?.theme === 'string' && Object.hasOwn(LEGACY_THEME_IDS, value.theme) ? LEGACY_THEME_IDS[value.theme] : value?.theme;
const theme: ThemeName = typeof savedTheme === 'string' && (/^custom:[a-z][a-z0-9-]{0,63}$/.test(savedTheme) || (THEMES as readonly string[]).includes(savedTheme)) ? savedTheme as ThemeName : 'default'; const theme: ThemeName = typeof savedTheme === 'string' && (/^custom:[a-z][a-z0-9-]{0,63}$/.test(savedTheme) || (THEMES as readonly string[]).includes(savedTheme)) ? savedTheme as ThemeName : 'default';
const result: Appearance = { theme, mode: characterTheme(theme)?.mode ?? (theme === 'sakura' || value?.mode === 'light' ? 'light' : 'dark') }; const selectedCustom = theme.startsWith('custom:') ? customThemes(value?.mode === 'light' ? 'light' : 'dark').find(item => `custom:${item.id}` === theme) : undefined;
const result: Appearance = { theme, mode: selectedCustom ? customThemeMode(selectedCustom.colors) : characterTheme(theme)?.mode ?? (theme === 'sakura' || value?.mode === 'light' ? 'light' : 'dark') };
if (value?.transparency && typeof value.transparency === 'object') {
const source = value.transparency as { enabled?: unknown; amount?: unknown };
result.transparency = { enabled: source.enabled !== false, amount: typeof source.amount === 'number' && Number.isFinite(source.amount) ? Math.max(0, Math.min(100, Math.round(source.amount))) : 18 };
}
const background = value?.newTabBackground; const background = value?.newTabBackground;
if (background && typeof background === 'object') { if (background && typeof background === 'object') {
const source = background as { image?: unknown; imageId?: unknown; overlay?: unknown; position?: unknown; size?: unknown }; const source = background as { image?: unknown; imageId?: unknown; overlay?: unknown; position?: unknown; size?: unknown };
@@ -61,23 +66,56 @@ function builtinPalette(theme: ThemeName) {
if (character) return { light: character.surfaces, dark: character.surfaces }; if (character) return { light: character.surfaces, dark: character.surfaces };
return palettes[theme === 'claude' ? 'claude' : 'default']; return palettes[theme === 'claude' ? 'claude' : 'default'];
} }
export function exportAppearanceTheme(theme: ThemeName): CustomTheme { export function customThemeMode(colors?: ThemeColors): 'light' | 'dark' {
const custom = customThemes().find(item => `custom:${item.id}` === theme); const hex = colors?.bg?.slice(1) ?? '141414';
if (custom) return custom; const full = hex.length <= 4 ? [...hex.slice(0, 3)].map(value => value + value).join('') : hex.slice(0, 6);
const palette = builtinPalette(theme); const rgb = [0, 2, 4].map(index => parseInt(full.slice(index, index + 2), 16) / 255)
const syntax = characterSyntax(theme); .map(value => value <= .04045 ? value / 12.92 : ((value + .055) / 1.055) ** 2.4);
const extra = characterTheme(theme) ? { ...syntax, 'accent-2': characterTheme(theme)!.secondary } : {}; return rgb[0] * .2126 + rgb[1] * .7152 + rgb[2] * .0722 > .179 ? 'light' : 'dark';
return { schema: 1, id: 'my-theme', name: 'My theme', }
light: { ...Object.fromEntries(keys.map((key, index) => [key, palette.light[index]])), ...extra }, export function exportAppearanceTheme(theme: ThemeName, mode: 'light' | 'dark' = 'dark'): CustomTheme {
dark: { ...Object.fromEntries(keys.map((key, index) => [key, palette.dark[index]])), ...extra } }; const custom = customThemes(mode).find(item => `custom:${item.id}` === theme);
if (custom) mode = customThemeMode(custom.colors);
mode = characterTheme(theme)?.mode ?? (theme === 'sakura' ? 'light' : mode);
const palette = builtinPalette(theme)[mode];
const colors: ThemeColors = Object.fromEntries(keys.map((key, index) => [key, palette[index]]));
colors['accent-2'] = characterTheme(theme)?.secondary ?? (theme === 'claude' ? '#6a9bcc' : theme === 'sakura' ? '#607fa9' : colors.accent);
const semantic = mode === 'light' ? ['#b42323', '#8a5700', '#806600', '#287b29', '#7740a5'] : ['#f44747', '#d68a00', '#cca700', '#89d185', '#c792ea'];
if (theme === 'claude') { semantic[3] = '#788c5d'; semantic[4] = '#6a9bcc'; }
if (theme === 'sakura') { semantic[3] = '#618c71'; semantic[4] = '#cb6b91'; }
(['error', 'warn-hot', 'warn', 'ok', 'special'] as const).forEach((key, index) => colors[key] = semantic[index]);
const syntax = theme === 'sakura' ? ['#cb6b91', '#98556c', '#618c71', '#69a2bd', '#607fa9', '#687788'] : [colors.special, colors.accent, colors.text, colors['accent-2'], colors['accent-2'], colors['text-dim']];
(['parameter', 'keyword', 'local', 'static', 'instance', 'global'] as const).forEach((key, index) => colors[`syntax-${key}`] = syntax[index]);
Object.assign(colors, { 'syntax-string': colors.ok, 'syntax-number': colors.special, 'syntax-comment': colors['text-dim'], 'syntax-type': colors['accent-2'], 'syntax-function': colors['accent-2'] }, characterSyntax(theme));
return { schema: 2, id: custom?.id ?? 'my-theme', name: custom?.name ?? 'My theme', colors: { ...colors, ...custom?.colors }, fonts: { ...themeFonts(theme), ...custom?.fonts } };
}
export function themeFonts(theme: ThemeName): Required<ThemeFonts> {
const ui = '"Segoe UI Variable Text", "Segoe UI", ui-sans-serif, system-ui, sans-serif';
const prose = '"Segoe UI Variable Display", "Segoe UI", "Helvetica Neue", ui-sans-serif, system-ui, sans-serif';
const mono = '"Cascadia Mono", "Cascadia Code", "JetBrains Mono", "Fira Code", Consolas, ui-monospace, monospace';
const fonts = { ui, prose, heading: prose, mono };
if (theme === 'claude') return { ...fonts, ui: '"Lora", Georgia, serif', prose: '"Lora", Georgia, serif', heading: '"Poppins", Arial, sans-serif' };
if (theme === 'harvest-moon') return { ...fonts, ui: 'Candara, "Trebuchet MS", "Segoe UI", sans-serif', prose: 'Constantia, Georgia, "Times New Roman", serif', heading: 'Constantia, Georgia, "Times New Roman", serif' };
if (theme === 'crimson-pilot') return { ...fonts, ui: 'Bahnschrift, "Trebuchet MS", Arial, sans-serif', prose: '"Segoe UI", "Helvetica Neue", Arial, sans-serif', heading: 'Bahnschrift, "Trebuchet MS", Arial, sans-serif' };
if (theme === 'silver-serpent') return { ...fonts, ui: 'Corbel, "Segoe UI", "Helvetica Neue", Arial, sans-serif', prose: '"Palatino Linotype", "Book Antiqua", Palatino, Georgia, serif', heading: '"Palatino Linotype", "Book Antiqua", Palatino, Georgia, serif' };
return fonts;
}
export function applyTransparency(value: Appearance['transparency'], root: HTMLElement) {
const supplied = value?.amount ?? 18;
const amount = value?.enabled === false ? 0 : Number.isFinite(supplied) ? Math.max(0, Math.min(100, supplied)) : 18;
root.dataset.transparency = amount ? 'on' : 'off';
root.style.setProperty('--rs-surface-opacity', `${100 - amount}%`);
root.style.setProperty('--rs-editor-surface-opacity', `${100 - amount * 10 / 18}%`);
root.style.setProperty('--rs-hover-surface-opacity', `${100 - amount * 8 / 18}%`);
root.style.setProperty('--rs-transparent-plugin-bg', amount ? 'transparent' : 'var(--rs-bg)');
} }
const backgroundUrls = new WeakMap<HTMLElement, { image: string; url: string }>(); const backgroundUrls = new WeakMap<HTMLElement, { image: string; url: string }>();
const backgroundRequests = new WeakMap<HTMLElement, string | undefined>(); const backgroundRequests = new WeakMap<HTMLElement, string | undefined>();
function applyBackgroundSurfaces(root: HTMLElement, hasImage: boolean) { function applyBackgroundSurfaces(root: HTMLElement, hasImage: boolean) {
root.style.setProperty('--rs-workarea-sidebar-bg', hasImage ? 'var(--rs-image-sidebar-bg)' : 'var(--rs-bg-elevated)'); root.style.setProperty('--rs-workarea-sidebar-bg', hasImage ? 'var(--rs-image-sidebar-bg)' : 'var(--rs-bg-elevated)');
root.style.setProperty('--rs-workarea-editor-bg', hasImage ? 'var(--rs-image-editor-bg)' : 'var(--rs-bg)'); root.style.setProperty('--rs-workarea-editor-bg', hasImage ? 'var(--rs-image-editor-bg)' : 'var(--rs-bg)');
root.style.setProperty('--rs-workarea-surface-opacity', hasImage ? '82%' : '100%'); root.style.setProperty('--rs-workarea-surface-opacity', hasImage ? 'var(--rs-surface-opacity)' : '100%');
root.style.setProperty('--rs-workarea-plugin-bg', hasImage ? 'transparent' : 'var(--rs-bg)'); root.style.setProperty('--rs-workarea-plugin-bg', hasImage ? 'var(--rs-transparent-plugin-bg)' : 'var(--rs-bg)');
} }
async function applySavedBackground(root: HTMLElement, background?: Appearance['newTabBackground']) { async function applySavedBackground(root: HTMLElement, background?: Appearance['newTabBackground']) {
const id = background?.imageId; const id = background?.imageId;
@@ -120,7 +158,11 @@ function applyBackgroundImage(root: HTMLElement, image?: string) {
if (previous) URL.revokeObjectURL(previous.url); if (previous) URL.revokeObjectURL(previous.url);
} }
export function applyAppearance(value: Appearance, root = document.documentElement) { export function applyAppearance(value: Appearance, root = document.documentElement) {
const { theme, mode, newTabBackground } = normalizeAppearance(value); const normalized = normalizeAppearance(value);
const { theme, newTabBackground } = normalized;
const custom = theme.startsWith('custom:') ? customThemes(normalized.mode).find(item => item.id === theme.slice(7)) : undefined;
const mode = custom ? customThemeMode(custom.colors) : normalized.mode;
applyTransparency(normalized.transparency, root);
root.style.setProperty('--rs-new-tab-bg', 'var(--rs-bg)'); root.style.setProperty('--rs-new-tab-bg', 'var(--rs-bg)');
const overlay = newTabBackground?.overlay ?? 0; const overlay = newTabBackground?.overlay ?? 0;
const shade = overlay < 0 ? '255,255,255' : '0,0,0'; const shade = overlay < 0 ? '255,255,255' : '0,0,0';
@@ -132,6 +174,8 @@ export function applyAppearance(value: Appearance, root = document.documentEleme
root.dataset.theme = mode; root.dataset.theme = mode;
root.dataset.palette = theme; root.dataset.palette = theme;
root.style.colorScheme = mode; root.style.colorScheme = mode;
const fonts = { ...themeFonts(theme), ...custom?.fonts };
FONT_ROLES.forEach(role => root.style.setProperty(`--rs-font-${role}`, fonts[role]));
const palette = builtinPalette(theme)[mode]; const palette = builtinPalette(theme)[mode];
keys.forEach((key, index) => root.style.setProperty(`--rs-${key}`, palette[index])); keys.forEach((key, index) => root.style.setProperty(`--rs-${key}`, palette[index]));
root.style.setProperty('--rs-accent-2', characterTheme(theme)?.secondary ?? (theme === 'claude' ? '#6a9bcc' : theme === 'sakura' ? '#607fa9' : 'var(--rs-accent)')); root.style.setProperty('--rs-accent-2', characterTheme(theme)?.secondary ?? (theme === 'claude' ? '#6a9bcc' : theme === 'sakura' ? '#607fa9' : 'var(--rs-accent)'));
@@ -149,8 +193,7 @@ export function applyAppearance(value: Appearance, root = document.documentEleme
['parameter', 'keyword', 'local', 'static', 'instance', 'global'].forEach((key, index) => root.style.setProperty(`--rs-syntax-${key}`, syntax[index])); ['parameter', 'keyword', 'local', 'static', 'instance', 'global'].forEach((key, index) => root.style.setProperty(`--rs-syntax-${key}`, syntax[index]));
for (const [key, color] of Object.entries(characterSyntax(theme))) root.style.setProperty(`--rs-${key}`, color); for (const [key, color] of Object.entries(characterSyntax(theme))) root.style.setProperty(`--rs-${key}`, color);
root.style.setProperty('--rs-danger', 'var(--rs-error)'); root.style.setProperty('--rs-danger', 'var(--rs-error)');
const custom = theme.startsWith('custom:') ? customThemes().find(item => item.id === theme.slice(7)) : undefined; if (custom) for (const [key, color] of Object.entries(custom.colors)) root.style.setProperty(`--rs-${key}`, color);
if (custom) for (const [key, color] of Object.entries(custom[mode])) root.style.setProperty(`--rs-${key}`, color);
window.dispatchEvent(new CustomEvent('runestone-theme-changed')); window.dispatchEvent(new CustomEvent('runestone-theme-changed'));
} }
export function saveAppearance(value: Appearance) { export function saveAppearance(value: Appearance) {
+53 -8
View File
@@ -1,13 +1,16 @@
export const CUSTOM_THEMES_KEY = "runestone.custom-themes"; export const CUSTOM_THEMES_KEY = "runestone.custom-themes";
export const COLOR_TOKENS = ["bg", "bg-elevated", "bg-active", "border", "text", "text-dim", "text-strong", "accent", "accent-2", "selection", "error", "warn", "warn-hot", "ok", "special", "syntax-parameter", "syntax-keyword", "syntax-local", "syntax-static", "syntax-instance", "syntax-global", "syntax-string", "syntax-number", "syntax-comment", "syntax-type", "syntax-function"] as const; export const COLOR_TOKENS = ["bg", "bg-elevated", "bg-active", "border", "text", "text-dim", "text-strong", "accent", "accent-2", "selection", "error", "warn", "warn-hot", "ok", "special", "syntax-parameter", "syntax-keyword", "syntax-local", "syntax-static", "syntax-instance", "syntax-global", "syntax-string", "syntax-number", "syntax-comment", "syntax-type", "syntax-function"] as const;
export type ThemeColors = Partial<Record<typeof COLOR_TOKENS[number], string>>; export type ThemeColors = Partial<Record<typeof COLOR_TOKENS[number], string>>;
export type CustomTheme = { schema: 1; id: string; name: string; light: ThemeColors; dark: ThemeColors }; export const FONT_ROLES = ['ui', 'prose', 'heading', 'mono'] as const;
export type ThemeFonts = Partial<Record<typeof FONT_ROLES[number], string>>;
export type CustomTheme = { schema: 2; id: string; name: string; colors: ThemeColors; fonts?: ThemeFonts };
export type LegacyCustomTheme = { schema: 1; id: string; name: string; light: ThemeColors; dark: ThemeColors };
export function parseCustomTheme(input: unknown): CustomTheme { export function parseCustomTheme(input: unknown, legacyMode: "light" | "dark" = "dark"): CustomTheme {
if (!input || typeof input !== "object") throw new Error("Choose a RuneStone theme JSON file."); if (!input || typeof input !== "object") throw new Error("Choose a RuneStone theme JSON file.");
const value = input as Record<string, unknown>; const value = input as Record<string, unknown>;
if (value.schema !== 1 || typeof value.id !== "string" || !/^[a-z][a-z0-9-]{0,63}$/.test(value.id) if ((value.schema !== 1 && value.schema !== 2) || typeof value.id !== "string" || !/^[a-z][a-z0-9-]{0,63}$/.test(value.id)
|| typeof value.name !== "string" || !value.name.trim() || value.name.length > 80) throw new Error("The theme needs schema 1, an ID, and a name."); || typeof value.name !== "string" || !value.name.trim() || value.name.length > 80) throw new Error("The theme needs schema 2, an ID, and a name.");
const colors = (mode: string): ThemeColors => { const colors = (mode: string): ThemeColors => {
const source = value[mode]; const source = value[mode];
if (!source || typeof source !== "object" || Array.isArray(source)) throw new Error(`The theme needs ${mode} colors.`); if (!source || typeof source !== "object" || Array.isArray(source)) throw new Error(`The theme needs ${mode} colors.`);
@@ -20,13 +23,55 @@ export function parseCustomTheme(input: unknown): CustomTheme {
if (!result.bg || !result.text || !result.accent) throw new Error(`The ${mode} palette needs bg, text, and accent.`); if (!result.bg || !result.text || !result.accent) throw new Error(`The ${mode} palette needs bg, text, and accent.`);
return result; return result;
}; };
return { schema: 1, id: value.id, name: value.name.trim(), light: colors("light"), dark: colors("dark") }; if (value.schema === 1) { colors("light"); colors("dark"); }
let fonts: ThemeFonts | undefined;
if (value.fonts !== undefined) {
if (!value.fonts || typeof value.fonts !== 'object' || Array.isArray(value.fonts)) throw new Error('Use an object for theme fonts.');
fonts = {};
for (const [role, stack] of Object.entries(value.fonts)) {
if (!(FONT_ROLES as readonly string[]).includes(role)) throw new Error(`Unknown theme font: ${role}`);
if (typeof stack !== 'string' || stack.length > 512 || !/^[\p{L}\p{N} _,'"-]+$/u.test(stack) || !stack.trim()
|| stack.split(',').some(family => !/^(?:"[^"\n]+"|'[^'\n]+'|[\p{L}\p{N}_ -]+)$/u.test(family.trim()))) throw new Error(`Use a font family stack for ${role}.`);
fonts[role as keyof ThemeFonts] = stack.trim();
}
}
return { schema: 2, id: value.id, name: value.name.trim(), colors: colors(value.schema === 1 ? legacyMode : "colors"), ...(fonts ? { fonts } : {}) };
} }
export function customThemes(): CustomTheme[] { const pendingLegacy = new Map<string, CustomTheme[]>();
export function customThemes(legacyMode?: "light" | "dark"): CustomTheme[] {
try { try {
const stored = JSON.parse(localStorage.getItem(CUSTOM_THEMES_KEY) || "[]"); const raw = localStorage.getItem(CUSTOM_THEMES_KEY) || "[]";
return Array.isArray(stored) ? stored.flatMap(value => { try { return [parseCustomTheme(value)]; } catch { return []; } }) : []; const pending = pendingLegacy.get(raw);
if (pending) return pending.map(theme => ({ ...theme, colors: { ...theme.colors } }));
const stored = JSON.parse(raw);
if (!Array.isArray(stored)) return [];
if (!legacyMode) {
try { legacyMode = JSON.parse(localStorage.getItem('runestone.appearance') || 'null')?.mode === 'light' ? 'light' : 'dark'; }
catch { legacyMode = 'dark'; }
}
const parsed = stored.flatMap(value => { try { return [parseCustomTheme(value, legacyMode)]; } catch { return []; } });
if (stored.some(value => value?.schema === 1)) {
// Retain both original palettes before converting the saved selection to one palette.
try {
const backupKey = `${CUSTOM_THEMES_KEY}.legacy`;
const backup = JSON.parse(localStorage.getItem(backupKey) || '[]');
if (!Array.isArray(backup)) throw new Error('Invalid legacy backup');
const originals = backup;
for (const value of stored.filter(value => value?.schema === 1)) {
if (!originals.some(item => JSON.stringify(item) === JSON.stringify(value))) originals.push(value);
}
localStorage.setItem(backupKey, JSON.stringify(originals));
localStorage.setItem(CUSTOM_THEMES_KEY, JSON.stringify(stored.map(value => {
try { return parseCustomTheme(value, legacyMode); } catch { return value; }
})));
} catch {
// Storage failures must not hide readable themes or change their chosen palette.
pendingLegacy.set(raw, parsed);
}
}
return parsed;
} catch { return []; } } catch { return []; }
} }
+11 -7
View File
@@ -6,11 +6,15 @@
--rs-tooltip-shadow: 0 4px 16px #0005; --rs-tooltip-shadow: 0 4px 16px #0005;
--rs-tooltip-font-size: 12px; --rs-tooltip-font-size: 12px;
--rs-control-radius: 5px; --rs-control-radius: 5px;
--rs-image-control-bg: color-mix(in srgb, var(--rs-bg) 82%, transparent); --rs-surface-opacity: 82%;
--rs-image-control-hover-bg: color-mix(in srgb, var(--rs-bg-active) 92%, transparent); --rs-editor-surface-opacity: 90%;
--rs-image-sidebar-bg: color-mix(in srgb, var(--rs-bg-elevated) 82%, transparent); --rs-hover-surface-opacity: 92%;
--rs-image-editor-bg: color-mix(in srgb, var(--rs-bg) 90%, transparent); --rs-transparent-plugin-bg: transparent;
--rs-code-block-bg: color-mix(in srgb, var(--rs-bg-elevated) 82%, transparent); --rs-image-control-bg: color-mix(in srgb, var(--rs-bg) var(--rs-surface-opacity), transparent);
--rs-image-control-hover-bg: color-mix(in srgb, var(--rs-bg-active) var(--rs-hover-surface-opacity), transparent);
--rs-image-sidebar-bg: color-mix(in srgb, var(--rs-bg-elevated) var(--rs-surface-opacity), transparent);
--rs-image-editor-bg: color-mix(in srgb, var(--rs-bg) var(--rs-editor-surface-opacity), transparent);
--rs-code-block-bg: color-mix(in srgb, var(--rs-bg-elevated) var(--rs-surface-opacity), transparent);
--rs-workarea-sidebar-bg: var(--rs-bg-elevated); --rs-workarea-sidebar-bg: var(--rs-bg-elevated);
--rs-workarea-editor-bg: var(--rs-bg); --rs-workarea-editor-bg: var(--rs-bg);
--rs-workarea-surface-opacity: 100%; --rs-workarea-surface-opacity: 100%;
@@ -30,8 +34,8 @@
--rs-menu-icon-gap: 8px; --rs-menu-icon-gap: 8px;
--rs-menu-font-size: 13px; --rs-menu-font-size: 13px;
--rs-menu-border: transparent; --rs-menu-border: transparent;
--rs-menu-bg: color-mix(in srgb, var(--rs-bg-elevated) 82%, transparent); --rs-menu-bg: color-mix(in srgb, var(--rs-bg-elevated) var(--rs-surface-opacity), transparent);
--rs-menu-active-bg: color-mix(in srgb, var(--rs-bg-active) 82%, transparent); --rs-menu-active-bg: color-mix(in srgb, var(--rs-bg-active) var(--rs-surface-opacity), transparent);
--rs-menu-shadow: 0 8px 30px #0006; --rs-menu-shadow: 0 8px 30px #0006;
--rs-item-selection-radius: var(--rs-control-radius); --rs-item-selection-radius: var(--rs-control-radius);
--rs-item-selection-bg: color-mix(in srgb, var(--rs-accent) 20%, transparent); --rs-item-selection-bg: color-mix(in srgb, var(--rs-accent) 20%, transparent);
+5 -4
View File
@@ -1,4 +1,5 @@
<script lang="ts"> <script lang="ts">
import { t } from "$lib/i18n";
import { onMount } from "svelte"; import { onMount } from "svelte";
import { getCurrentWindow } from "@tauri-apps/api/window"; import { getCurrentWindow } from "@tauri-apps/api/window";
import IconButton from "./IconButton.svelte"; import IconButton from "./IconButton.svelte";
@@ -32,12 +33,12 @@
}); });
</script> </script>
<div class="window-controls" role="group" aria-label="Window controls"> <div class="window-controls" role="group" aria-label={$t("Window controls")}>
<IconButton icon="minimize" label="Minimize window" onclick={() => void run("minimize")} /> <IconButton icon="minimize" label={$t("Minimize window")} onclick={() => void run("minimize")} />
<IconButton icon={maximized ? "window-restore" : "window-maximize"} <IconButton icon={maximized ? "window-restore" : "window-maximize"}
label={maximized ? "Restore window" : "Maximize window"} onclick={() => void run("toggleMaximize")} /> label={maximized ? $t("Restore window") : $t("Maximize window")} onclick={() => void run("toggleMaximize")} />
<div class="window-close"> <div class="window-close">
<IconButton icon="close" label="Close window" onclick={() => void run("close")} /> <IconButton icon="close" label={$t("Close window")} onclick={() => void run("close")} />
</div> </div>
</div> </div>
+7
View File
@@ -1,5 +1,12 @@
// Stroke icons share the same 24px grid and weight as IconButton. // Stroke icons share the same 24px grid and weight as IconButton.
export const actionIcons = { export const actionIcons = {
play: '<path d="m7 4 14 8-14 8Z"/>',
pause: '<path d="M7 4v16M17 4v16"/>',
'skip-forward': '<path d="m4 4 12 8-12 8ZM20 4v16"/>',
eye: '<path d="M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7S2 12 2 12Z"/><circle cx="12" cy="12" r="3"/>',
'eye-off': '<path d="m3 3 18 18M10.6 5.1 12 5c6.5 0 10 7 10 7a18 18 0 0 1-3.1 3.8M6.2 6.2A21 21 0 0 0 2 12s3.5 7 10 7a13 13 0 0 0 5.8-1.4M9.9 9.9a3 3 0 0 0 4.2 4.2"/>',
image: '<rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="8" cy="8" r="1.5"/><path d="m21 15-5-5L5 21"/>',
settings: '<path d="M4 7h16M4 17h16"/><circle cx="9" cy="7" r="3"/><circle cx="15" cy="17" r="3"/>',
archive: '<path d="M4 8v12h16V8M3 3h18v5H3zM9 12h6"/>', archive: '<path d="M4 8v12h16V8M3 3h18v5H3zM9 12h6"/>',
save: '<path d="M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2z"/><path d="M17 21v-8H7v8M7 3v5h8"/>', save: '<path d="M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2z"/><path d="M17 21v-8H7v8M7 3v5h8"/>',
refresh: '<path d="M20 7v5h-5M4 17v-5h5M6 7a7 7 0 0 1 12-1l2 3M4 15l2 3a7 7 0 0 0 12-1"/>', refresh: '<path d="M20 7v5h-5M4 17v-5h5M6 7a7 7 0 0 1 12-1l2 3M4 15l2 3a7 7 0 0 0 12-1"/>',
+1 -1
View File
@@ -46,5 +46,5 @@
.rs-menu > button > .action-icon, .rs-picker-icon { width: var(--rs-menu-icon-size); height: var(--rs-menu-icon-size); flex: 0 0 var(--rs-menu-icon-size); } .rs-menu > button > .action-icon, .rs-picker-icon { width: var(--rs-menu-icon-size); height: var(--rs-menu-icon-size); flex: 0 0 var(--rs-menu-icon-size); }
.rs-picker-hint { display: block; color: var(--rs-text-dim); font-size: var(--rs-settings-description-size); } .rs-picker-hint { display: block; color: var(--rs-text-dim); font-size: var(--rs-settings-description-size); }
.rs-picker-icon > svg { width: 100%; height: 100%; } .rs-picker-icon > svg { width: 100%; height: 100%; }
.rs-menu > button > .action-label { flex: 1; min-width: 0; overflow-wrap: anywhere; } .rs-menu > button > .action-label { flex: 1; min-width: 0; overflow: visible; text-overflow: clip; white-space: normal; overflow-wrap: anywhere; }
.rs-menu > button > .action-chevron { width: 13px; height: 13px; flex: 0 0 13px; } .rs-menu > button > .action-chevron { width: 13px; height: 13px; flex: 0 0 13px; }
+6 -1
View File
@@ -2,8 +2,9 @@ import { invoke } from "@tauri-apps/api/core";
import { listen, type UnlistenFn } from "@tauri-apps/api/event"; import { listen, type UnlistenFn } from "@tauri-apps/api/event";
import { open as openDialog } from "@tauri-apps/plugin-dialog"; import { open as openDialog } from "@tauri-apps/plugin-dialog";
import type { TreeEntry, WorkspaceEvent, WorkspaceInfo } from "./types"; import type { TreeEntry, WorkspaceEvent, WorkspaceInfo } from "./types";
import { tr } from "../i18n/index.ts";
export async function pickWorkspaceFolder(title = "Open workspace"): Promise<string | null> { export async function pickWorkspaceFolder(title = tr("Open workspace")): Promise<string | null> {
const selected = await openDialog({ const selected = await openDialog({
directory: true, directory: true,
multiple: false, multiple: false,
@@ -31,6 +32,10 @@ export function workspaceRecent(): Promise<string[]> {
return invoke("workspace_recent"); return invoke("workspace_recent");
} }
export function workspaceForget(path: string): Promise<string[]> {
return invoke("workspace_forget", { path });
}
export function workspaceNew(parent: string, name: string): Promise<void> { export function workspaceNew(parent: string, name: string): Promise<void> {
return invoke("workspace_new", { parent, name }); return invoke("workspace_new", { parent, name });
} }