Release RuneStone 0.1.4 with installable plugins and settings
This commit is contained in:
@@ -12,3 +12,5 @@ src-tauri/target
|
|||||||
src-tauri/gen
|
src-tauri/gen
|
||||||
.idea
|
.idea
|
||||||
/.audit
|
/.audit
|
||||||
|
|
||||||
|
/plugin-packages/
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
A desktop workspace for writing and code.
|
A desktop workspace for writing and code.
|
||||||
|
|
||||||
RuneStone brings Markdown notes, scripts, images, and a terminal into one window.
|
RuneStone brings Markdown notes, scripts, images, and optional plugins into one window.
|
||||||
Open a folder and work with the files already inside it.
|
Open a folder and work with the files already inside it.
|
||||||
|
|
||||||
## Why RuneStone?
|
## Why RuneStone?
|
||||||
@@ -18,15 +18,15 @@ and use your own tools to manage them. Workspace settings live separately in `.r
|
|||||||
- **Markdown writing:** Live formatting, source editing, split view, and read view.
|
- **Markdown writing:** Live formatting, source editing, split view, and read view.
|
||||||
- **Code editing:** A source editor for scripts, with file navigation and workspace search.
|
- **Code editing:** A source editor for scripts, with file navigation and workspace search.
|
||||||
- **Images and diagrams:** Image insertion and previews, plus Mermaid diagrams.
|
- **Images and diagrams:** Image insertion and previews, plus Mermaid diagrams.
|
||||||
- **Tables:** Editable Markdown tables with formulas for calculations.
|
- **Tables:** Editable Markdown tables with optional calculations through the Table formulas plugin.
|
||||||
- **Terminals:** Multiple shell sessions, split panes, and commands beside your documents.
|
- **Terminal plugin:** Shell sessions, split panes, and commands beside your documents.
|
||||||
- **File handling:** Autosave every five seconds and controls to resolve changes from other tools.
|
- **File handling:** Adjustable auto-save and controls to resolve changes from other tools.
|
||||||
|
|
||||||
## Project status
|
## Project status
|
||||||
|
|
||||||
RuneStone is under development, with Windows as its first target.
|
RuneStone is under development, with Windows as its first target.
|
||||||
**Plugin support is planned and is not available yet.** Git controls, language servers,
|
Local [plugin packages](docs/plugins.md) are available. Git controls, language servers,
|
||||||
session restoration, and crash recovery are also pending.
|
session restoration, and crash recovery remain planned.
|
||||||
|
|
||||||
The [roadmap](docs/roadmap.md) shows the proposed direction, goals, and milestones.
|
The [roadmap](docs/roadmap.md) shows the proposed direction, goals, and milestones.
|
||||||
The [user guide](docs/user-guide.md) covers current features and limitations.
|
The [user guide](docs/user-guide.md) covers current features and limitations.
|
||||||
@@ -47,7 +47,10 @@ If Microsoft Edge WebView2 is missing, setup downloads and installs it, which ne
|
|||||||
Press Ctrl+N to create a note or script, Ctrl+P to find a file, and Ctrl+S to save.
|
Press Ctrl+N to create a note or script, Ctrl+P to find a file, and Ctrl+S to save.
|
||||||
|
|
||||||
See the [installation guide](docs/installation.md) for setup help, updates, and removal.
|
See the [installation guide](docs/installation.md) for setup help, updates, and removal.
|
||||||
To run from source, see the [development guide](docs/development.md#run-from-source).
|
To run from source, see the [Developer README](docs/development.md#run-from-source).
|
||||||
|
For feature tests, use `pnpm tauri dev` after setup.
|
||||||
|
It reloads interface changes without a full rebuild.
|
||||||
|
See [the development workflow](docs/development.md#test-changes-without-a-full-rebuild) for commands and rebuild limits.
|
||||||
|
|
||||||
## Documentation
|
## Documentation
|
||||||
|
|
||||||
@@ -55,7 +58,7 @@ Documentation lives in this repository:
|
|||||||
|
|
||||||
- [User guide](docs/user-guide.md): Editing, images, tables, terminals, and shortcuts.
|
- [User guide](docs/user-guide.md): Editing, images, tables, terminals, and shortcuts.
|
||||||
- [Installation guide](docs/installation.md): Windows setup and troubleshooting.
|
- [Installation guide](docs/installation.md): Windows setup and troubleshooting.
|
||||||
- [Development guide](docs/development.md): Build tools, source setup, and tests.
|
- [Developer README](docs/development.md): Source setup, live updates, rebuild limits, and tests.
|
||||||
- [Release guide](docs/releases.md): Build and package the Windows installer.
|
- [Release guide](docs/releases.md): Build and package the Windows installer.
|
||||||
- [Roadmap](docs/roadmap.md): Product direction, goals, and milestones.
|
- [Roadmap](docs/roadmap.md): Product direction, goals, and milestones.
|
||||||
|
|
||||||
|
|||||||
+112
-5
@@ -1,7 +1,61 @@
|
|||||||
# Development guide
|
# Developer README
|
||||||
|
|
||||||
[Back to RuneStone](../README.md)
|
[Back to RuneStone](../README.md)
|
||||||
|
|
||||||
|
## Test changes without a full rebuild
|
||||||
|
|
||||||
|
From the repository folder, run:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
pnpm tauri dev
|
||||||
|
```
|
||||||
|
|
||||||
|
For a fresh checkout, complete [Run from source](#run-from-source) first.
|
||||||
|
|
||||||
|
This command starts Vite and opens RuneStone in a native desktop window.
|
||||||
|
Keep the terminal open while you edit the source.
|
||||||
|
Svelte, TypeScript, and CSS changes update through hot module replacement (HMR), or a page reload when required.
|
||||||
|
Frontend changes do not need a Rust rebuild or an installer.
|
||||||
|
|
||||||
|
The first launch compiles the Rust app and its dependencies.
|
||||||
|
Later launches reuse Cargo's cached output.
|
||||||
|
Rust changes still need compilation, but Cargo reuses unchanged build output.
|
||||||
|
Tauri then restarts the app automatically.
|
||||||
|
See [Tauri development](https://v2.tauri.app/develop/) and [Vite HMR](https://vite.dev/guide/features.html#hot-module-replacement) for details.
|
||||||
|
|
||||||
|
### Daily workflow
|
||||||
|
|
||||||
|
1. Start `pnpm tauri dev` in a terminal at the repository root.
|
||||||
|
2. Open a test workspace with the folder button in the development window.
|
||||||
|
3. Edit a source file in your code editor.
|
||||||
|
4. Save the source file, then test the change in the development window.
|
||||||
|
5. To stop the development session, press Ctrl+C in its terminal.
|
||||||
|
|
||||||
|
Use sample documents for feature tests. The desktop app reads and writes real files.
|
||||||
|
Save open documents before a change that reloads or restarts the app.
|
||||||
|
A reload can reset editor state, and a Rust restart ends terminal sessions.
|
||||||
|
|
||||||
|
`pnpm tauri dev` starts `pnpm dev` through `beforeDevCommand` in `src-tauri/tauri.conf.json`.
|
||||||
|
Do not start a separate `pnpm dev` process for this workflow.
|
||||||
|
The frontend uses port 1420, and Tauri loads `http://localhost:1420`.
|
||||||
|
|
||||||
|
### What needs a rebuild?
|
||||||
|
|
||||||
|
| Change or task | Action |
|
||||||
|
| --- | --- |
|
||||||
|
| Svelte, TypeScript, or CSS under `src/` | Save the source file. Vite updates the interface without a Rust rebuild. |
|
||||||
|
| Feature source under `plugins/` | Run `pnpm build:plugins`, then uninstall and install the changed package through Settings. |
|
||||||
|
| Rust code under `src-tauri/src/` | Save the source file. Tauri rebuilds the changed Rust code and restarts the app. |
|
||||||
|
| Rust dependencies or build settings | Allow Cargo to compile the affected dependencies. These changes can take longer. |
|
||||||
|
| JavaScript dependencies after a pull or branch change | Stop development, run `pnpm install --frozen-lockfile`, then start `pnpm tauri dev` again. |
|
||||||
|
| Tauri configuration, capabilities, or Vite configuration | Restart `pnpm tauri dev` to check the new settings. Native changes can require compilation. |
|
||||||
|
| Release or installer behavior | Use the [release guide](releases.md). Packaging requires a release build. |
|
||||||
|
|
||||||
|
Keep `src-tauri/target/` between sessions so Cargo can reuse its build cache.
|
||||||
|
Do not run `cargo clean` as part of normal feature tests.
|
||||||
|
An installed copy from the Start menu uses its packaged code and does not show source changes.
|
||||||
|
Use the window that `pnpm tauri dev` opens.
|
||||||
|
|
||||||
## Stack
|
## Stack
|
||||||
|
|
||||||
RuneStone uses Tauri 2 and Rust for the desktop host.
|
RuneStone uses Tauri 2 and Rust for the desktop host.
|
||||||
@@ -12,6 +66,7 @@ Windows is the first target. The older WriterHost component remains unused.
|
|||||||
See the setup steps below to install dependencies and run the desktop app.
|
See the setup steps below to install dependencies and run the desktop app.
|
||||||
See the [roadmap](roadmap.md) for goals and milestones. See the [product scope](product-scope.md) for capabilities and architecture constraints.
|
See the [roadmap](roadmap.md) for goals and milestones. See the [product scope](product-scope.md) for capabilities and architecture constraints.
|
||||||
Agent instructions and UI design rules live in [AGENTS.md](../AGENTS.md).
|
Agent instructions and UI design rules live in [AGENTS.md](../AGENTS.md).
|
||||||
|
See the [plugin guide](plugins.md) to build and install feature packages, use the API, and understand current plugin boundaries.
|
||||||
|
|
||||||
## Run from source
|
## Run from source
|
||||||
|
|
||||||
@@ -35,9 +90,25 @@ See the [release guide](releases.md) to build a Windows installer.
|
|||||||
|
|
||||||
## Checks
|
## Checks
|
||||||
|
|
||||||
Run these commands from the repository folder:
|
Run checks from the repository folder in a second terminal.
|
||||||
|
These commands do not require an installer.
|
||||||
|
|
||||||
|
For type errors while you edit:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
pnpm check:watch
|
||||||
|
```
|
||||||
|
|
||||||
|
For one test file:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
node --experimental-strip-types --test scripts/tableSelection.spec.ts
|
||||||
|
```
|
||||||
|
|
||||||
|
For the full set of checks:
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
|
pnpm build:plugins
|
||||||
pnpm check
|
pnpm check
|
||||||
pnpm test
|
pnpm test
|
||||||
pnpm build
|
pnpm build
|
||||||
@@ -45,7 +116,9 @@ cargo test --manifest-path src-tauri/Cargo.toml --lib --offline
|
|||||||
```
|
```
|
||||||
|
|
||||||
The offline Rust command requires cached dependencies. Omit `--offline` if Cargo needs to download them.
|
The offline Rust command requires cached dependencies. Omit `--offline` if Cargo needs to download them.
|
||||||
`pnpm build` builds the frontend. Use `pnpm tauri build` to build the desktop app.
|
`pnpm build` checks the production frontend build. It is not required after each source edit.
|
||||||
|
`pnpm preview` serves the last frontend build and does not watch source changes.
|
||||||
|
Use `pnpm tauri build` to build the release desktop app.
|
||||||
|
|
||||||
The Rust tests cover real terminal shells, working directories, Unicode output,
|
The Rust tests cover real terminal shells, working directories, Unicode output,
|
||||||
resizing, exit status, and session termination. Native terminal tests launch each
|
resizing, exit status, and session termination. Native terminal tests launch each
|
||||||
@@ -53,20 +126,54 @@ detected shell profile and check shell prompt integration.
|
|||||||
|
|
||||||
## Browser smoke tests
|
## Browser smoke tests
|
||||||
|
|
||||||
|
`pnpm dev` starts only the Vite server at `http://127.0.0.1:1420`.
|
||||||
|
A browser can show the interface, but real folder access, file writes, and terminals require the desktop host.
|
||||||
|
Use `pnpm tauri dev` for manual tests of those features.
|
||||||
|
|
||||||
|
Run `pnpm build:plugins` before tests that use Terminal or Table formulas.
|
||||||
|
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.
|
||||||
They do not replace native desktop tests.
|
They do not replace native desktop tests.
|
||||||
|
|
||||||
1. Install Playwright, or set `PLAYWRIGHT_MODULE` to a shared Playwright package.
|
1. Install Playwright, or set `PLAYWRIGHT_MODULE` to a shared Playwright package.
|
||||||
2. Start the frontend with `pnpm dev`.
|
2. Start the frontend with `pnpm dev`, or reuse the server from an active `pnpm tauri dev` session.
|
||||||
3. In a second terminal, run a smoke script, such as `node scripts/workbench.smoke.mjs`.
|
3. In a second terminal, run a smoke script, such as `node scripts/workbench.smoke.mjs`.
|
||||||
|
|
||||||
Set `CHROME_PATH` if you need to select an installed browser executable.
|
Playwright is not a dependency in `package.json`.
|
||||||
|
Set `PLAYWRIGHT_MODULE` to the absolute path of an existing Playwright package if you use a shared installation.
|
||||||
|
That package must have Chromium installed, or you must select an installed browser with `CHROME_PATH`.
|
||||||
|
|
||||||
|
For example, in PowerShell, replace these example paths with your local paths:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
$env:PLAYWRIGHT_MODULE = "C:\tools\browser-tests\node_modules\playwright"
|
||||||
|
$env:CHROME_PATH = "C:\Program Files\Google\Chrome\Application\chrome.exe"
|
||||||
|
node scripts/workbench.smoke.mjs
|
||||||
|
```
|
||||||
|
|
||||||
| Script | Coverage |
|
| Script | Coverage |
|
||||||
| --- | --- |
|
| --- | --- |
|
||||||
| `scripts/workbench.smoke.mjs` | The Svelte, Monaco, and xterm interface |
|
| `scripts/workbench.smoke.mjs` | The Svelte, Monaco, and xterm interface |
|
||||||
|
| `scripts/pluginInstall.smoke.mjs` | Package review, external commands and views, the uninstall confirmation, and cleanup |
|
||||||
|
| `scripts/plugins.smoke.mjs` | Plugin toggles, formula source preservation, terminal cleanup, and preferences across windows |
|
||||||
| `scripts/terminal.smoke.mjs` | Terminal groups, single-session layout, menus, profiles, history, tasks, settings, and editor actions |
|
| `scripts/terminal.smoke.mjs` | Terminal groups, single-session layout, menus, profiles, history, tasks, settings, and editor actions |
|
||||||
| `scripts/images.smoke.mjs` | Image drops, clipboard imports, source editing, zoom, undo, failed writes, and tab changes during imports |
|
| `scripts/images.smoke.mjs` | Image drops, clipboard imports, source editing, zoom, undo, failed writes, and tab changes during imports |
|
||||||
| `scripts/imageNavigation.smoke.mjs` | Navigator pointer drags, hidden image source, selection, context actions, inline/reference images, and drag cancellation |
|
| `scripts/imageNavigation.smoke.mjs` | Navigator pointer drags, hidden image source, selection, context actions, inline/reference images, and drag cancellation |
|
||||||
|
|
||||||
Additional smoke scripts live in `scripts/`.
|
Additional smoke scripts live in `scripts/`.
|
||||||
|
|
||||||
|
## Development help
|
||||||
|
|
||||||
|
| Problem | Action |
|
||||||
|
| --- | --- |
|
||||||
|
| Port 1420 is already in use | Stop the other RuneStone development server in its terminal, then retry. Vite uses a fixed port. |
|
||||||
|
| The app still shows the old interface | Use the development window. Check the terminal for compile errors, then restart the development command if needed. |
|
||||||
|
| Browser view says desktop features require `pnpm tauri dev` | Start that command and use its native window for real workspace and terminal tests. |
|
||||||
|
| Windows cannot find `link.exe`, or Rust cannot link the app | Install the C++ build tools and Windows SDK from the Tauri prerequisites guide above. Open a new terminal. |
|
||||||
|
| A smoke test cannot find Playwright or Chromium | Set `PLAYWRIGHT_MODULE` to an installed package. Install its Chromium browser or set `CHROME_PATH`. |
|
||||||
|
| Cargo reports missing dependencies with `--offline` | Run the command without `--offline` while connected to the internet. |
|
||||||
|
|
||||||
|
Read Rust errors in the terminal that runs `pnpm tauri dev`.
|
||||||
|
In the Windows development window, press Ctrl+Shift+I to open the web inspector.
|
||||||
|
Use its console for frontend errors.
|
||||||
|
See [Tauri's inspector instructions](https://v2.tauri.app/develop/#opening-the-web-inspector).
|
||||||
|
|||||||
+213
@@ -0,0 +1,213 @@
|
|||||||
|
# Plugins
|
||||||
|
|
||||||
|
[Back to development](development.md)
|
||||||
|
|
||||||
|
RuneStone installs local JavaScript plugins from package files or folders.
|
||||||
|
Open Settings → Plug-ins to install, enable, disable, or uninstall them.
|
||||||
|
Terminal and Table formulas use the same installed package system as all other plugins.
|
||||||
|
|
||||||
|
## Build and install the feature packages
|
||||||
|
|
||||||
|
1. Run `pnpm build:plugins` from the repository root.
|
||||||
|
2. In Settings → Plug-ins, choose Install from folder and select `plugin-packages/`.
|
||||||
|
3. Review both packages, then choose Install and enable.
|
||||||
|
|
||||||
|
No plugin starts automatically in a fresh installation.
|
||||||
|
The application build does not include these packages. Package builds include their JavaScript dependencies and terminal styles.
|
||||||
|
Build them again after source changes, then uninstall the old package and install the new folder.
|
||||||
|
The old bundled switches no longer apply. Existing terminal appearance settings remain available after installation.
|
||||||
|
Formula source stays in Markdown files when the plugin is absent, disabled, or removed.
|
||||||
|
Native pseudo-terminal services remain in the desktop host. The Terminal package supplies the interface, shortcuts, and session controls.
|
||||||
|
|
||||||
|
## Install a plugin
|
||||||
|
|
||||||
|
1. Choose Install from file or Install from folder.
|
||||||
|
2. Select the packages to install in the review dialog.
|
||||||
|
3. Choose Install to keep them disabled, or Install and enable to run them.
|
||||||
|
|
||||||
|
A plugin file uses the `.runestone-plugin` extension and ZIP format.
|
||||||
|
You can also select `plugin.json`, its containing folder, or a collection folder containing plugin folders and package files.
|
||||||
|
Collection discovery checks one level and accepts at most 100 entries.
|
||||||
|
RuneStone copies packages into its per-user application data directory. It never modifies the selected source.
|
||||||
|
The review shows the author, version, source, destination, and access level.
|
||||||
|
|
||||||
|
External plugins run with RuneStone's application access. Enable only code you trust.
|
||||||
|
Package metadata and hashes do not verify a publisher's identity. This version has no permission sandbox or marketplace.
|
||||||
|
Scanning and installation do not execute code, install dependencies, or run installation scripts.
|
||||||
|
|
||||||
|
Plugins cannot overwrite an existing ID. Uninstall the previous package before installing another version.
|
||||||
|
Each package succeeds or fails independently. The result identifies any failures.
|
||||||
|
A changed source requires a new review. Cancelling the review removes its temporary copies.
|
||||||
|
|
||||||
|
Try the example in `fixtures/plugins/workspace-overview/`.
|
||||||
|
Install that folder, then choose Install and enable.
|
||||||
|
Use the puzzle button in the main toolbar to run Show workspace overview or open the Workspace overview view.
|
||||||
|
|
||||||
|
## Uninstall with one confirmation
|
||||||
|
|
||||||
|
1. Choose Uninstall on the plugin's row.
|
||||||
|
2. Check its name, author, version, folder, and deletion message, then choose Uninstall and delete files.
|
||||||
|
|
||||||
|
The dialog initially focuses Cancel. Escape cancels the uninstall flow.
|
||||||
|
Cancel leaves the files and enabled state unchanged.
|
||||||
|
Disable instead keeps every installed file and turns the plugin off.
|
||||||
|
Each uninstall requires a new confirmation.
|
||||||
|
|
||||||
|
After confirmation, RuneStone disables the plugin in every window and waits for cleanup.
|
||||||
|
It deletes only the installed package. Source downloads, plugin settings, generated data, and workspace documents remain intact.
|
||||||
|
The app shows Restart required because already loaded JavaScript can remain in memory until RuneStone closes.
|
||||||
|
|
||||||
|
Cleanup failure blocks deletion and keeps the installed files. Restart RuneStone before trying again.
|
||||||
|
An interrupted file deletion shows Removal incomplete. Retry cleanup continues only that previously confirmed removal.
|
||||||
|
Changed files in the removal directory block further deletion. Inspect the path named in the error before retrying.
|
||||||
|
Reinstallation requires a new enable decision and can reuse retained settings.
|
||||||
|
|
||||||
|
```mermaid
|
||||||
|
flowchart LR
|
||||||
|
installed("Installed plugin") --> confirm("Confirm file deletion")
|
||||||
|
confirm --> cleanup("Stop in all windows")
|
||||||
|
cleanup --> removed("Delete package; retain data")
|
||||||
|
```
|
||||||
|
|
||||||
|
## Storage and recovery
|
||||||
|
|
||||||
|
RuneStone resolves the root through Tauri's `app_data_dir()`. Settings shows the complete path.
|
||||||
|
|
||||||
|
```text
|
||||||
|
<application-data>/
|
||||||
|
plugins/<plugin-id>/
|
||||||
|
plugin.json
|
||||||
|
main.js
|
||||||
|
assets/
|
||||||
|
plugin-data/<plugin-id>/settings.json
|
||||||
|
plugin-state.json
|
||||||
|
plugin-staging/
|
||||||
|
plugin-removals/
|
||||||
|
```
|
||||||
|
|
||||||
|
Rust stores desired enable states in `plugin-state.json` and broadcasts changes to open windows.
|
||||||
|
The browser preview has no installed plugins unless a smoke test supplies a desktop mock.
|
||||||
|
|
||||||
|
Startup, window focus, Refresh, and a five-second poll scan installed files.
|
||||||
|
Changed packages stop running and require another enable decision. Missing packages are never restored automatically.
|
||||||
|
Valid packages copied directly into the managed directory appear disabled.
|
||||||
|
Staging directories never participate in plugin discovery.
|
||||||
|
|
||||||
|
Each reviewed candidate belongs to one window and expires after 30 minutes.
|
||||||
|
Rust checks the source and staged content hashes before publishing a complete directory.
|
||||||
|
A duplicate destination blocks publication. A crash cannot enable a partial installation.
|
||||||
|
|
||||||
|
Removal plans belong to one window and expire after five minutes.
|
||||||
|
The backend accepts a single-use removal token when the user confirms deletion.
|
||||||
|
A changed package requires a new confirmation.
|
||||||
|
Runtime cleanup must complete in every window before the package moves into `plugin-removals/`.
|
||||||
|
A persisted record identifies that directory and the original file hashes.
|
||||||
|
Recovery deletes only unchanged remaining files from that confirmed transaction. It cannot target a newly installed copy.
|
||||||
|
Install and removal operations share one native service and serialize their state changes.
|
||||||
|
|
||||||
|
## Package contract
|
||||||
|
|
||||||
|
Place `plugin.json` at the root of the folder or archive:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"schemaVersion": 1,
|
||||||
|
"id": "org.example.hello",
|
||||||
|
"name": "Hello",
|
||||||
|
"author": "Example author",
|
||||||
|
"description": "Open a small example view.",
|
||||||
|
"version": "1.0.0",
|
||||||
|
"apiVersion": 1,
|
||||||
|
"entry": "main.js",
|
||||||
|
"access": "full-app"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
The package API is version 1. Its interface lives in `src/lib/plugins/sdk.ts`.
|
||||||
|
All packages use one API and the same installation, enable, disable, and removal lifecycle.
|
||||||
|
Versions use three numeric parts. Schema and API versions must match the supported version exactly.
|
||||||
|
The `runestone.*` prefix follows the same rules as other package IDs. It does not prove the publisher's identity.
|
||||||
|
|
||||||
|
Package names use ASCII letters, digits, dots, underscores, and hyphens, with forward slashes between directories.
|
||||||
|
IDs use lowercase letters, digits, dots, and hyphens and start with a letter.
|
||||||
|
Windows device names, parent traversal, absolute paths, links, junctions, and case-insensitive collisions are invalid.
|
||||||
|
Limits are 5,000 entries, 100 MiB of expanded data, and 25 MiB per file.
|
||||||
|
The manifest has a 64 KiB limit. The final installed path cannot exceed 240 characters.
|
||||||
|
|
||||||
|
The entry is one compiled `.js` or `.mjs` module. Bundle dependencies into it.
|
||||||
|
Relative module imports cannot resolve from its Blob URL. Read packaged assets through the API instead.
|
||||||
|
Raw TypeScript, Svelte source, native libraries, plugin dependencies, and automatic updates are unsupported.
|
||||||
|
|
||||||
|
## Plugin API
|
||||||
|
|
||||||
|
The entry exports `activate(api)`. Activation can return a cleanup function or a promise for that function.
|
||||||
|
The runtime limits activation and each cleanup callback to five seconds.
|
||||||
|
A timeout reports an error and blocks successful cleanup until the app restarts.
|
||||||
|
|
||||||
|
```js
|
||||||
|
export function activate(api) {
|
||||||
|
api.registerView({
|
||||||
|
id: "hello",
|
||||||
|
title: "Hello",
|
||||||
|
mount(container) {
|
||||||
|
const text = document.createElement("p");
|
||||||
|
text.textContent = "Hello from a RuneStone plugin.";
|
||||||
|
container.append(text);
|
||||||
|
return () => text.remove();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
api.registerCommand({
|
||||||
|
id: "show-hello",
|
||||||
|
title: "Show hello",
|
||||||
|
run: () => api.openView("hello")
|
||||||
|
});
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
| API | Contract |
|
||||||
|
| --- | --- |
|
||||||
|
| `api.id` | The installed plugin ID |
|
||||||
|
| `api.signal` | An abort signal triggered before shutdown |
|
||||||
|
| `contribute(key, value)` | Register a typed terminal or table formula contribution |
|
||||||
|
| `registerCommand({ id, title, run })` | Add a command to the toolbar's plugin menu |
|
||||||
|
| `registerView({ id, title, mount })` | Add a view that mounts into a supplied DOM element |
|
||||||
|
| `openView(id)` | Open one of the plugin's registered views |
|
||||||
|
| `onDispose(callback)` | Register synchronous or asynchronous cleanup |
|
||||||
|
| `workspace.list(path?)` | List a directory in this window's active workspace |
|
||||||
|
| `workspace.read(path)` | Read a workspace text file |
|
||||||
|
| `workspace.write(path, contents, expected)` | Save only if the file still matches the original text |
|
||||||
|
| `settings.read()` / `settings.write(value)` | Read or write retained JSON settings, with a 1 MiB limit |
|
||||||
|
| `assets.read(path)` | Read package bytes as a `Uint8Array` |
|
||||||
|
|
||||||
|
Command and view IDs must be unique within their respective plugin collections.
|
||||||
|
Views can return asynchronous cleanup. Closing a view and disabling its plugin share the same cleanup promise.
|
||||||
|
Remove timers, listeners, and other resources in cleanup. Use the abort signal to stop pending work.
|
||||||
|
The SDK rejects calls after shutdown starts, but it does not isolate JavaScript with full application access.
|
||||||
|
Packages activate in every RuneStone window, including standalone terminal windows.
|
||||||
|
|
||||||
|
Contribution types live in `src/lib/plugins/contracts.ts`.
|
||||||
|
Only one active package can own each contribution. The runtime removes contributions before cleanup starts.
|
||||||
|
Terminal controls mount into a host element and return update, command, and disposal functions.
|
||||||
|
The plugin must stop its mounted controls and native sessions in `onDispose` before cleanup completes.
|
||||||
|
|
||||||
|
## Modules and checks
|
||||||
|
|
||||||
|
| Module | Owns |
|
||||||
|
| --- | --- |
|
||||||
|
| `src-tauri/src/plugins.rs` | Discovery, validation, installation, persistence, removal plans, and cleanup acknowledgments |
|
||||||
|
| `src/lib/plugins/PluginManager.svelte` | Package review, switches, and the uninstall dialog |
|
||||||
|
| `src/lib/plugins/sdk.ts` | External package types |
|
||||||
|
| `src/lib/plugins/externalSession.ts` | Activation, contributions, view disposal, and shutdown |
|
||||||
|
| `src/lib/plugins/external.ts` | Native state synchronization and external module loading |
|
||||||
|
| `src/lib/plugins/PluginTools.svelte` | External commands and views |
|
||||||
|
| `src/lib/plugins/registry.ts` / `contracts.ts` | Shared feature contributions and their types |
|
||||||
|
| `src/lib/plugins/TerminalSlot.svelte` | The host element for terminal controls |
|
||||||
|
| `plugins/terminal/` / `plugins/table-formulas/` | Separate feature packages |
|
||||||
|
| `scripts/buildPlugins.mjs` | Package compilation into `plugin-packages/` |
|
||||||
|
|
||||||
|
Run `pnpm build:plugins`, `pnpm check`, `pnpm test`, `pnpm build`, and `cargo test --manifest-path src-tauri/Cargo.toml --lib --offline`.
|
||||||
|
The Rust tests use real temporary files and archives. Browser tests mock desktop calls and exercise the real UI and module loader.
|
||||||
|
Run `scripts/pluginInstall.smoke.mjs`, `scripts/plugins.smoke.mjs`, and `scripts/settings.smoke.mjs` against the development server.
|
||||||
|
|
||||||
|
Native plugin packages and restricted permissions remain future work.
|
||||||
|
The core keeps basic Markdown tables, file editing, selection, sorting, and document access when optional features stop.
|
||||||
+21
-10
@@ -5,16 +5,17 @@
|
|||||||
This reference preserves intended capabilities and design constraints. Some features already exist.
|
This reference preserves intended capabilities and design constraints. Some features already exist.
|
||||||
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 planned design keeps the core active and adds optional features through separately packaged plugins. Plugin support is not implemented yet.
|
The core stays active while installed packages supply optional Terminal and Table formulas features.
|
||||||
|
External JavaScript packages can add commands and views. See the [plugin guide](plugins.md) for current boundaries.
|
||||||
|
|
||||||
## Workspace and files
|
## Workspace and files
|
||||||
|
|
||||||
- Open one folder as the workspace.
|
- Open one folder as the workspace.
|
||||||
- Keep notes, scripts, and images in the same tree.
|
- Keep notes, scripts, and images in the same tree.
|
||||||
- Honor `.gitignore` in the navigator.
|
- Show workspace files without applying `.gitignore`, `.ignore`, or global Git exclusions.
|
||||||
- Watch the folder for changes. Poll when the path is a network drive.
|
- Watch the folder for changes. Poll when the path is a network drive.
|
||||||
- Prefer a local Git clone. Do not treat a live network share as the sync path.
|
- Prefer a local Git clone. Do not treat a live network share as the sync path.
|
||||||
- Store display order, pins, bookmarks, and plugin settings in `.runestone/`.
|
- Store display order, pins, and bookmarks in `.runestone/`. Store plugin packages and retained plugin settings in application data.
|
||||||
- Open an existing Obsidian folder as files plus wiki links. Ignore `.obsidian`.
|
- Open an existing Obsidian folder as files plus wiki links. Ignore `.obsidian`.
|
||||||
|
|
||||||
## Writer and IDE
|
## Writer and IDE
|
||||||
@@ -47,15 +48,25 @@ The planned design keeps the core active and adds optional features through sepa
|
|||||||
|
|
||||||
## Plugins
|
## Plugins
|
||||||
|
|
||||||
Plugin support is pending. In-house plugins ship with RuneStone as separate packages and use the same interfaces as external plugins.
|
Terminal and Table formulas use the same installed package system as all other plugins.
|
||||||
|
External JavaScript packages now support local installation, commands, views, retained settings, and removal with one confirmation.
|
||||||
Users can enable or disable each plugin. A marketplace is outside the planned scope.
|
Users can enable or disable each plugin. A marketplace is outside the planned scope.
|
||||||
|
Installation accepts plugin packages or folders and stores copies in the application data directory.
|
||||||
|
Uninstall requires one confirmation before RuneStone removes the installed plugin files.
|
||||||
|
Cancel preserves the plugin. Removal keeps settings, source packages, and workspace documents.
|
||||||
|
See the [installation and removal guide](plugins.md#uninstall-with-one-confirmation).
|
||||||
|
|
||||||
### Plugin to-do list
|
### Plugin to-do list
|
||||||
|
|
||||||
- [ ] Build the plugin system: package loading, version checks, permissions, settings, and enable or disable controls.
|
- [x] Use one package system with API version checks, cleanup, saved preferences, and enable controls.
|
||||||
- [ ] Define shared interfaces for plugins to add commands, views, and workspace features.
|
- [x] Add external package loading, exact API compatibility checks, and retained plugin settings.
|
||||||
- [ ] Move the terminal into a separate in-house plugin that ships with RuneStone.
|
- [x] Define an external API for commands, views, and workspace files.
|
||||||
- [ ] Move Excel-like table features, including formulas and spreadsheet operations, into a separate in-house plugin that ships with RuneStone.
|
- [x] Require one confirmation before removing installed plugin files.
|
||||||
|
- [ ] Add isolated execution and restricted permissions.
|
||||||
|
- [x] Move terminal views, shortcuts, settings, and desktop API calls into an external plugin package.
|
||||||
|
- [ ] Move native terminal services into a separate in-house package.
|
||||||
|
- [x] Move formula evaluation, rendered results, and help controls into an external Table formulas package.
|
||||||
|
- [ ] Move the remaining spreadsheet operations into a separate in-house package.
|
||||||
- [ ] Add a Kanban plugin for boards, columns, and task cards.
|
- [ ] Add a Kanban plugin for boards, columns, and task cards.
|
||||||
- [ ] Add a Gantt plugin for task timelines and dependencies.
|
- [ ] Add a Gantt plugin for task timelines and dependencies.
|
||||||
- [ ] Add a Calendar plugin for dated tasks and events.
|
- [ ] Add a Calendar plugin for dated tasks and events.
|
||||||
@@ -65,9 +76,9 @@ Keep basic Markdown table editing and rendering in the core. Users must retain a
|
|||||||
Kanban, Gantt, and Calendar are separate plugins that share a task index.
|
Kanban, Gantt, and Calendar are separate plugins that share a task index.
|
||||||
Kanban boards are Markdown files. Headings are columns. Task list items are cards.
|
Kanban boards are Markdown files. Headings are columns. Task list items are cards.
|
||||||
|
|
||||||
### Planned defaults
|
### Planned plugin lineup
|
||||||
|
|
||||||
Planned plugins enabled by default:
|
No plugin starts automatically in a fresh installation. The planned lineup includes:
|
||||||
|
|
||||||
- Terminal. Workspace shells, sessions, and script execution.
|
- Terminal. Workspace shells, sessions, and script execution.
|
||||||
- Tables. Excel-like formulas and spreadsheet operations.
|
- Tables. Excel-like formulas and spreadsheet operations.
|
||||||
|
|||||||
+4
-2
@@ -44,8 +44,10 @@ 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.
|
||||||
|
|
||||||
Plugin support is pending. Separately packaged plugins would let users choose tools for planning, tabletop play, and other workflows.
|
Users can install, disable, and remove Terminal and Table formulas while retaining access to their files.
|
||||||
The terminal and Excel-like table features would ship as in-house plugins through the same plugin system.
|
Separately packaged plugins can extend that choice to planning, tabletop play, and other workflows.
|
||||||
|
Users can now install local packages and remove them through one confirmation while retaining their data.
|
||||||
|
Restricted permissions and the remaining spreadsheet modules are still planned.
|
||||||
|
|
||||||
**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.
|
||||||
|
|||||||
+27
-3
@@ -2,10 +2,33 @@
|
|||||||
|
|
||||||
[Back to RuneStone](../README.md)
|
[Back to RuneStone](../README.md)
|
||||||
|
|
||||||
Current features and limitations as of September 2026.
|
Current features and limitations as of October 2026.
|
||||||
|
|
||||||
|
## Settings and help
|
||||||
|
|
||||||
|
Use the gear beside the workspace selector to open Settings, or press Ctrl+,.
|
||||||
|
Use the question mark beside it to open Help and about, or press F1.
|
||||||
|
Both shortcuts work when the sidebar is hidden.
|
||||||
|
|
||||||
|
General settings control auto-save. It starts enabled, with a five-second interval.
|
||||||
|
Choose a whole number from 1 to 300 seconds, or turn auto-save off.
|
||||||
|
Changes apply when you leave the interval field and persist across restarts.
|
||||||
|
These preferences apply to all workspaces on this device. Other open windows receive changes immediately.
|
||||||
|
Restore defaults enables auto-save and sets the interval to five seconds.
|
||||||
|
|
||||||
|
Search settings to find a category. Plug-ins lists installed packages, including Terminal and Table formulas after installation.
|
||||||
|
No plugin starts automatically in a fresh installation. Enable changes persist across restarts and open windows.
|
||||||
|
Disabling Terminal ends its sessions. Disabling Table formulas keeps the formula source and basic table editing.
|
||||||
|
Use Install from file or Install from folder to add local plugins. The puzzle button opens their commands and views.
|
||||||
|
Uninstall requires one confirmation and preserves settings, source packages, and workspace documents.
|
||||||
|
See the [plugin guide](plugins.md) for package formats, removal, and current boundaries.
|
||||||
|
Help and about includes the app version, basic instructions, and keyboard shortcuts.
|
||||||
|
Press Escape or use the close button to return to your work.
|
||||||
|
|
||||||
## Workspace, editing, and terminals
|
## Workspace, editing, and terminals
|
||||||
|
|
||||||
|
- The navigator, Quick Open, and search do not apply `.gitignore`, `.ignore`, or global Git exclusions.
|
||||||
|
Internal folders (`.git`, `.obsidian`, and `.runestone`) and temporary save files stay hidden.
|
||||||
- The folder button and Ctrl+O open recent workspaces, with the current workspace
|
- The folder button and Ctrl+O open recent workspaces, with the current workspace
|
||||||
marked and full paths shown. The list remembers the 20 most recently opened
|
marked and full paths shown. The list remembers the 20 most recently opened
|
||||||
folders across restarts. Open another folder from the bottom of the menu, or
|
folders across restarts. Open another folder from the bottom of the menu, or
|
||||||
@@ -88,7 +111,8 @@ Current features and limitations as of September 2026.
|
|||||||
- Right-click a tab for Move tab left and Move tab right. With a tab focused, use Alt+Shift+Left or Alt+Shift+Right.
|
- Right-click a tab for Move tab left and Move tab right. With a tab focused, use Alt+Shift+Left or Alt+Shift+Right.
|
||||||
Use the arrow keys, Home, or End to select tabs. Press Escape to cancel a drag.
|
Use the arrow keys, Home, or End to select tabs. Press Escape to cancel a drag.
|
||||||
- Click the + beside the tabs or press Ctrl T to open an empty tab. Open or create a file from there to use that tab. No file is created until you choose New file.
|
- Click the + beside the tabs or press Ctrl T to open an empty tab. Open or create a file from there to use that tab. No file is created until you choose New file.
|
||||||
- Changed notes and scripts autosave every 5 seconds, including background tabs.
|
- Changed notes and scripts auto-save every five seconds by default, including background tabs.
|
||||||
|
Use Settings to change the interval or turn auto-save off.
|
||||||
Unchanged files are never rewritten. Ctrl+S saves immediately. Disk conflicts
|
Unchanged files are never rewritten. Ctrl+S saves immediately. Disk conflicts
|
||||||
and unavailable files preserve your edits for resolution instead of overwriting.
|
and unavailable files preserve your edits for resolution instead of overwriting.
|
||||||
- The reader uses a Markdown parser for paragraphs, nested lists, tables, tasks,
|
- The reader uses a Markdown parser for paragraphs, nested lists, tables, tasks,
|
||||||
@@ -143,6 +167,6 @@ Current features and limitations as of September 2026.
|
|||||||
## Limitations
|
## Limitations
|
||||||
|
|
||||||
Vault-wide wiki-link resolution, backlinks and math rendering still need work.
|
Vault-wide wiki-link resolution, backlinks and math rendering still need work.
|
||||||
Git UI, language servers, plugins, persistent tab restoration and crash recovery
|
Git UI, language servers, restricted plugin permissions, persistent tab restoration and crash recovery
|
||||||
are not implemented. Unsaved buffers and terminals last for the current app
|
are not implemented. Unsaved buffers and terminals last for the current app
|
||||||
session only.
|
session only.
|
||||||
|
|||||||
@@ -0,0 +1,26 @@
|
|||||||
|
export function activate(api) {
|
||||||
|
api.registerCommand({ id: "show-overview", title: "Show workspace overview", run: () => api.openView("overview") });
|
||||||
|
api.registerView({
|
||||||
|
id: "overview",
|
||||||
|
title: "Workspace overview",
|
||||||
|
async mount(container) {
|
||||||
|
const status = document.createElement("p");
|
||||||
|
status.textContent = "Loading workspace files…";
|
||||||
|
container.append(status);
|
||||||
|
let disposed = false;
|
||||||
|
try {
|
||||||
|
const entries = await api.workspace.list();
|
||||||
|
if (api.signal.aborted || disposed) return;
|
||||||
|
status.textContent = `${entries.length} files and folders in this workspace.`;
|
||||||
|
const list = document.createElement("ul");
|
||||||
|
for (const entry of entries) {
|
||||||
|
const item = document.createElement("li");
|
||||||
|
item.textContent = `${entry.name}${entry.kind === "folder" ? "/" : ""}`;
|
||||||
|
list.append(item);
|
||||||
|
}
|
||||||
|
container.append(list);
|
||||||
|
} catch (error) { status.textContent = String(error); }
|
||||||
|
return () => { disposed = true; container.replaceChildren(); };
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
{
|
||||||
|
"schemaVersion": 1,
|
||||||
|
"id": "org.runestone-example.workspace-overview",
|
||||||
|
"name": "Workspace overview",
|
||||||
|
"author": "RuneStone example",
|
||||||
|
"description": "List files and folders in the active workspace.",
|
||||||
|
"version": "1.0.0",
|
||||||
|
"apiVersion": 1,
|
||||||
|
"entry": "main.js",
|
||||||
|
"access": "full-app"
|
||||||
|
}
|
||||||
+4
-3
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "runestone",
|
"name": "runestone",
|
||||||
"version": "0.1.3",
|
"version": "0.1.4",
|
||||||
"description": "Desktop editor for a local workspace",
|
"description": "Desktop editor for a local workspace",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
@@ -9,10 +9,11 @@
|
|||||||
"build:installer": "tauri build --bundles nsis -- --locked",
|
"build:installer": "tauri build --bundles nsis -- --locked",
|
||||||
"preview": "vite preview",
|
"preview": "vite preview",
|
||||||
"prepare": "svelte-kit sync || echo ''",
|
"prepare": "svelte-kit sync || echo ''",
|
||||||
"check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json",
|
"check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json && svelte-check --tsconfig ./tsconfig.plugins.json",
|
||||||
"check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch",
|
"check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch",
|
||||||
"tauri": "tauri",
|
"tauri": "tauri",
|
||||||
"test": "node --experimental-strip-types --test scripts/*.spec.ts"
|
"test": "node --experimental-strip-types --test scripts/*.spec.ts",
|
||||||
|
"build:plugins": "node scripts/buildPlugins.mjs"
|
||||||
},
|
},
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
|
|||||||
@@ -0,0 +1,46 @@
|
|||||||
|
import { actionIcon } from "../../src/lib/ui/actionIcons.ts";
|
||||||
|
|
||||||
|
export function createFormulaTools(finish: () => void, measure: () => void) {
|
||||||
|
const formulaTools = document.createElement("div");
|
||||||
|
formulaTools.className = "table-formula-tools";
|
||||||
|
const formulaHelp = document.createElement("details");
|
||||||
|
formulaHelp.className = "table-formula-help";
|
||||||
|
const summary = document.createElement("summary");
|
||||||
|
summary.append(actionIcon("math"), document.createTextNode("Formulas"));
|
||||||
|
summary.title = "How to calculate with table cells";
|
||||||
|
// Committing a wrapped formula can shrink its row. Keep the click target in
|
||||||
|
// place until mouseup, then finish editing and give keyboard focus to help.
|
||||||
|
summary.addEventListener("mousedown", event => { if (event.button === 0) { event.preventDefault(); event.stopPropagation(); } });
|
||||||
|
summary.addEventListener("click", () => { finish(); summary.focus(); });
|
||||||
|
const instructions = document.createElement("div");
|
||||||
|
instructions.className = "table-formula-instructions";
|
||||||
|
const intro = document.createElement("p");
|
||||||
|
intro.textContent = "Start a cell with =, then press Enter or Tab. Columns are A, B, C…; the header is row 1 and the first data row is 2.";
|
||||||
|
const examples = document.createElement("dl");
|
||||||
|
for (const [formula, description] of [
|
||||||
|
["=AVERAGE(B2,C2)", "Average two values: 9 and 10 give 9.5."],
|
||||||
|
["=AVERAGE(B2:C2)", "Average every cell in the range B2 through C2."],
|
||||||
|
["=SUM(B2:B10)", "Add the values in a range."],
|
||||||
|
["=(B2+C2)/2", "Add two values and divide by two."],
|
||||||
|
["=ROUND(B2/3,2)", "Round to two decimal places."],
|
||||||
|
]) {
|
||||||
|
const term = document.createElement("dt"), code = document.createElement("code"), descriptionElement = document.createElement("dd");
|
||||||
|
code.textContent = formula; term.append(code); descriptionElement.textContent = description;
|
||||||
|
examples.append(term, descriptionElement);
|
||||||
|
}
|
||||||
|
const functions = document.createElement("p");
|
||||||
|
functions.textContent = "Functions: SUM, AVERAGE, MIN, MAX, COUNT, ABS, ROUND. Operators: + − * / ^ and %. Use commas between function arguments; use a colon for a cell range.";
|
||||||
|
const references = document.createElement("p");
|
||||||
|
references.textContent = "References stay at their written addresses when copying, inserting, deleting, sorting, or moving cells. Code-formatted expressions are literal text; formulas must start with = outside code formatting.";
|
||||||
|
instructions.append(intro, examples, functions, references);
|
||||||
|
formulaHelp.append(summary, instructions);
|
||||||
|
formulaHelp.addEventListener("toggle", measure);
|
||||||
|
const formulaStatus = document.createElement("span");
|
||||||
|
formulaStatus.className = "table-formula-status";
|
||||||
|
formulaStatus.textContent = "Type = in a cell to calculate";
|
||||||
|
const formulaHint = document.createElement("div");
|
||||||
|
formulaHint.className = "table-formula-hint";
|
||||||
|
formulaHint.hidden = true;
|
||||||
|
formulaTools.append(formulaHelp, formulaStatus);
|
||||||
|
return { formulaTools, formulaStatus, formulaHint };
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
import type { PluginApi } from "../../src/lib/plugins/sdk.ts";
|
||||||
|
import { createFormulaTools } from "./controls.ts";
|
||||||
|
import * as formulas from "./formulas.ts";
|
||||||
|
import { tableFormulaHtml, renderTableFormulas } from "./render.ts";
|
||||||
|
|
||||||
|
export function activate(api: PluginApi) {
|
||||||
|
api.contribute("tableFormulas", { ...formulas, tableFormulaHtml, renderTableFormulas, createFormulaTools });
|
||||||
|
}
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
{
|
||||||
|
"schemaVersion": 1,
|
||||||
|
"id": "runestone.table-formulas",
|
||||||
|
"name": "Table formulas",
|
||||||
|
"author": "RuneStone",
|
||||||
|
"description": "Calculate formulas in Markdown tables.",
|
||||||
|
"version": "1.0.0",
|
||||||
|
"apiVersion": 1,
|
||||||
|
"entry": "main.js",
|
||||||
|
"access": "full-app"
|
||||||
|
}
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
import MarkdownIt from "markdown-it";
|
||||||
|
import type { Token } from "markdown-it";
|
||||||
|
import { evaluateTableFormulas, formulaErrors, type FormulaResult } from "./formulas.ts";
|
||||||
|
const escapeHtml = (text: string) => text.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">").replaceAll('"', """);
|
||||||
|
|
||||||
|
export function tableFormulaHtml(result: FormulaResult): string {
|
||||||
|
const label = `${result.formula} → ${result.error ? formulaErrors[result.error] : result.text}`;
|
||||||
|
return `<span class="md-table-formula${result.error ? " is-error" : ""}" title="${escapeHtml(label)}" aria-label="${escapeHtml(label)}">${escapeHtml(result.text)}</span>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function renderTableFormulas(tokens: Token[]) {
|
||||||
|
let rows: Token[][] | undefined;
|
||||||
|
for (const token of tokens) {
|
||||||
|
if (token.type === "table_open") rows = [];
|
||||||
|
else if (rows && token.type === "tr_open") rows.push([]);
|
||||||
|
else if (rows && token.type === "inline") rows.at(-1)?.push(token);
|
||||||
|
else if (rows && token.type === "table_close") {
|
||||||
|
const results = evaluateTableFormulas(rows.map(row => row.map(cell => cell.content)));
|
||||||
|
rows.forEach((row, r) => row.forEach((cell, c) => {
|
||||||
|
const result = results[r][c];
|
||||||
|
if (!result) return;
|
||||||
|
const output = new MarkdownIt.Token("html_inline", "", 0);
|
||||||
|
output.content = tableFormulaHtml(result);
|
||||||
|
cell.children = [output];
|
||||||
|
}));
|
||||||
|
rows = undefined;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import { untrack } from "svelte";
|
||||||
|
import type { TerminalProps, TerminalAction } from "../../src/lib/plugins/contracts";
|
||||||
|
import TerminalDock from "./TerminalDock.svelte";
|
||||||
|
let { initial }: { initial: TerminalProps } = $props();
|
||||||
|
let dockProps = $state<TerminalProps>(untrack(() => initial));
|
||||||
|
let dock: TerminalDock;
|
||||||
|
export function update(value: TerminalProps) { dockProps = value; }
|
||||||
|
export async function command(action: Exclude<TerminalAction, "toggle">) { await dock.command(action); }
|
||||||
|
</script>
|
||||||
|
<TerminalDock bind:this={dock} {...dockProps} />
|
||||||
@@ -2,10 +2,11 @@
|
|||||||
import { onMount, tick } from "svelte";
|
import { onMount, tick } from "svelte";
|
||||||
import IconButton from "$lib/ui/IconButton.svelte";
|
import IconButton from "$lib/ui/IconButton.svelte";
|
||||||
import { actionMenu, type ActionMenuItem } from "$lib/ui/actionMenu";
|
import { actionMenu, type ActionMenuItem } from "$lib/ui/actionMenu";
|
||||||
import { ptyProfiles, ptyNewWindow, ptyDictation, workspaceRead } from "$lib/workspace/api";
|
import { workspaceRead } from "$lib/workspace/api";
|
||||||
import { directoryCommand, fileCommand, parseTasks, readSettings, remember, type ShellProfile, type TerminalControl, type TerminalSettings as Settings } from "$lib/terminal/model";
|
import { ptyProfiles, ptyNewWindow, ptyDictation } from "./api";
|
||||||
import TerminalPicker from "$lib/terminal/TerminalPicker.svelte";
|
import { directoryCommand, fileCommand, parseTasks, readSettings, remember, type ShellProfile, type TerminalControl, type TerminalSettings as Settings } from "./model";
|
||||||
import TerminalSettings from "$lib/terminal/TerminalSettings.svelte";
|
import TerminalPicker from "./TerminalPicker.svelte";
|
||||||
|
import TerminalSettings from "./TerminalSettings.svelte";
|
||||||
import TerminalPane from "./TerminalPane.svelte";
|
import TerminalPane from "./TerminalPane.svelte";
|
||||||
|
|
||||||
type Session = { id: string; group: string; title: string; state: string; profile: ShellProfile; directory: string; weight: number; command?: string };
|
type Session = { id: string; group: string; title: string; state: string; profile: ShellProfile; directory: string; weight: number; command?: string };
|
||||||
@@ -3,8 +3,8 @@
|
|||||||
import { FitAddon } from "@xterm/addon-fit";
|
import { FitAddon } from "@xterm/addon-fit";
|
||||||
import { Terminal } from "@xterm/xterm";
|
import { Terminal } from "@xterm/xterm";
|
||||||
import { onMount } from "svelte";
|
import { onMount } from "svelte";
|
||||||
import { ptyClose, ptyOpen, ptyResize, ptyWrite } from "$lib/workspace/api";
|
import { ptyClose, ptyOpen, ptyResize, ptyWrite } from "./api";
|
||||||
import { terminalShortcut, type ShellProfile, type TerminalControl, type TerminalSettings } from "$lib/terminal/model";
|
import { terminalShortcut, type ShellProfile, type TerminalControl, type TerminalSettings } from "./model";
|
||||||
import "@xterm/xterm/css/xterm.css";
|
import "@xterm/xterm/css/xterm.css";
|
||||||
|
|
||||||
type Props = {
|
type Props = {
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
import { invoke } from "@tauri-apps/api/core";
|
||||||
|
|
||||||
|
const sessions = new Set<string>();
|
||||||
|
const opening = new Set<Promise<void>>();
|
||||||
|
const closing = new Map<string, Promise<void>>();
|
||||||
|
let stopped = false;
|
||||||
|
|
||||||
|
export async function closeTerminals(): Promise<void> {
|
||||||
|
stopped = true;
|
||||||
|
await Promise.allSettled([...opening]);
|
||||||
|
const results = await Promise.allSettled([...sessions].map(ptyClose));
|
||||||
|
const errors = results.filter(result => result.status === "rejected");
|
||||||
|
if (errors.length) throw new Error(errors.map(result => String(result.reason)).join("\n"));
|
||||||
|
}
|
||||||
|
|
||||||
|
export function ptyOpen(id: string, cols: number, rows: number, cwd: string, profile?: string, directory?: string): Promise<void> {
|
||||||
|
if (stopped) return Promise.reject(new Error("This plugin is disabled."));
|
||||||
|
sessions.add(id);
|
||||||
|
const pending = invoke<void>("pty_open", { id, cols, rows, cwd, profile, directory });
|
||||||
|
opening.add(pending);
|
||||||
|
void pending.finally(() => opening.delete(pending)).catch(() => {});
|
||||||
|
return pending;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function ptyProfiles(): Promise<import("./model").ShellProfile[]> {
|
||||||
|
return invoke("pty_profiles");
|
||||||
|
}
|
||||||
|
export function ptyNewWindow(): Promise<void> {
|
||||||
|
return invoke("pty_new_window", { id: crypto.randomUUID() });
|
||||||
|
}
|
||||||
|
export function ptyDictation(): Promise<void> { return invoke("pty_dictation"); }
|
||||||
|
|
||||||
|
export function ptyWrite(id: string, data: string): Promise<void> {
|
||||||
|
return invoke("pty_write", { id, data });
|
||||||
|
}
|
||||||
|
|
||||||
|
export function ptyResize(id: string, cols: number, rows: number): Promise<void> {
|
||||||
|
return invoke("pty_resize", { id, cols, rows });
|
||||||
|
}
|
||||||
|
|
||||||
|
export function ptyClose(id: string): Promise<void> {
|
||||||
|
const pending = closing.get(id);
|
||||||
|
if (pending) return pending;
|
||||||
|
const close = invoke<void>("pty_close", { id }).then(() => { sessions.delete(id); }).finally(() => closing.delete(id));
|
||||||
|
closing.set(id, close);
|
||||||
|
return close;
|
||||||
|
}
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
import { flushSync, mount, unmount } from "svelte";
|
||||||
|
import type { PluginApi } from "../../src/lib/plugins/sdk.ts";
|
||||||
|
import { terminalShortcut } from "./model.ts";
|
||||||
|
import TerminalBridge from "./TerminalBridge.svelte";
|
||||||
|
import { closeTerminals } from "./api.ts";
|
||||||
|
|
||||||
|
export async function activate(api: PluginApi) {
|
||||||
|
const css = new TextDecoder().decode(await api.assets.read("style.css"));
|
||||||
|
if (api.signal.aborted) return;
|
||||||
|
const style = document.createElement("style");
|
||||||
|
style.textContent = css;
|
||||||
|
document.head.append(style);
|
||||||
|
api.onDispose(() => style.remove());
|
||||||
|
const mounts = new Set<() => Promise<void>>();
|
||||||
|
api.onDispose(closeTerminals);
|
||||||
|
api.onDispose(async () => { await Promise.all([...mounts].map(dispose => dispose())); });
|
||||||
|
api.contribute("terminal", {
|
||||||
|
shortcut: terminalShortcut,
|
||||||
|
mount(container, props) {
|
||||||
|
if (api.signal.aborted) throw new Error("This plugin is disabled.");
|
||||||
|
const instance = mount(TerminalBridge, { target: container, props: { initial: props } });
|
||||||
|
flushSync();
|
||||||
|
let stopping: Promise<void> | undefined;
|
||||||
|
const dispose = () => stopping ??= unmount(instance).then(() => { mounts.delete(dispose); });
|
||||||
|
mounts.add(dispose);
|
||||||
|
return { update: value => instance.update(value), command: action => instance.command(action), dispose };
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
{
|
||||||
|
"schemaVersion": 1,
|
||||||
|
"id": "runestone.terminal",
|
||||||
|
"name": "Terminal",
|
||||||
|
"author": "RuneStone",
|
||||||
|
"description": "Run shells, scripts, and workspace tasks.",
|
||||||
|
"version": "1.0.0",
|
||||||
|
"apiVersion": 1,
|
||||||
|
"entry": "main.js",
|
||||||
|
"access": "full-app"
|
||||||
|
}
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
import { build } from "vite";
|
||||||
|
import { svelte } from "@sveltejs/vite-plugin-svelte";
|
||||||
|
import { copyFile, mkdir } from "node:fs/promises";
|
||||||
|
import { fileURLToPath } from "node:url";
|
||||||
|
|
||||||
|
const root = fileURLToPath(new URL("../", import.meta.url));
|
||||||
|
for (const name of ["terminal", "table-formulas"]) {
|
||||||
|
const source = new URL(`../plugins/${name}/`, import.meta.url);
|
||||||
|
const output = new URL(`../plugin-packages/${name}/`, import.meta.url);
|
||||||
|
await build({
|
||||||
|
configFile: false,
|
||||||
|
root,
|
||||||
|
plugins: [svelte({ configFile: false, compilerOptions: { dev: false } })],
|
||||||
|
resolve: { alias: { $lib: fileURLToPath(new URL("../src/lib/", import.meta.url)) }, conditions: ["browser"] },
|
||||||
|
build: {
|
||||||
|
outDir: fileURLToPath(output), emptyOutDir: true,
|
||||||
|
lib: { entry: fileURLToPath(new URL("index.ts", source)), formats: ["es"], fileName: () => "main.js", cssFileName: "style" },
|
||||||
|
rolldownOptions: { output: { codeSplitting: false } },
|
||||||
|
},
|
||||||
|
});
|
||||||
|
await mkdir(output, { recursive: true });
|
||||||
|
await copyFile(new URL("plugin.json", source), new URL("plugin.json", output));
|
||||||
|
}
|
||||||
@@ -0,0 +1,77 @@
|
|||||||
|
import test from "node:test";
|
||||||
|
import assert from "node:assert/strict";
|
||||||
|
import { ExternalSession } from "../src/lib/plugins/externalSession.ts";
|
||||||
|
import type { PluginApi } from "../src/lib/plugins/sdk.ts";
|
||||||
|
function fixture() {
|
||||||
|
let writes = 0;
|
||||||
|
const session = new ExternalSession("org.test.demo", {
|
||||||
|
workspace: { list: async () => [], read: async () => "original", write: async () => { writes++; } },
|
||||||
|
settings: { read: async () => null, write: async () => {} },
|
||||||
|
assets: { read: async () => new Uint8Array() },
|
||||||
|
}, () => {}, () => {});
|
||||||
|
return { session, writes: () => writes };
|
||||||
|
}
|
||||||
|
test("external commands run and all host access stops before cleanup", async () => {
|
||||||
|
const { session, writes } = fixture(); let api!: PluginApi; let ran = 0;
|
||||||
|
await session.start({ activate(value) {
|
||||||
|
api = value;
|
||||||
|
api.registerCommand({ id: "run", title: "Run", run: () => { ran++; } });
|
||||||
|
api.registerView({ id: "view", title: "View", mount: () => {} });
|
||||||
|
api.onDispose(() => { assert(api.signal.aborted); assert.throws(() => api.workspace.read("x"), /disabled/); });
|
||||||
|
} });
|
||||||
|
await session.run("run"); assert.equal(ran, 1);
|
||||||
|
assert.throws(() => api.workspace.write("x", "new", undefined!), /original/);
|
||||||
|
await api.workspace.write("x", "new", "original"); assert.equal(writes(), 1);
|
||||||
|
await session.stop(); assert.equal(session.commands.size, 0); assert.equal(session.views.size, 0);
|
||||||
|
await assert.rejects(session.run("run"), /disabled/);
|
||||||
|
assert.throws(() => api.settings.read(), /disabled/);
|
||||||
|
});
|
||||||
|
test("async activation cleanup runs once even when disabled before activation finishes", async () => {
|
||||||
|
const { session } = fixture(); let resolve!: () => void; let cleaned = 0;
|
||||||
|
const gate = new Promise<void>(done => resolve = done);
|
||||||
|
const start = session.start({ async activate() { await gate; return () => { cleaned++; }; } });
|
||||||
|
await Promise.resolve();
|
||||||
|
const stopped = session.stop(); resolve();
|
||||||
|
await Promise.all([start, stopped]); await session.stop(); assert.equal(cleaned, 1);
|
||||||
|
});
|
||||||
|
test("failed cleanup does not skip other callbacks and blocks successful shutdown", async () => {
|
||||||
|
const { session } = fixture(); const calls: number[] = [];
|
||||||
|
await session.start({ activate(api) {
|
||||||
|
api.onDispose(() => { calls.push(1); });
|
||||||
|
api.onDispose(() => { calls.push(2); throw new Error("Cleanup failed"); });
|
||||||
|
api.onDispose(() => { calls.push(3); });
|
||||||
|
} });
|
||||||
|
await assert.rejects(session.stop(), /Cleanup failed/); assert.deepEqual(calls, [3, 2, 1]);
|
||||||
|
});
|
||||||
|
test("duplicate contribution IDs fail and partial activation can be cleaned", async () => {
|
||||||
|
const { session } = fixture(); let cleaned = false;
|
||||||
|
await assert.rejects(session.start({ activate(api) {
|
||||||
|
api.onDispose(() => { cleaned = true; });
|
||||||
|
api.registerCommand({ id: "run", title: "Run", run() {} });
|
||||||
|
api.registerCommand({ id: "run", title: "Again", run() {} });
|
||||||
|
} }), /duplicate/);
|
||||||
|
await session.stop(); assert(cleaned); assert.equal(session.commands.size, 0);
|
||||||
|
});
|
||||||
|
test("view disposal is idempotent and participates in plugin shutdown", async () => {
|
||||||
|
const { session } = fixture(); let cleaned = 0; let cleared = 0;
|
||||||
|
await session.start({ activate(api) { api.registerView({ id: "view", title: "View", mount: () => () => { cleaned++; } }); } });
|
||||||
|
const cleanup = await session.mount("view", { replaceChildren() { cleared++; } } as unknown as HTMLElement);
|
||||||
|
await session.stop(); await cleanup(); assert.equal(cleaned, 1); assert.equal(cleared, 1);
|
||||||
|
});
|
||||||
|
test("shutdown waits for view cleanup that already started when the view closed", async () => {
|
||||||
|
const { session } = fixture(); let done!: () => void; let cleaned = false;
|
||||||
|
const gate = new Promise<void>(resolve => done = resolve);
|
||||||
|
await session.start({ activate(api) { api.registerView({ id: "view", title: "View", mount: () => async () => { await gate; cleaned = true; } }); } });
|
||||||
|
const cleanup = await session.mount("view", { replaceChildren() {} } as unknown as HTMLElement);
|
||||||
|
const closing = cleanup(); await Promise.resolve();
|
||||||
|
let stopped = false; const stopping = session.stop().then(() => { stopped = true; });
|
||||||
|
await Promise.resolve(); await Promise.resolve(); assert.equal(stopped, false);
|
||||||
|
done(); await Promise.all([closing, stopping]); assert(cleaned);
|
||||||
|
});
|
||||||
|
test("cleanup returned by late activation still blocks shutdown when it fails", async () => {
|
||||||
|
const { session } = fixture(); let done!: () => void;
|
||||||
|
const gate = new Promise<void>(resolve => done = resolve);
|
||||||
|
const starting = session.start({ async activate() { await gate; return () => { throw new Error("Late cleanup failed"); }; } });
|
||||||
|
await Promise.resolve(); const stopping = session.stop(); done();
|
||||||
|
await assert.rejects(starting, /Late cleanup failed/); await assert.rejects(stopping, /Late cleanup failed/);
|
||||||
|
});
|
||||||
@@ -0,0 +1,172 @@
|
|||||||
|
// Run against `pnpm dev`. PLAYWRIGHT_MODULE may point to a shared installation.
|
||||||
|
import { createRequire } from "node:module";
|
||||||
|
import assert from "node:assert/strict";
|
||||||
|
import { readFileSync } from "node:fs";
|
||||||
|
const require = createRequire(import.meta.url);
|
||||||
|
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright");
|
||||||
|
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
|
||||||
|
const context = await browser.newContext({ viewport: { width: 1440, height: 1000 } });
|
||||||
|
const page = await context.newPage();
|
||||||
|
page.setDefaultTimeout(10000);
|
||||||
|
const errors = [];
|
||||||
|
page.on("console", message => { if (message.type() === "error" || message.type() === "warning") console.log(message.type(), message.text()); });
|
||||||
|
page.on("pageerror", error => errors.push(error.message));
|
||||||
|
const manifest = JSON.parse(readFileSync('fixtures/plugins/workspace-overview/plugin.json', 'utf8'));
|
||||||
|
const pluginCode = readFileSync('fixtures/plugins/workspace-overview/main.js', 'utf8') + '\n// Browser cleanup probe\n';
|
||||||
|
await page.context().addInitScript(({ manifest, pluginCode }) => {
|
||||||
|
window.isTauri = true;
|
||||||
|
const root = "C:\\smoke-workspace";
|
||||||
|
const files = new Map([
|
||||||
|
["notes/welcome.md", "---\ntitle: Welcome\n---\n\n# Working notes\n\nFirst paragraph.\n\n- [ ] A task\n\n[[second]]\n"],
|
||||||
|
["notes/second.md", "# Second note\n"],
|
||||||
|
["src/hello.py", "print('hello')\n"],
|
||||||
|
]);
|
||||||
|
const callbacks = new Map();
|
||||||
|
const listeners = new Map();
|
||||||
|
let sequence = 0;
|
||||||
|
const calls = [];
|
||||||
|
let installed = [];
|
||||||
|
let removalPrepared = false;
|
||||||
|
const data = { preserved: true };
|
||||||
|
const path = "C:\\AppData\\RuneStone\\plugins\\" + manifest.id;
|
||||||
|
const snapshot = () => ({ root: "C:\\AppData\\RuneStone\\plugins", plugins: installed });
|
||||||
|
const emit = (event, payload) => {
|
||||||
|
for (const id of listeners.get(event) || []) callbacks.get(id)?.({ event, id, payload });
|
||||||
|
};
|
||||||
|
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 = {}) => {
|
||||||
|
calls.push({ command, args });
|
||||||
|
if (command === "plugin:window|is_maximized") return false;
|
||||||
|
if (command.startsWith("plugin:window|")) return null;
|
||||||
|
if (command === "plugins_snapshot") return snapshot();
|
||||||
|
if (command === "plugins_choose") return [{ token: 'candidate', source: 'C:/Downloads/overview.runestone-plugin', manifest, error: null }];
|
||||||
|
if (command === "plugins_cancel") { removalPrepared = false; return; }
|
||||||
|
if (command === "plugins_install") {
|
||||||
|
installed = [{ manifest, hash: 'reviewed-hash', enabled: args.enabled, path, error: null, removal: false }];
|
||||||
|
emit('plugins-changed', null); return [{ name: manifest.name, error: null }];
|
||||||
|
}
|
||||||
|
if (command === "plugins_set_enabled") {
|
||||||
|
installed[0].enabled = args.enabled;
|
||||||
|
emit('plugins-changed', null); return;
|
||||||
|
}
|
||||||
|
if (command === "plugins_load") { window.__TEST__.cleaned = false; window.__TEST__.released = false; return pluginCode.replace('export function activate(api) {', 'export function activate(api) { api.onDispose(() => { window.__TEST__.cleaned = true; });'); }
|
||||||
|
if (command === "plugins_release") { window.__TEST__.released = true; return; }
|
||||||
|
if (command === "plugins_data") return JSON.stringify(data);
|
||||||
|
if (command === "plugins_reveal") return;
|
||||||
|
if (command === "plugins_prepare_remove") { removalPrepared = true; return { token: 'remove-plan', plugin: installed[0] }; }
|
||||||
|
if (command === "plugins_remove") {
|
||||||
|
if (!removalPrepared) throw Error('Missing removal plan');
|
||||||
|
removalPrepared = false;
|
||||||
|
installed[0].enabled = false; emit('plugins-changed', null);
|
||||||
|
for (let i=0; i<100 && !window.__TEST__.released; i++) await new Promise(resolve => setTimeout(resolve, 50));
|
||||||
|
if (!window.__TEST__.cleaned || !window.__TEST__.released) throw Error('Cleanup was not acknowledged');
|
||||||
|
installed = []; emit('plugins-changed', null); return;
|
||||||
|
}
|
||||||
|
if (command === "plugin:event|listen") {
|
||||||
|
const list = listeners.get(args.event) || []; list.push(args.handler); listeners.set(args.event, list); return args.handler;
|
||||||
|
}
|
||||||
|
if (command === "plugin:event|unlisten") { callbacks.delete(args.eventId); return; }
|
||||||
|
if (command === "workspace_last_path") return root;
|
||||||
|
if (command === "workspace_open") return { root, name: "smoke-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_write") {
|
||||||
|
if (args.expected !== undefined && files.get(args.rel) !== args.expected) throw new Error("Save blocked: file changed on disk");
|
||||||
|
files.set(args.rel, args.contents); emit("workspace-event", { root, kind: "modify", paths: [args.rel] }); return;
|
||||||
|
}
|
||||||
|
if (command === "workspace_list") {
|
||||||
|
const prefix = args.rel ? args.rel + "/" : "";
|
||||||
|
const entries = new Map();
|
||||||
|
for (const path of files.keys()) {
|
||||||
|
if (!path.startsWith(prefix) || path.startsWith(".runestone/")) continue;
|
||||||
|
const tail = path.slice(prefix.length); const name = tail.split("/")[0];
|
||||||
|
entries.set(name, { name, rel_path: prefix + name, kind: tail.includes("/") ? "folder" : "file" });
|
||||||
|
}
|
||||||
|
return [...entries.values()];
|
||||||
|
}
|
||||||
|
if (command === "workspace_create") { if (files.has(args.rel)) throw new Error("exists"); files.set(args.rel, ""); return; }
|
||||||
|
if (command === "workspace_search") return [];
|
||||||
|
if (command === "pty_profiles") return [{ id: "powershell", title: "PowerShell", kind: "powershell" }];
|
||||||
|
if (command === "pty_open") {
|
||||||
|
const data = [...new TextEncoder().encode("READY 🪨\r\n\x1b[6n")];
|
||||||
|
emit("pty-data", { id: args.id, data: data.slice(0, 8) });
|
||||||
|
emit("pty-data", { id: args.id, data: data.slice(8) });
|
||||||
|
await new Promise(resolve => setTimeout(resolve, 50));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (command.startsWith("pty_")) return;
|
||||||
|
if (command === "plugin:dialog|message") return "Cancel";
|
||||||
|
throw new Error(`Unhandled IPC: ${command}`);
|
||||||
|
},
|
||||||
|
};
|
||||||
|
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) };
|
||||||
|
window.__TEST__ = { files, calls, emit, root, data };
|
||||||
|
}, { manifest, pluginCode });
|
||||||
|
|
||||||
|
async function quickOpen(name) {
|
||||||
|
await page.keyboard.press("Control+p");
|
||||||
|
await page.getByRole("textbox", { name: "Find a file" }).fill(name);
|
||||||
|
await page.getByRole("dialog").getByRole("button").filter({ hasText: name }).first().click();
|
||||||
|
await page.locator('.live-writer').waitFor();
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
const settingsDialog = page.getByRole('dialog', { name: 'Settings', exact: true });
|
||||||
|
const count = command => page.evaluate(command => window.__TEST__.calls.filter(call => call.command === command).length, command);
|
||||||
|
async function settings() {
|
||||||
|
await page.getByRole('button', { name: 'Settings (Ctrl+,)', exact: true }).click();
|
||||||
|
await settingsDialog.getByRole('button', { name: 'Plug-ins', exact: true }).click();
|
||||||
|
}
|
||||||
|
async function uninstall() { await settingsDialog.getByRole('button', { name: 'Uninstall Workspace overview', exact: true }).click(); }
|
||||||
|
try {
|
||||||
|
await page.goto(process.env.SMOKE_URL || 'http://127.0.0.1:1420');
|
||||||
|
await page.getByText('smoke-workspace', { exact: true }).waitFor();
|
||||||
|
await settings();
|
||||||
|
await settingsDialog.getByRole('button', { name: 'Install from file', exact: true }).click();
|
||||||
|
let review = page.getByRole('dialog', { name: 'Review plugin installation', exact: true });
|
||||||
|
await review.getByRole('button', { name: 'Cancel', exact: true }).click();
|
||||||
|
assert.equal(await count('plugins_install'), 0);
|
||||||
|
await settingsDialog.getByRole('button', { name: 'Install from folder', exact: true }).click();
|
||||||
|
await review.getByRole('button', { name: 'Install and enable', exact: true }).click();
|
||||||
|
await settingsDialog.getByRole('switch', { name: 'Workspace overview', exact: true }).waitFor();
|
||||||
|
assert(await settingsDialog.getByRole('switch', { name: 'Workspace overview', exact: true }).isChecked());
|
||||||
|
await page.screenshot({ path: '.audit/plugin-manager-installed.png' });
|
||||||
|
await page.keyboard.press('Escape');
|
||||||
|
await page.getByRole('button', { name: 'Plugin commands and views', exact: true }).click();
|
||||||
|
await page.getByRole('button', { name: /Show workspace overview/ }).click();
|
||||||
|
const view = page.getByRole('dialog', { name: 'Workspace overview', exact: true });
|
||||||
|
await view.getByText(/files and folders in this workspace/).waitFor();
|
||||||
|
await view.getByRole('button', { name: 'Close plugin view', exact: true }).click();
|
||||||
|
await settings();
|
||||||
|
await uninstall();
|
||||||
|
const confirmation = page.getByRole('dialog', { name: 'Uninstall Workspace overview?', exact: true });
|
||||||
|
assert(await confirmation.getByRole('button', { name: 'Cancel', exact: true }).evaluate(el => el === document.activeElement));
|
||||||
|
assert.equal(await confirmation.getByRole('button', { name: 'Continue', exact: true }).count(), 0);
|
||||||
|
await confirmation.getByRole('button', { name: 'Cancel', exact: true }).click();
|
||||||
|
assert.equal(await count('plugins_remove'), 0);
|
||||||
|
assert(await settingsDialog.getByRole('switch', { name: 'Workspace overview', exact: true }).isChecked());
|
||||||
|
await uninstall();
|
||||||
|
await confirmation.waitFor();
|
||||||
|
await page.keyboard.press('Escape');
|
||||||
|
assert(await settingsDialog.isVisible());
|
||||||
|
assert(await settingsDialog.getByRole('switch', { name: 'Workspace overview', exact: true }).isChecked());
|
||||||
|
assert.equal(await count('plugins_remove'), 0);
|
||||||
|
await uninstall();
|
||||||
|
await confirmation.waitFor();
|
||||||
|
await page.screenshot({ path: '.audit/plugin-uninstall-confirmation.png' });
|
||||||
|
await confirmation.getByRole('button', { name: 'Uninstall and delete files', exact: true }).click();
|
||||||
|
await settingsDialog.getByText('No plugins installed.', { exact: true }).waitFor();
|
||||||
|
assert.equal(await count('plugins_remove'), 1);
|
||||||
|
assert.equal(await page.evaluate(() => window.__TEST__.cleaned), true);
|
||||||
|
assert.equal(await page.evaluate(() => window.__TEST__.data.preserved), true);
|
||||||
|
await page.keyboard.press('Escape');
|
||||||
|
assert.equal(await page.getByRole('button', { name: 'Plugin commands and views', exact: true }).count(), 0);
|
||||||
|
await page.setViewportSize({ width: 590, height: 820 });
|
||||||
|
await settings();
|
||||||
|
await page.screenshot({ path: '.audit/plugin-manager-narrow.png' });
|
||||||
|
assert.equal(await settingsDialog.evaluate(element => element.scrollWidth > element.clientWidth), false);
|
||||||
|
assert.deepEqual(errors, []);
|
||||||
|
console.log('External plugin smoke passed: file/folder review, code loading, command/view, one confirmation, cancellation, focus, cleanup, and uninstall.');
|
||||||
|
} finally { await browser.close(); }
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
import { readFile } from "node:fs/promises";
|
||||||
|
|
||||||
|
/** Load the actual compiled packages through the production Blob module loader. */
|
||||||
|
export async function mockFeaturePlugins(surface) {
|
||||||
|
const packages = await Promise.all(["terminal", "table-formulas"].map(async name => {
|
||||||
|
const root = new URL(`../plugin-packages/${name}/`, import.meta.url);
|
||||||
|
return {
|
||||||
|
manifest: JSON.parse(await readFile(new URL("plugin.json", root), "utf8")),
|
||||||
|
code: await readFile(new URL("main.js", root), "utf8"),
|
||||||
|
css: name === "terminal" ? await readFile(new URL("style.css", root), "base64") : "",
|
||||||
|
};
|
||||||
|
}));
|
||||||
|
await surface.addInitScript(packages => {
|
||||||
|
const key = "test.installed-plugins";
|
||||||
|
const root = "C:\\AppData\\RuneStone\\plugins";
|
||||||
|
const defaults = packages.map(item => ({ manifest: item.manifest, hash: "test-hash", enabled: true, path: root + "\\" + item.manifest.id, error: null, removal: false }));
|
||||||
|
const read = () => JSON.parse(localStorage.getItem(key) || JSON.stringify(defaults));
|
||||||
|
const write = rows => { localStorage.setItem(key, JSON.stringify(rows)); window.__TEST__?.emit("plugins-changed", {}); };
|
||||||
|
if (!localStorage.getItem(key)) localStorage.setItem(key, JSON.stringify(defaults));
|
||||||
|
window.addEventListener("storage", event => { if (event.key === key) window.__TEST__?.emit("plugins-changed", {}); });
|
||||||
|
const original = window.__TAURI_INTERNALS__.invoke;
|
||||||
|
window.__TAURI_INTERNALS__.invoke = async (command, args = {}) => {
|
||||||
|
if (!command.startsWith("plugins_")) return original(command, args);
|
||||||
|
window.__TEST__?.calls.push({ command, args });
|
||||||
|
if (command === "plugins_snapshot") return { root, plugins: read() };
|
||||||
|
if (command === "plugins_load") return packages.find(item => item.manifest.id === args.id).code;
|
||||||
|
if (command === "plugins_asset") return packages.find(item => item.manifest.id === args.id).css;
|
||||||
|
if (command === "plugins_set_enabled") { write(read().map(item => item.manifest.id === args.id ? { ...item, enabled: args.enabled } : item)); return; }
|
||||||
|
if (command === "plugins_prepare_remove") return { token: args.id, plugin: read().find(item => item.manifest.id === args.id) };
|
||||||
|
if (command === "plugins_remove") { write(read().filter(item => item.manifest.id !== args.token)); return; }
|
||||||
|
if (command === "plugins_data") return "null";
|
||||||
|
if (["plugins_release", "plugins_cancel", "plugins_reveal"].includes(command)) return;
|
||||||
|
throw new Error(`Unhandled plugin IPC: ${command}`);
|
||||||
|
};
|
||||||
|
}, packages);
|
||||||
|
}
|
||||||
@@ -0,0 +1,194 @@
|
|||||||
|
import { mockFeaturePlugins } from "./pluginMocks.mjs";
|
||||||
|
// Run against `pnpm dev`. PLAYWRIGHT_MODULE may point to a shared installation.
|
||||||
|
import { createRequire } from "node:module";
|
||||||
|
import assert from "node:assert/strict";
|
||||||
|
const require = createRequire(import.meta.url);
|
||||||
|
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright");
|
||||||
|
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
|
||||||
|
const context = await browser.newContext({ viewport: { width: 1440, height: 1000 } });
|
||||||
|
const page = await context.newPage();
|
||||||
|
page.setDefaultTimeout(10000);
|
||||||
|
const errors = [];
|
||||||
|
page.on("console", message => { if (message.type() === "error" || message.type() === "warning") console.log(message.type(), message.text()); });
|
||||||
|
page.on("pageerror", error => errors.push(error.message));
|
||||||
|
await page.context().addInitScript(() => {
|
||||||
|
window.isTauri = true;
|
||||||
|
const root = "C:\\smoke-workspace";
|
||||||
|
const files = new Map([
|
||||||
|
["notes/welcome.md", "---\ntitle: Welcome\n---\n\n# Working notes\n\nFirst paragraph.\n\n- [ ] A task\n\n[[second]]\n"],
|
||||||
|
["notes/second.md", "# Second note\n"],
|
||||||
|
["src/hello.py", "print('hello')\n"],
|
||||||
|
]);
|
||||||
|
const callbacks = new Map();
|
||||||
|
const listeners = new Map();
|
||||||
|
let sequence = 0;
|
||||||
|
const calls = [];
|
||||||
|
const emit = (event, payload) => {
|
||||||
|
for (const id of listeners.get(event) || []) callbacks.get(id)?.({ event, id, payload });
|
||||||
|
};
|
||||||
|
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 = {}) => {
|
||||||
|
calls.push({ command, args });
|
||||||
|
if (command === "plugin:event|listen") {
|
||||||
|
const list = listeners.get(args.event) || []; list.push(args.handler); listeners.set(args.event, list); return args.handler;
|
||||||
|
}
|
||||||
|
if (command === "plugin:event|unlisten") { callbacks.delete(args.eventId); return; }
|
||||||
|
if (command === "workspace_last_path") return root;
|
||||||
|
if (command === "workspace_open") return { root, name: "smoke-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_write") {
|
||||||
|
if (args.expected !== undefined && files.get(args.rel) !== args.expected) throw new Error("Save blocked: file changed on disk");
|
||||||
|
files.set(args.rel, args.contents); emit("workspace-event", { root, kind: "modify", paths: [args.rel] }); return;
|
||||||
|
}
|
||||||
|
if (command === "workspace_list") {
|
||||||
|
const prefix = args.rel ? args.rel + "/" : "";
|
||||||
|
const entries = new Map();
|
||||||
|
for (const path of files.keys()) {
|
||||||
|
if (!path.startsWith(prefix) || path.startsWith(".runestone/")) continue;
|
||||||
|
const tail = path.slice(prefix.length); const name = tail.split("/")[0];
|
||||||
|
entries.set(name, { name, rel_path: prefix + name, kind: tail.includes("/") ? "folder" : "file" });
|
||||||
|
}
|
||||||
|
return [...entries.values()];
|
||||||
|
}
|
||||||
|
if (command === "workspace_create") { if (files.has(args.rel)) throw new Error("exists"); files.set(args.rel, ""); return; }
|
||||||
|
if (command === "workspace_search") return [];
|
||||||
|
if (command === "pty_profiles") return [{ id: "powershell", title: "PowerShell", kind: "powershell" }];
|
||||||
|
if (command === "pty_open") {
|
||||||
|
const data = [...new TextEncoder().encode("READY 🪨\r\n\x1b[6n")];
|
||||||
|
emit("pty-data", { id: args.id, data: data.slice(0, 8) });
|
||||||
|
emit("pty-data", { id: args.id, data: data.slice(8) });
|
||||||
|
await new Promise(resolve => setTimeout(resolve, 50));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (command.startsWith("pty_")) return;
|
||||||
|
if (command === "plugin:dialog|message") return "Cancel";
|
||||||
|
throw new Error(`Unhandled IPC: ${command}`);
|
||||||
|
},
|
||||||
|
};
|
||||||
|
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) };
|
||||||
|
window.__TEST__ = { files, calls, emit, root };
|
||||||
|
});
|
||||||
|
await mockFeaturePlugins(page.context());
|
||||||
|
|
||||||
|
|
||||||
|
async function quickOpen(name) {
|
||||||
|
await page.keyboard.press("Control+p");
|
||||||
|
await page.getByRole("textbox", { name: "Find a file" }).fill(name);
|
||||||
|
await page.getByRole("dialog").getByRole("button").filter({ hasText: name }).first().click();
|
||||||
|
await page.locator('.live-writer').waitFor();
|
||||||
|
}
|
||||||
|
|
||||||
|
const source = '# Formulas\n\n| A | B |\n| --- | --- |\n| 2 | =A2*3 |\n\nAfter.\n';
|
||||||
|
const table = page.locator('.live-writer table');
|
||||||
|
const dialog = page.getByRole('dialog', { name: 'Settings', exact: true });
|
||||||
|
const switchFor = name => dialog.getByRole('switch', { name, exact: true });
|
||||||
|
async function settings() {
|
||||||
|
await page.getByRole('button', { name: 'Settings (Ctrl+,)', exact: true }).click();
|
||||||
|
await dialog.getByRole('button', { name: 'Plug-ins', exact: true }).click();
|
||||||
|
}
|
||||||
|
async function closeSettings() {
|
||||||
|
await page.waitForFunction(() => [...document.querySelectorAll('input[role="switch"]')].every(input => !input.disabled));
|
||||||
|
await page.keyboard.press('Escape');
|
||||||
|
await dialog.waitFor({ state: 'hidden' });
|
||||||
|
}
|
||||||
|
const count = command => page.evaluate(command => window.__TEST__.calls.filter(call => call.command === command).length, command);
|
||||||
|
try {
|
||||||
|
await page.goto(process.env.SMOKE_URL || 'http://127.0.0.1:1420');
|
||||||
|
await page.getByText('smoke-workspace', { exact: true }).waitFor();
|
||||||
|
await page.evaluate(text => window.__TEST__.files.set('formulas.md', text), source);
|
||||||
|
await quickOpen('formulas.md');
|
||||||
|
await table.waitFor();
|
||||||
|
assert.equal(await table.locator('.md-table-formula').innerText(), '6');
|
||||||
|
await settings();
|
||||||
|
await switchFor('Table formulas').uncheck();
|
||||||
|
await closeSettings();
|
||||||
|
await page.waitForFunction(() => !document.querySelector('.md-table-formula'));
|
||||||
|
assert.match(await table.innerText(), /=A2\*3/);
|
||||||
|
assert.equal(await page.locator('.table-formula-tools').count(), 0);
|
||||||
|
await table.locator('td').last().click();
|
||||||
|
await page.locator('.writer-cell-editor').fill('=A2*4');
|
||||||
|
await page.keyboard.press('Enter');
|
||||||
|
await settings();
|
||||||
|
await switchFor('Table formulas').check();
|
||||||
|
await closeSettings();
|
||||||
|
await page.waitForFunction(() => document.querySelector('.md-table-formula')?.textContent === '8');
|
||||||
|
await page.getByRole('group', { name: 'Document view', exact: true }).getByRole('button', { pressed: true }).press('ArrowRight');
|
||||||
|
const preview = page.locator('.md-page table').first();
|
||||||
|
await preview.locator('.md-table-formula').waitFor();
|
||||||
|
await settings();
|
||||||
|
await switchFor('Table formulas').uncheck();
|
||||||
|
await closeSettings();
|
||||||
|
await page.waitForFunction(() => !document.querySelector('.md-page .md-table-formula'));
|
||||||
|
assert.match(await preview.innerText(), /=A2\*4/);
|
||||||
|
await settings();
|
||||||
|
await switchFor('Table formulas').check();
|
||||||
|
await closeSettings();
|
||||||
|
await preview.locator('.md-table-formula').waitFor();
|
||||||
|
assert.equal(await preview.locator('.md-table-formula').innerText(), '8');
|
||||||
|
await page.keyboard.press('Control+s');
|
||||||
|
await page.waitForFunction(() => window.__TEST__.files.get('formulas.md').includes('=A2*4'));
|
||||||
|
assert(!await page.evaluate(() => window.__TEST__.files.get('formulas.md').includes('>8<')));
|
||||||
|
|
||||||
|
await page.getByRole('button', { name: 'Terminal', exact: true }).click();
|
||||||
|
await page.waitForFunction(() => window.__TEST__.calls.some(call => call.command === 'pty_open'));
|
||||||
|
await settings();
|
||||||
|
await switchFor('Terminal').uncheck();
|
||||||
|
await page.waitForFunction(() => window.__TEST__.calls.some(call => call.command === 'pty_close'));
|
||||||
|
await page.screenshot({ path: '.audit/plugins-settings.png' });
|
||||||
|
await closeSettings();
|
||||||
|
assert.equal(await page.getByRole('button', { name: 'Terminal', exact: true }).count(), 0);
|
||||||
|
const opened = await count('pty_open');
|
||||||
|
await page.keyboard.press('Control+j');
|
||||||
|
assert.equal(await count('pty_open'), opened);
|
||||||
|
await page.reload();
|
||||||
|
await page.getByText('smoke-workspace', { exact: true }).waitFor();
|
||||||
|
assert.equal(await page.getByRole('button', { name: 'Terminal', exact: true }).count(), 0);
|
||||||
|
await settings();
|
||||||
|
assert(!await switchFor('Terminal').isChecked());
|
||||||
|
|
||||||
|
const standalone = await page.context().newPage();
|
||||||
|
await standalone.goto((process.env.SMOKE_URL || 'http://127.0.0.1:1420') + '?terminalWindow=C%3A%5Csmoke-workspace');
|
||||||
|
await standalone.getByText(/Install and enable the Terminal plugin/).waitFor();
|
||||||
|
await switchFor('Terminal').check();
|
||||||
|
await standalone.locator('.xterm').waitFor();
|
||||||
|
await standalone.waitForFunction(() => window.__TEST__.calls.some(call => call.command === 'pty_open'));
|
||||||
|
await switchFor('Terminal').uncheck();
|
||||||
|
await standalone.getByText(/Install and enable the Terminal plugin/).waitFor();
|
||||||
|
await standalone.waitForFunction(() => window.__TEST__.calls.some(call => call.command === 'pty_close'));
|
||||||
|
await standalone.close();
|
||||||
|
await switchFor('Terminal').check();
|
||||||
|
await closeSettings();
|
||||||
|
await page.getByRole('button', { name: 'Terminal', exact: true }).click();
|
||||||
|
await page.locator('.xterm').waitFor();
|
||||||
|
await page.evaluate(text => window.__TEST__.files.set('formulas.md', text.replace('=A2*3', '=A2*4')), source);
|
||||||
|
await page.getByRole('button', { name: 'Terminal', exact: true }).focus();
|
||||||
|
await quickOpen('formulas.md');
|
||||||
|
await settings();
|
||||||
|
assert.equal(await dialog.getByRole('heading', { name: 'Bundled plugins' }).count(), 0);
|
||||||
|
for (const name of ['Terminal', 'Table formulas']) {
|
||||||
|
await page.waitForFunction(() => [...document.querySelectorAll('input[role="switch"]')].every(input => !input.disabled));
|
||||||
|
await dialog.getByRole('button', { name: `Uninstall ${name}`, exact: true }).click();
|
||||||
|
const confirmation = page.getByRole('dialog', { name: `Uninstall ${name}?`, exact: true });
|
||||||
|
await confirmation.getByRole('button', { name: 'Uninstall and delete files', exact: true }).click();
|
||||||
|
await confirmation.waitFor({ state: 'hidden' });
|
||||||
|
await switchFor(name).waitFor({ state: 'detached' });
|
||||||
|
}
|
||||||
|
await closeSettings();
|
||||||
|
await page.waitForFunction(() => !document.querySelector('.md-table-formula') && !document.querySelector('.xterm'));
|
||||||
|
assert.equal(await page.getByRole('button', { name: 'Terminal', exact: true }).count(), 0);
|
||||||
|
assert.match(await table.innerText(), /=A2\*4/);
|
||||||
|
await page.reload();
|
||||||
|
await page.getByText('smoke-workspace', { exact: true }).waitFor();
|
||||||
|
await settings();
|
||||||
|
await dialog.getByText('No plugins installed.', { exact: true }).waitFor();
|
||||||
|
assert.deepEqual(errors, []);
|
||||||
|
console.log('Plugin smoke passed: formulas, source preservation, terminal shutdown, persistence, shortcuts, cross-window enable controls, removal, and no automatic restoration.');
|
||||||
|
} catch (error) {
|
||||||
|
await page.screenshot({ path: ".audit/plugins-failure.png" });
|
||||||
|
console.log(await page.locator('.md-page').allTextContents());
|
||||||
|
console.log(errors);
|
||||||
|
throw error;
|
||||||
|
} finally { await browser.close(); }
|
||||||
@@ -0,0 +1,62 @@
|
|||||||
|
import test from "node:test";
|
||||||
|
import assert from "node:assert/strict";
|
||||||
|
import { ContributionRegistry, pluginHost } from "../src/lib/plugins/registry.ts";
|
||||||
|
import { ExternalSession } from "../src/lib/plugins/externalSession.ts";
|
||||||
|
import { activate } from "../plugins/table-formulas/index.ts";
|
||||||
|
import { renderMarkdownHtml, renderMarkdownSections } from "../src/lib/workspace/noteHtml.ts";
|
||||||
|
import type { PluginApi } from "../src/lib/plugins/sdk.ts";
|
||||||
|
|
||||||
|
const services = {
|
||||||
|
workspace: { list: async () => [], read: async () => "", write: async () => {} },
|
||||||
|
settings: { read: async () => null, write: async () => {} },
|
||||||
|
assets: { read: async () => new Uint8Array() },
|
||||||
|
};
|
||||||
|
test("core starts without optional features and formula packages preserve source when stopped", async () => {
|
||||||
|
assert.equal(pluginHost.get("terminal"), undefined);
|
||||||
|
assert.equal(pluginHost.get("tableFormulas"), undefined);
|
||||||
|
const source = "| A | B |\n| --- | --- |\n| 2 | =A2*3 |\n";
|
||||||
|
assert.doesNotMatch(renderMarkdownHtml(source, new Map()), /md-table-formula/);
|
||||||
|
const session = new ExternalSession("runestone.table-formulas", services, () => {}, () => {});
|
||||||
|
await session.start({ activate });
|
||||||
|
const enabled = renderMarkdownHtml(source, new Map());
|
||||||
|
assert.match(enabled, />6<\/span>/);
|
||||||
|
await session.stop();
|
||||||
|
for (const html of [renderMarkdownHtml(source, new Map()), ...renderMarkdownSections(source, new Map()).map(section => section.html)]) {
|
||||||
|
assert.doesNotMatch(html, /md-table-formula/);
|
||||||
|
assert.match(html, /=A2\*3/);
|
||||||
|
assert.match(html, /<table>/);
|
||||||
|
}
|
||||||
|
const next = new ExternalSession("runestone.table-formulas", services, () => {}, () => {});
|
||||||
|
await next.start({ activate });
|
||||||
|
assert.equal(renderMarkdownHtml(source, new Map()), enabled);
|
||||||
|
await next.stop();
|
||||||
|
});
|
||||||
|
|
||||||
|
test("package contribution conflicts preserve the first owner and revoke access before cleanup", async () => {
|
||||||
|
const registry = new ContributionRegistry();
|
||||||
|
const first = new ExternalSession("first", services, () => {}, () => {}, registry);
|
||||||
|
const second = new ExternalSession("second", services, () => {}, () => {}, registry);
|
||||||
|
let api!: PluginApi;
|
||||||
|
await first.start({ activate(value) { api = value; activate(api); } });
|
||||||
|
const contribution = registry.get("tableFormulas");
|
||||||
|
await assert.rejects(second.start({ activate }), /already registered/);
|
||||||
|
await second.stop();
|
||||||
|
assert.equal(registry.get("tableFormulas"), contribution);
|
||||||
|
api.onDispose(() => {
|
||||||
|
assert.equal(registry.get("tableFormulas"), undefined);
|
||||||
|
assert.throws(() => api.contribute("tableFormulas", contribution!), /disabled/);
|
||||||
|
});
|
||||||
|
await first.stop();
|
||||||
|
});
|
||||||
|
|
||||||
|
test("partial activation and failed cleanup cannot retain feature contributions", async () => {
|
||||||
|
const registry = new ContributionRegistry();
|
||||||
|
const session = new ExternalSession("failed", services, () => {}, () => {}, registry);
|
||||||
|
await assert.rejects(session.start({ activate(api) {
|
||||||
|
activate(api);
|
||||||
|
api.onDispose(() => { throw new Error("Cleanup failed"); });
|
||||||
|
throw new Error("Activation failed");
|
||||||
|
} }), /Activation failed/);
|
||||||
|
await assert.rejects(session.stop(), /Cleanup failed/);
|
||||||
|
assert.equal(registry.get("tableFormulas"), undefined);
|
||||||
|
});
|
||||||
@@ -0,0 +1,165 @@
|
|||||||
|
// Run against pnpm dev with PLAYWRIGHT_MODULE and CHROME_PATH if needed.
|
||||||
|
import { createRequire } from "node:module";
|
||||||
|
import { mkdirSync, readFileSync } from "node:fs";
|
||||||
|
import assert from "node:assert/strict";
|
||||||
|
const require = createRequire(import.meta.url);
|
||||||
|
const { version } = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8"));
|
||||||
|
mkdirSync(".audit", { recursive: true });
|
||||||
|
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright");
|
||||||
|
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
|
||||||
|
const context = await browser.newContext({ viewport: { width: 1100, height: 800 } });
|
||||||
|
const page = await context.newPage();
|
||||||
|
const errors = [];
|
||||||
|
page.on("pageerror", error => errors.push(error.message));
|
||||||
|
await context.addInitScript(() => {
|
||||||
|
window.isTauri = true;
|
||||||
|
const disk = { "note.txt": "Original note" };
|
||||||
|
const writes = [];
|
||||||
|
window.__TEST__ = { disk, writes };
|
||||||
|
window.__TAURI_INTERNALS__ = {
|
||||||
|
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
|
||||||
|
transformCallback: () => 1, unregisterCallback: () => {},
|
||||||
|
invoke: async (command, args = {}) => {
|
||||||
|
if (command === "plugins_snapshot") return { root: "D:\\AppData\\RuneStone\\plugins", plugins: [] };
|
||||||
|
if (command === "workspace_last_path") return "D:\\Notes";
|
||||||
|
if (command === "workspace_open") return { root: "D:\\Notes", name: "Notes", watch_mode: "native" };
|
||||||
|
if (command === "workspace_list") return args.rel ? [] : [{ name: "note.txt", rel_path: "note.txt", kind: "file" }];
|
||||||
|
if (command === "workspace_read") { if (args.rel in disk) return disk[args.rel]; throw "Missing file"; }
|
||||||
|
if (command === "workspace_write") { disk[args.rel] = args.contents; writes.push(args); return; }
|
||||||
|
return null;
|
||||||
|
},
|
||||||
|
};
|
||||||
|
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} };
|
||||||
|
});
|
||||||
|
const url = process.env.SMOKE_URL || "http://127.0.0.1:1420";
|
||||||
|
const settings = page.getByRole("dialog", { name: "Settings", exact: true });
|
||||||
|
const trigger = page.getByRole("button", { name: "Settings (Ctrl+,)", exact: true });
|
||||||
|
const interval = settings.getByRole("spinbutton", { name: "Auto-save interval" });
|
||||||
|
const enabled = settings.getByRole("switch", { name: "Auto-save", exact: true });
|
||||||
|
async function changeSeconds(value) {
|
||||||
|
await interval.fill(String(value));
|
||||||
|
await interval.press("Tab");
|
||||||
|
}
|
||||||
|
async function edit(value) {
|
||||||
|
await page.evaluate(async text => {
|
||||||
|
const { monaco } = await import("/src/lib/editor/monacoEnv.ts");
|
||||||
|
monaco.editor.getEditors().find(editor => editor.getDomNode()?.isConnected).setValue(text);
|
||||||
|
}, value);
|
||||||
|
}
|
||||||
|
const writes = () => page.evaluate(() => window.__TEST__.writes.length);
|
||||||
|
try {
|
||||||
|
await page.clock.install();
|
||||||
|
await page.goto(url);
|
||||||
|
await page.locator(".ws").filter({ hasText: "Notes" }).waitFor();
|
||||||
|
await trigger.click();
|
||||||
|
assert.equal(await interval.inputValue(), "5");
|
||||||
|
assert(await enabled.isChecked());
|
||||||
|
await changeSeconds(2);
|
||||||
|
await settings.getByRole("status").filter({ hasText: "Changes saved." }).waitFor();
|
||||||
|
await page.keyboard.press("Escape");
|
||||||
|
assert(await trigger.evaluate(element => element === document.activeElement), "Closing restores focus");
|
||||||
|
await page.reload();
|
||||||
|
await trigger.click();
|
||||||
|
assert.equal(await interval.inputValue(), "2", "Interval survives reload");
|
||||||
|
await changeSeconds(0);
|
||||||
|
await settings.getByRole("alert").filter({ hasText: "whole number" }).waitFor();
|
||||||
|
assert.equal(await page.evaluate(() => JSON.parse(localStorage.getItem("runestone.settings")).autosaveSeconds), 2);
|
||||||
|
await changeSeconds(2);
|
||||||
|
await settings.getByRole("textbox", { name: "Search settings" }).fill("plugins");
|
||||||
|
await settings.getByText("No plugins installed.", { exact: true }).waitFor();
|
||||||
|
assert(await settings.getByRole("button", { name: "Install from folder", exact: true }).isEnabled());
|
||||||
|
await settings.getByRole("textbox", { name: "Search settings" }).fill("no such setting");
|
||||||
|
await settings.getByText("No settings found", { exact: true }).waitFor();
|
||||||
|
await settings.getByRole("button", { name: "Clear search" }).click();
|
||||||
|
await page.screenshot({ path: ".audit/settings-general.png" });
|
||||||
|
await page.keyboard.press("Escape");
|
||||||
|
|
||||||
|
await page.keyboard.press("Control+p");
|
||||||
|
await page.getByRole("textbox", { name: "Find a file" }).fill("note.txt");
|
||||||
|
await page.getByRole("dialog").getByRole("button").filter({ hasText: "note.txt" }).first().click();
|
||||||
|
await page.locator(".monaco-editor textarea").waitFor();
|
||||||
|
await page.clock.pauseAt(new Date());
|
||||||
|
await trigger.click();
|
||||||
|
await changeSeconds(3);
|
||||||
|
await page.keyboard.press("Escape");
|
||||||
|
await edit("Saved at three seconds");
|
||||||
|
const before = await writes();
|
||||||
|
await page.clock.runFor(2100);
|
||||||
|
assert.equal(await writes(), before, "Old two-second timer is removed");
|
||||||
|
await page.clock.runFor(1000);
|
||||||
|
assert.equal(await writes(), before + 1, "New interval saves the dirty buffer");
|
||||||
|
await page.clock.runFor(3100);
|
||||||
|
assert.equal(await writes(), before + 1, "Clean files are not rewritten");
|
||||||
|
await trigger.click();
|
||||||
|
await enabled.uncheck();
|
||||||
|
assert(await interval.isDisabled());
|
||||||
|
await page.keyboard.press("Escape");
|
||||||
|
await edit("Manual save while auto-save is disabled");
|
||||||
|
await page.clock.runFor(10000);
|
||||||
|
assert.equal(await writes(), before + 1);
|
||||||
|
await page.keyboard.press("Control+s");
|
||||||
|
await page.waitForFunction(count => window.__TEST__.writes.length === count, before + 2);
|
||||||
|
await page.locator(".monaco-editor textarea").focus();
|
||||||
|
await page.keyboard.press("Control+,");
|
||||||
|
await settings.waitFor();
|
||||||
|
await page.keyboard.press("Escape");
|
||||||
|
await page.locator(".monaco-editor textarea").focus();
|
||||||
|
await page.keyboard.press("F1");
|
||||||
|
await page.getByRole("dialog", { name: "Help and about", exact: true }).waitFor();
|
||||||
|
await page.keyboard.press("Escape");
|
||||||
|
|
||||||
|
const other = await context.newPage();
|
||||||
|
await other.goto(url);
|
||||||
|
await other.getByRole("button", { name: "Settings (Ctrl+,)" }).click();
|
||||||
|
assert.equal(await other.getByRole("spinbutton", { name: "Auto-save interval" }).inputValue(), "3");
|
||||||
|
assert.equal(await other.getByRole("switch", { name: "Auto-save", exact: true }).isChecked(), false);
|
||||||
|
await other.getByRole("button", { name: "Restore defaults" }).click();
|
||||||
|
await page.waitForFunction(() => JSON.parse(localStorage.getItem("runestone.settings")).autosaveEnabled);
|
||||||
|
await trigger.click();
|
||||||
|
await enabled.waitFor();
|
||||||
|
assert(await enabled.isChecked(), "Other windows receive changes");
|
||||||
|
assert.equal(await interval.inputValue(), "5");
|
||||||
|
await page.keyboard.press("Escape");
|
||||||
|
await edit("Auto-save enabled from another window");
|
||||||
|
await page.clock.runFor(5100);
|
||||||
|
assert.equal(await writes(), before + 3);
|
||||||
|
await other.close();
|
||||||
|
|
||||||
|
await trigger.click();
|
||||||
|
await page.evaluate(() => {
|
||||||
|
window.__SET_ITEM__ = Storage.prototype.setItem;
|
||||||
|
Storage.prototype.setItem = () => { throw new Error("Storage unavailable"); };
|
||||||
|
});
|
||||||
|
await changeSeconds(7);
|
||||||
|
await settings.getByRole("alert").filter({ hasText: "Could not save" }).waitFor();
|
||||||
|
await page.evaluate(() => { Storage.prototype.setItem = window.__SET_ITEM__; });
|
||||||
|
await page.keyboard.press("Escape");
|
||||||
|
await trigger.click();
|
||||||
|
assert.equal(await interval.inputValue(), "5", "Failed writes preserve applied settings");
|
||||||
|
await page.keyboard.press("Escape");
|
||||||
|
|
||||||
|
await page.getByRole("button", { name: "Help and about (F1)" }).click();
|
||||||
|
const help = page.getByRole("dialog", { name: "Help and about", exact: true });
|
||||||
|
await help.getByRole("heading", { name: "RuneStone", exact: true }).waitFor();
|
||||||
|
await help.getByText(`Version ${version}`, { exact: false }).waitFor();
|
||||||
|
await page.screenshot({ path: ".audit/settings-help.png" });
|
||||||
|
await page.keyboard.press("Escape");
|
||||||
|
await page.keyboard.press("Control+b");
|
||||||
|
await page.keyboard.press("Control+,");
|
||||||
|
await settings.waitFor();
|
||||||
|
await page.keyboard.press("Escape");
|
||||||
|
await page.keyboard.press("F1");
|
||||||
|
await help.waitFor();
|
||||||
|
await page.keyboard.press("Escape");
|
||||||
|
await page.setViewportSize({ width: 420, height: 650 });
|
||||||
|
await page.keyboard.press("Control+,");
|
||||||
|
await settings.waitFor();
|
||||||
|
assert(await settings.evaluate(el => el.scrollWidth === el.clientWidth), "Narrow layout fits");
|
||||||
|
await page.screenshot({ path: ".audit/settings-narrow.png" });
|
||||||
|
for (let i = 0; i < 12; i++) {
|
||||||
|
await page.keyboard.press("Tab");
|
||||||
|
assert(await settings.evaluate(el => el.contains(document.activeElement)), "Focus stays in the modal");
|
||||||
|
}
|
||||||
|
assert.deepEqual(errors, []);
|
||||||
|
console.log("Settings smoke passed: timer changes, disabled auto-save, manual saves, persistence, cross-window updates, validation, storage failure, help, search, focus, shortcuts, and narrow layout.");
|
||||||
|
} finally { await browser.close(); }
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
import { test } from "node:test";
|
||||||
|
import assert from "node:assert/strict";
|
||||||
|
import { DEFAULT_SETTINGS, SETTINGS_KEY, parseSettings, saveSettings } from "../src/lib/workspace/settings.ts";
|
||||||
|
|
||||||
|
test("missing or damaged preferences keep safe defaults", () => {
|
||||||
|
for (const raw of [null, "{broken", "null", "[]", "42", '"text"']) {
|
||||||
|
assert.deepEqual(parseSettings(raw), DEFAULT_SETTINGS);
|
||||||
|
}
|
||||||
|
for (const autosaveSeconds of [0, -1, 301, 1.5, "10", null]) {
|
||||||
|
assert.deepEqual(parseSettings(JSON.stringify({ autosaveEnabled: false, autosaveSeconds })), { autosaveEnabled: false, autosaveSeconds: 5 });
|
||||||
|
}
|
||||||
|
assert.deepEqual(parseSettings('{"autosaveEnabled":"false","autosaveSeconds":10}'), { autosaveEnabled: true, autosaveSeconds: 10 });
|
||||||
|
});
|
||||||
|
|
||||||
|
test("preferences persist and load at both interval limits", () => {
|
||||||
|
const store = new Map<string, string>();
|
||||||
|
for (const autosaveSeconds of [1, 23, 300]) {
|
||||||
|
const settings = { autosaveEnabled: false, autosaveSeconds };
|
||||||
|
saveSettings({ setItem: (key, value) => { store.set(key, value); } }, settings);
|
||||||
|
assert.deepEqual(parseSettings(store.get(SETTINGS_KEY)!), settings);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test("invalid changes never reach storage and storage failures reach the caller", () => {
|
||||||
|
let writes = 0;
|
||||||
|
const storage = { setItem: () => { writes++; } };
|
||||||
|
for (const autosaveSeconds of [NaN, Infinity, 0, 301, 2.5]) {
|
||||||
|
assert.throws(() => saveSettings(storage, { autosaveEnabled: true, autosaveSeconds }));
|
||||||
|
}
|
||||||
|
assert.equal(writes, 0);
|
||||||
|
assert.throws(() => saveSettings({ setItem: () => { throw new Error("Storage unavailable"); } }, { ...DEFAULT_SETTINGS }), /Storage unavailable/);
|
||||||
|
});
|
||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import { mockFeaturePlugins } from "./pluginMocks.mjs";
|
||||||
// Run against `pnpm dev`. PLAYWRIGHT_MODULE may point to a shared installation.
|
// Run against `pnpm dev`. PLAYWRIGHT_MODULE may point to a shared installation.
|
||||||
import { createRequire } from "node:module";
|
import { createRequire } from "node:module";
|
||||||
import assert from "node:assert/strict";
|
import assert from "node:assert/strict";
|
||||||
@@ -69,14 +70,15 @@ await page.addInitScript(() => {
|
|||||||
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) };
|
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) };
|
||||||
window.__TEST__ = { files, calls, emit, root };
|
window.__TEST__ = { files, calls, emit, root };
|
||||||
});
|
});
|
||||||
|
await mockFeaturePlugins(page);
|
||||||
|
|
||||||
|
|
||||||
async function quickOpen(name) {
|
async function quickOpen(name) {
|
||||||
await page.keyboard.press("Control+p");
|
await page.keyboard.press("Control+p");
|
||||||
await page.getByRole("textbox", { name: "Find a file" }).fill(name);
|
await page.getByRole("textbox", { name: "Find a file" }).fill(name);
|
||||||
await page.getByRole("dialog").getByRole("button").filter({ hasText: name }).first().click();
|
await page.getByRole("dialog").getByRole("button").filter({ hasText: name }).first().click();
|
||||||
if (await page.getByRole("button", { name: "Switch to IDE layout (Ctrl E)", exact: true }).count()) {
|
await page.locator('.live-writer').waitFor();
|
||||||
await page.getByRole("button", { name: "Switch to IDE layout (Ctrl E)", exact: true }).click();
|
await page.keyboard.press('Control+e');
|
||||||
}
|
|
||||||
await page.locator(".monaco-editor textarea").waitFor();
|
await page.locator(".monaco-editor textarea").waitFor();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -98,7 +100,7 @@ try {
|
|||||||
window.__TEST__.emit('workspace-event', { root: window.__TEST__.root, kind: 'create', paths: ['formulas.md'] });
|
window.__TEST__.emit('workspace-event', { root: window.__TEST__.root, kind: 'create', paths: ['formulas.md'] });
|
||||||
}, source);
|
}, source);
|
||||||
await quickOpen('formulas.md');
|
await quickOpen('formulas.md');
|
||||||
await page.getByRole('button', { name: 'Switch to writing layout (Ctrl E)', exact: true }).click();
|
await page.keyboard.press('Control+e');
|
||||||
await table.waitFor();
|
await table.waitFor();
|
||||||
assert.equal(await result(1, 3).innerText(), '9.5');
|
assert.equal(await result(1, 3).innerText(), '9.5');
|
||||||
assert.equal(await result(3, 3).innerText(), '17.5');
|
assert.equal(await result(3, 3).innerText(), '17.5');
|
||||||
@@ -172,12 +174,12 @@ try {
|
|||||||
await checkFooter();
|
await checkFooter();
|
||||||
await page.setViewportSize({ width: 1440, height: 1000 });
|
await page.setViewportSize({ width: 1440, height: 1000 });
|
||||||
await page.screenshot({ path: '.audit/table-formulas.png' });
|
await page.screenshot({ path: '.audit/table-formulas.png' });
|
||||||
await page.getByRole('button', { name: 'Switch to IDE layout (Ctrl E)', exact: true }).click();
|
await page.keyboard.press('Control+e');
|
||||||
await page.getByRole('button', { name: 'Switch to writing layout (Ctrl E)', exact: true }).click();
|
await page.keyboard.press('Control+e');
|
||||||
assert.equal(await result(3, 1).innerText(), '12');
|
assert.equal(await result(3, 1).innerText(), '12');
|
||||||
assert.equal(await result(3, 3).innerText(), '58');
|
assert.equal(await result(3, 3).innerText(), '58');
|
||||||
for (const mode of ['Read', 'Split']) {
|
for (const mode of ['Read', 'Split']) {
|
||||||
await page.getByRole('button', { name: mode, exact: true }).click();
|
await page.getByRole('group', { name: 'Document view', exact: true }).getByRole('button', { pressed: true }).press('ArrowRight');
|
||||||
const preview = page.locator('.md-page table').first();
|
const preview = page.locator('.md-page table').first();
|
||||||
await preview.waitFor();
|
await preview.waitFor();
|
||||||
assert.equal(await preview.locator('tbody tr').last().locator('.md-table-formula').last().innerText(), '58');
|
assert.equal(await preview.locator('tbody tr').last().locator('.md-table-formula').last().innerText(), '58');
|
||||||
|
|||||||
@@ -1,6 +1,15 @@
|
|||||||
import assert from "node:assert/strict";
|
import assert from "node:assert/strict";
|
||||||
import test from "node:test";
|
import test, { before, after } from "node:test";
|
||||||
import { cellAddress, evaluateTableFormulas } from "../src/lib/editor/tableFormulas.ts";
|
import { ExternalSession } from "../src/lib/plugins/externalSession.ts";
|
||||||
|
import { activate } from "../plugins/table-formulas/index.ts";
|
||||||
|
const session = new ExternalSession("runestone.table-formulas", {
|
||||||
|
workspace: { list: async () => [], read: async () => "", write: async () => {} },
|
||||||
|
settings: { read: async () => null, write: async () => {} },
|
||||||
|
assets: { read: async () => new Uint8Array() },
|
||||||
|
}, () => {}, () => {});
|
||||||
|
before(() => session.start({ activate }));
|
||||||
|
after(() => session.stop());
|
||||||
|
import { cellAddress, evaluateTableFormulas } from "../plugins/table-formulas/formulas.ts";
|
||||||
import { tableCellMarkdown } from "../src/lib/editor/tableCellMarkdown.ts";
|
import { tableCellMarkdown } from "../src/lib/editor/tableCellMarkdown.ts";
|
||||||
import { renderMarkdownHtml, renderMarkdownSections } from "../src/lib/workspace/noteHtml.ts";
|
import { renderMarkdownHtml, renderMarkdownSections } from "../src/lib/workspace/noteHtml.ts";
|
||||||
|
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import { mockFeaturePlugins } from "./pluginMocks.mjs";
|
||||||
// Run against `pnpm dev`. PLAYWRIGHT_MODULE may point to a shared installation.
|
// Run against `pnpm dev`. PLAYWRIGHT_MODULE may point to a shared installation.
|
||||||
import { createRequire } from "node:module";
|
import { createRequire } from "node:module";
|
||||||
import assert from "node:assert/strict";
|
import assert from "node:assert/strict";
|
||||||
@@ -71,6 +72,8 @@ await page.addInitScript(() => {
|
|||||||
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) };
|
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) };
|
||||||
window.__TEST__ = { files, calls, emit, root };
|
window.__TEST__ = { files, calls, emit, root };
|
||||||
});
|
});
|
||||||
|
await mockFeaturePlugins(page);
|
||||||
|
|
||||||
|
|
||||||
const count = command => page.evaluate(command => window.__TEST__.calls.filter(c => c.command === command).length, command);
|
const count = command => page.evaluate(command => window.__TEST__.calls.filter(c => c.command === command).length, command);
|
||||||
const waitCount = (command, n) => page.waitForFunction(({ command, n }) => window.__TEST__.calls.filter(c => c.command === command).length === n, { command, n });
|
const waitCount = (command, n) => page.waitForFunction(({ command, n }) => window.__TEST__.calls.filter(c => c.command === command).length === n, { command, n });
|
||||||
@@ -78,7 +81,7 @@ const click = name => page.getByRole("button", { name, exact: true }).click();
|
|||||||
const menu = name => page.getByRole("menuitem", { name, exact: true }).click();
|
const menu = name => page.getByRole("menuitem", { name, exact: true }).click();
|
||||||
const writes = () => page.evaluate(() => window.__TEST__.calls.filter(c => c.command === "pty_write").map(c => c.args.data).join(""));
|
const writes = () => page.evaluate(() => window.__TEST__.calls.filter(c => c.command === "pty_write").map(c => c.args.data).join(""));
|
||||||
try {
|
try {
|
||||||
await page.goto("http://127.0.0.1:1420");
|
await page.goto(process.env.SMOKE_URL || "http://127.0.0.1:1420");
|
||||||
await page.getByText("smoke-workspace", { exact: true }).waitFor();
|
await page.getByText("smoke-workspace", { exact: true }).waitFor();
|
||||||
await click("Terminal");
|
await click("Terminal");
|
||||||
await waitCount("pty_open", 1);
|
await waitCount("pty_open", 1);
|
||||||
@@ -181,7 +184,7 @@ try {
|
|||||||
await waitCount("pty_open", 8);
|
await waitCount("pty_open", 8);
|
||||||
await page.keyboard.press("Control+Shift+Alt+Backquote");
|
await page.keyboard.press("Control+Shift+Alt+Backquote");
|
||||||
await waitCount("pty_new_window", 2);
|
await waitCount("pty_new_window", 2);
|
||||||
await page.goto("http://127.0.0.1:1420/?terminalWindow=C%3A%5Csmoke-workspace");
|
await page.goto((process.env.SMOKE_URL || "http://127.0.0.1:1420") + "/?terminalWindow=C%3A%5Csmoke-workspace");
|
||||||
await waitCount("pty_open", 1);
|
await waitCount("pty_open", 1);
|
||||||
assert.equal(await count("workspace_open"), 0);
|
assert.equal(await count("workspace_open"), 0);
|
||||||
assert.equal(await page.getByRole("button", { name: "Close terminal window", exact: true }).count(), 1);
|
assert.equal(await page.getByRole("button", { name: "Close terminal window", exact: true }).count(), 1);
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import assert from "node:assert/strict";
|
import assert from "node:assert/strict";
|
||||||
import test from "node:test";
|
import test from "node:test";
|
||||||
import { directoryCommand, fileCommand, parseTasks, quoteShell, remember, terminalShortcut } from "../src/lib/terminal/model.ts";
|
import { directoryCommand, fileCommand, parseTasks, quoteShell, remember, terminalShortcut } from "../plugins/terminal/model.ts";
|
||||||
|
|
||||||
test("paths are shell-quoted without evaluating metacharacters", () => {
|
test("paths are shell-quoted without evaluating metacharacters", () => {
|
||||||
assert.equal(directoryCommand("C:\\a'b\\$notes", "powershell"), "Set-Location -LiteralPath 'C:\\a''b\\$notes'");
|
assert.equal(directoryCommand("C:\\a'b\\$notes", "powershell"), "Set-Location -LiteralPath 'C:\\a''b\\$notes'");
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import { mockFeaturePlugins } from "./pluginMocks.mjs";
|
||||||
// Run against `pnpm dev`. PLAYWRIGHT_MODULE may point to a shared installation.
|
// Run against `pnpm dev`. PLAYWRIGHT_MODULE may point to a shared installation.
|
||||||
import { createRequire } from "node:module";
|
import { createRequire } from "node:module";
|
||||||
import assert from "node:assert/strict";
|
import assert from "node:assert/strict";
|
||||||
@@ -71,6 +72,8 @@ await page.addInitScript(() => {
|
|||||||
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) };
|
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) };
|
||||||
window.__TEST__ = { files, calls, emit, root };
|
window.__TEST__ = { files, calls, emit, root };
|
||||||
});
|
});
|
||||||
|
await mockFeaturePlugins(page);
|
||||||
|
|
||||||
|
|
||||||
async function quickOpen(name) {
|
async function quickOpen(name) {
|
||||||
await page.keyboard.press("Control+p");
|
await page.keyboard.press("Control+p");
|
||||||
|
|||||||
Generated
+36
-1
@@ -3032,7 +3032,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "runestone"
|
name = "runestone"
|
||||||
version = "0.1.3"
|
version = "0.1.4"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"base64 0.23.1",
|
"base64 0.23.1",
|
||||||
"dunce",
|
"dunce",
|
||||||
@@ -3041,12 +3041,15 @@ dependencies = [
|
|||||||
"portable-pty",
|
"portable-pty",
|
||||||
"serde",
|
"serde",
|
||||||
"serde_json",
|
"serde_json",
|
||||||
|
"sha2",
|
||||||
"tauri",
|
"tauri",
|
||||||
"tauri-build",
|
"tauri-build",
|
||||||
"tauri-plugin-dialog",
|
"tauri-plugin-dialog",
|
||||||
"tauri-plugin-opener",
|
"tauri-plugin-opener",
|
||||||
"thiserror 2.0.20",
|
"thiserror 2.0.20",
|
||||||
|
"uuid",
|
||||||
"windows-sys 0.61.2",
|
"windows-sys 0.61.2",
|
||||||
|
"zip",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -4294,6 +4297,12 @@ version = "0.2.5"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b"
|
checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "typed-path"
|
||||||
|
version = "0.12.3"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "8e28f89b80c87b8fb0cf04ab448d5dd0dd0ade2f8891bae878de66a75a28600e"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "typeid"
|
name = "typeid"
|
||||||
version = "1.0.3"
|
version = "1.0.3"
|
||||||
@@ -5341,6 +5350,20 @@ dependencies = [
|
|||||||
"syn 3.0.6",
|
"syn 3.0.6",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "zip"
|
||||||
|
version = "8.6.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "2d04a6b5381502aa6087c94c669499eb1602eb9c5e8198e534de571f7154809b"
|
||||||
|
dependencies = [
|
||||||
|
"crc32fast",
|
||||||
|
"flate2",
|
||||||
|
"indexmap 2.14.2",
|
||||||
|
"memchr",
|
||||||
|
"typed-path",
|
||||||
|
"zopfli",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "zlib-rs"
|
name = "zlib-rs"
|
||||||
version = "0.6.8"
|
version = "0.6.8"
|
||||||
@@ -5353,6 +5376,18 @@ version = "1.0.23"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
|
checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "zopfli"
|
||||||
|
version = "0.8.3"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "f05cd8797d63865425ff89b5c4a48804f35ba0ce8d125800027ad6017d2b5249"
|
||||||
|
dependencies = [
|
||||||
|
"bumpalo",
|
||||||
|
"crc32fast",
|
||||||
|
"log",
|
||||||
|
"simd-adler32",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "zvariant"
|
name = "zvariant"
|
||||||
version = "5.15.0"
|
version = "5.15.0"
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "runestone"
|
name = "runestone"
|
||||||
version = "0.1.3"
|
version = "0.1.4"
|
||||||
description = "Writing workspace plus script editor"
|
description = "Writing workspace plus script editor"
|
||||||
authors = ["you"]
|
authors = ["you"]
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
@@ -25,6 +25,9 @@ tauri-plugin-dialog = "2.7.3"
|
|||||||
windows-sys = { version = "0.61.2", features = ["Win32_Storage_FileSystem", "Win32_UI_Input_KeyboardAndMouse"] }
|
windows-sys = { version = "0.61.2", features = ["Win32_Storage_FileSystem", "Win32_UI_Input_KeyboardAndMouse"] }
|
||||||
base64 = "0.23.1"
|
base64 = "0.23.1"
|
||||||
portable-pty = "0.9.0"
|
portable-pty = "0.9.0"
|
||||||
|
zip = { version = "8.6.0", default-features = false, features = ["deflate"] }
|
||||||
|
sha2 = "0.10"
|
||||||
|
uuid = { version = "1", features = ["v4"] }
|
||||||
|
|
||||||
|
|
||||||
# Read the optimization guideline for more details: https://tauri.app/concept/size/#cargo-configuration
|
# Read the optimization guideline for more details: https://tauri.app/concept/size/#cargo-configuration
|
||||||
|
|||||||
@@ -19,6 +19,19 @@ fn main() {
|
|||||||
"workspace_abs_path",
|
"workspace_abs_path",
|
||||||
"workspace_reveal",
|
"workspace_reveal",
|
||||||
"workspace_search",
|
"workspace_search",
|
||||||
|
"plugins_snapshot",
|
||||||
|
"plugins_choose",
|
||||||
|
"plugins_cancel",
|
||||||
|
"plugins_install",
|
||||||
|
"plugins_set_enabled",
|
||||||
|
"plugins_load",
|
||||||
|
"plugins_release",
|
||||||
|
"plugins_prepare_remove",
|
||||||
|
"plugins_remove",
|
||||||
|
"plugins_retry_remove",
|
||||||
|
"plugins_reveal",
|
||||||
|
"plugins_data",
|
||||||
|
"plugins_asset",
|
||||||
"pty_open",
|
"pty_open",
|
||||||
"pty_write",
|
"pty_write",
|
||||||
"pty_resize",
|
"pty_resize",
|
||||||
|
|||||||
@@ -29,6 +29,19 @@
|
|||||||
"allow-workspace-abs-path",
|
"allow-workspace-abs-path",
|
||||||
"allow-workspace-reveal",
|
"allow-workspace-reveal",
|
||||||
"allow-workspace-search",
|
"allow-workspace-search",
|
||||||
|
"allow-plugins-snapshot",
|
||||||
|
"allow-plugins-choose",
|
||||||
|
"allow-plugins-cancel",
|
||||||
|
"allow-plugins-install",
|
||||||
|
"allow-plugins-set-enabled",
|
||||||
|
"allow-plugins-load",
|
||||||
|
"allow-plugins-release",
|
||||||
|
"allow-plugins-prepare-remove",
|
||||||
|
"allow-plugins-remove",
|
||||||
|
"allow-plugins-retry-remove",
|
||||||
|
"allow-plugins-reveal",
|
||||||
|
"allow-plugins-data",
|
||||||
|
"allow-plugins-asset",
|
||||||
"allow-pty-open",
|
"allow-pty-open",
|
||||||
"allow-pty-write",
|
"allow-pty-write",
|
||||||
"allow-pty-resize",
|
"allow-pty-resize",
|
||||||
|
|||||||
@@ -0,0 +1,11 @@
|
|||||||
|
# Automatically generated - DO NOT EDIT!
|
||||||
|
|
||||||
|
[[permission]]
|
||||||
|
identifier = "allow-plugins-asset"
|
||||||
|
description = "Enables the plugins_asset command without any pre-configured scope."
|
||||||
|
commands.allow = ["plugins_asset"]
|
||||||
|
|
||||||
|
[[permission]]
|
||||||
|
identifier = "deny-plugins-asset"
|
||||||
|
description = "Denies the plugins_asset command without any pre-configured scope."
|
||||||
|
commands.deny = ["plugins_asset"]
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
# Automatically generated - DO NOT EDIT!
|
||||||
|
|
||||||
|
[[permission]]
|
||||||
|
identifier = "allow-plugins-cancel"
|
||||||
|
description = "Enables the plugins_cancel command without any pre-configured scope."
|
||||||
|
commands.allow = ["plugins_cancel"]
|
||||||
|
|
||||||
|
[[permission]]
|
||||||
|
identifier = "deny-plugins-cancel"
|
||||||
|
description = "Denies the plugins_cancel command without any pre-configured scope."
|
||||||
|
commands.deny = ["plugins_cancel"]
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
# Automatically generated - DO NOT EDIT!
|
||||||
|
|
||||||
|
[[permission]]
|
||||||
|
identifier = "allow-plugins-choose"
|
||||||
|
description = "Enables the plugins_choose command without any pre-configured scope."
|
||||||
|
commands.allow = ["plugins_choose"]
|
||||||
|
|
||||||
|
[[permission]]
|
||||||
|
identifier = "deny-plugins-choose"
|
||||||
|
description = "Denies the plugins_choose command without any pre-configured scope."
|
||||||
|
commands.deny = ["plugins_choose"]
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
# Automatically generated - DO NOT EDIT!
|
||||||
|
|
||||||
|
[[permission]]
|
||||||
|
identifier = "allow-plugins-data"
|
||||||
|
description = "Enables the plugins_data command without any pre-configured scope."
|
||||||
|
commands.allow = ["plugins_data"]
|
||||||
|
|
||||||
|
[[permission]]
|
||||||
|
identifier = "deny-plugins-data"
|
||||||
|
description = "Denies the plugins_data command without any pre-configured scope."
|
||||||
|
commands.deny = ["plugins_data"]
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
# Automatically generated - DO NOT EDIT!
|
||||||
|
|
||||||
|
[[permission]]
|
||||||
|
identifier = "allow-plugins-install"
|
||||||
|
description = "Enables the plugins_install command without any pre-configured scope."
|
||||||
|
commands.allow = ["plugins_install"]
|
||||||
|
|
||||||
|
[[permission]]
|
||||||
|
identifier = "deny-plugins-install"
|
||||||
|
description = "Denies the plugins_install command without any pre-configured scope."
|
||||||
|
commands.deny = ["plugins_install"]
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
# Automatically generated - DO NOT EDIT!
|
||||||
|
|
||||||
|
[[permission]]
|
||||||
|
identifier = "allow-plugins-load"
|
||||||
|
description = "Enables the plugins_load command without any pre-configured scope."
|
||||||
|
commands.allow = ["plugins_load"]
|
||||||
|
|
||||||
|
[[permission]]
|
||||||
|
identifier = "deny-plugins-load"
|
||||||
|
description = "Denies the plugins_load command without any pre-configured scope."
|
||||||
|
commands.deny = ["plugins_load"]
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
# Automatically generated - DO NOT EDIT!
|
||||||
|
|
||||||
|
[[permission]]
|
||||||
|
identifier = "allow-plugins-prepare-remove"
|
||||||
|
description = "Enables the plugins_prepare_remove command without any pre-configured scope."
|
||||||
|
commands.allow = ["plugins_prepare_remove"]
|
||||||
|
|
||||||
|
[[permission]]
|
||||||
|
identifier = "deny-plugins-prepare-remove"
|
||||||
|
description = "Denies the plugins_prepare_remove command without any pre-configured scope."
|
||||||
|
commands.deny = ["plugins_prepare_remove"]
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
# Automatically generated - DO NOT EDIT!
|
||||||
|
|
||||||
|
[[permission]]
|
||||||
|
identifier = "allow-plugins-release"
|
||||||
|
description = "Enables the plugins_release command without any pre-configured scope."
|
||||||
|
commands.allow = ["plugins_release"]
|
||||||
|
|
||||||
|
[[permission]]
|
||||||
|
identifier = "deny-plugins-release"
|
||||||
|
description = "Denies the plugins_release command without any pre-configured scope."
|
||||||
|
commands.deny = ["plugins_release"]
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
# Automatically generated - DO NOT EDIT!
|
||||||
|
|
||||||
|
[[permission]]
|
||||||
|
identifier = "allow-plugins-remove"
|
||||||
|
description = "Enables the plugins_remove command without any pre-configured scope."
|
||||||
|
commands.allow = ["plugins_remove"]
|
||||||
|
|
||||||
|
[[permission]]
|
||||||
|
identifier = "deny-plugins-remove"
|
||||||
|
description = "Denies the plugins_remove command without any pre-configured scope."
|
||||||
|
commands.deny = ["plugins_remove"]
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
# Automatically generated - DO NOT EDIT!
|
||||||
|
|
||||||
|
[[permission]]
|
||||||
|
identifier = "allow-plugins-retry-remove"
|
||||||
|
description = "Enables the plugins_retry_remove command without any pre-configured scope."
|
||||||
|
commands.allow = ["plugins_retry_remove"]
|
||||||
|
|
||||||
|
[[permission]]
|
||||||
|
identifier = "deny-plugins-retry-remove"
|
||||||
|
description = "Denies the plugins_retry_remove command without any pre-configured scope."
|
||||||
|
commands.deny = ["plugins_retry_remove"]
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
# Automatically generated - DO NOT EDIT!
|
||||||
|
|
||||||
|
[[permission]]
|
||||||
|
identifier = "allow-plugins-reveal"
|
||||||
|
description = "Enables the plugins_reveal command without any pre-configured scope."
|
||||||
|
commands.allow = ["plugins_reveal"]
|
||||||
|
|
||||||
|
[[permission]]
|
||||||
|
identifier = "deny-plugins-reveal"
|
||||||
|
description = "Denies the plugins_reveal command without any pre-configured scope."
|
||||||
|
commands.deny = ["plugins_reveal"]
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
# Automatically generated - DO NOT EDIT!
|
||||||
|
|
||||||
|
[[permission]]
|
||||||
|
identifier = "allow-plugins-set-enabled"
|
||||||
|
description = "Enables the plugins_set_enabled command without any pre-configured scope."
|
||||||
|
commands.allow = ["plugins_set_enabled"]
|
||||||
|
|
||||||
|
[[permission]]
|
||||||
|
identifier = "deny-plugins-set-enabled"
|
||||||
|
description = "Denies the plugins_set_enabled command without any pre-configured scope."
|
||||||
|
commands.deny = ["plugins_set_enabled"]
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
# Automatically generated - DO NOT EDIT!
|
||||||
|
|
||||||
|
[[permission]]
|
||||||
|
identifier = "allow-plugins-snapshot"
|
||||||
|
description = "Enables the plugins_snapshot command without any pre-configured scope."
|
||||||
|
commands.allow = ["plugins_snapshot"]
|
||||||
|
|
||||||
|
[[permission]]
|
||||||
|
identifier = "deny-plugins-snapshot"
|
||||||
|
description = "Denies the plugins_snapshot command without any pre-configured scope."
|
||||||
|
commands.deny = ["plugins_snapshot"]
|
||||||
@@ -1,4 +1,5 @@
|
|||||||
mod pty;
|
mod pty;
|
||||||
|
mod plugins;
|
||||||
mod workspace;
|
mod workspace;
|
||||||
|
|
||||||
use pty::PtyState;
|
use pty::PtyState;
|
||||||
@@ -12,6 +13,7 @@ pub fn run() {
|
|||||||
.plugin(tauri_plugin_dialog::init())
|
.plugin(tauri_plugin_dialog::init())
|
||||||
.manage(WorkspaceState::new())
|
.manage(WorkspaceState::new())
|
||||||
.manage(PtyState::new())
|
.manage(PtyState::new())
|
||||||
|
.manage(plugins::PluginState::default())
|
||||||
.invoke_handler(tauri::generate_handler![
|
.invoke_handler(tauri::generate_handler![
|
||||||
workspace::workspace_open,
|
workspace::workspace_open,
|
||||||
workspace::workspace_open_window,
|
workspace::workspace_open_window,
|
||||||
@@ -30,6 +32,19 @@ pub fn run() {
|
|||||||
workspace::workspace_abs_path,
|
workspace::workspace_abs_path,
|
||||||
workspace::workspace_reveal,
|
workspace::workspace_reveal,
|
||||||
workspace::workspace_search,
|
workspace::workspace_search,
|
||||||
|
plugins::plugins_snapshot,
|
||||||
|
plugins::plugins_choose,
|
||||||
|
plugins::plugins_cancel,
|
||||||
|
plugins::plugins_install,
|
||||||
|
plugins::plugins_set_enabled,
|
||||||
|
plugins::plugins_load,
|
||||||
|
plugins::plugins_release,
|
||||||
|
plugins::plugins_prepare_remove,
|
||||||
|
plugins::plugins_remove,
|
||||||
|
plugins::plugins_retry_remove,
|
||||||
|
plugins::plugins_reveal,
|
||||||
|
plugins::plugins_data,
|
||||||
|
plugins::plugins_asset,
|
||||||
pty::pty_open,
|
pty::pty_open,
|
||||||
pty::pty_write,
|
pty::pty_write,
|
||||||
pty::pty_resize,
|
pty::pty_resize,
|
||||||
@@ -43,6 +58,7 @@ pub fn run() {
|
|||||||
.run(|app, event| {
|
.run(|app, event| {
|
||||||
if let tauri::RunEvent::WindowEvent { label, event: tauri::WindowEvent::Destroyed, .. } = &event {
|
if let tauri::RunEvent::WindowEvent { label, event: tauri::WindowEvent::Destroyed, .. } = &event {
|
||||||
app.state::<PtyState>().close_window(label);
|
app.state::<PtyState>().close_window(label);
|
||||||
|
app.state::<plugins::PluginState>().close_window(label);
|
||||||
app.state::<WorkspaceState>().close_window(label);
|
app.state::<WorkspaceState>().close_window(label);
|
||||||
}
|
}
|
||||||
if matches!(event, tauri::RunEvent::Exit) {
|
if matches!(event, tauri::RunEvent::Exit) {
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
+40
-13
@@ -456,7 +456,11 @@ pub fn workspace_open(
|
|||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
pub fn workspace_list(window: tauri::Window, state: State<WorkspaceState>, rel: String) -> WsResult<Vec<TreeEntry>> {
|
pub fn workspace_list(window: tauri::Window, state: State<WorkspaceState>, rel: String) -> WsResult<Vec<TreeEntry>> {
|
||||||
let root = current_root(&state, window.label())?;
|
let root = current_root(&state, window.label())?;
|
||||||
let dir = resolve_existing(&root, &rel)?;
|
list_entries(&root, &rel)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn list_entries(root: &Path, rel: &str) -> WsResult<Vec<TreeEntry>> {
|
||||||
|
let dir = resolve_existing(root, rel)?;
|
||||||
if !dir.is_dir() {
|
if !dir.is_dir() {
|
||||||
return Err(err("path is not a folder"));
|
return Err(err("path is not a folder"));
|
||||||
}
|
}
|
||||||
@@ -464,12 +468,7 @@ pub fn workspace_list(window: tauri::Window, state: State<WorkspaceState>, rel:
|
|||||||
let mut entries = Vec::new();
|
let mut entries = Vec::new();
|
||||||
let walker = ignore::WalkBuilder::new(&dir)
|
let walker = ignore::WalkBuilder::new(&dir)
|
||||||
.max_depth(Some(1))
|
.max_depth(Some(1))
|
||||||
.hidden(false)
|
.standard_filters(false)
|
||||||
.git_ignore(true)
|
|
||||||
.require_git(false)
|
|
||||||
.git_global(true)
|
|
||||||
.git_exclude(true)
|
|
||||||
.parents(true)
|
|
||||||
.build();
|
.build();
|
||||||
|
|
||||||
for result in walker {
|
for result in walker {
|
||||||
@@ -788,17 +787,18 @@ pub struct SearchHit {
|
|||||||
|
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
pub fn workspace_search(window: tauri::Window, state: State<WorkspaceState>, query: String) -> WsResult<Vec<SearchHit>> {
|
pub fn workspace_search(window: tauri::Window, state: State<WorkspaceState>, query: String) -> WsResult<Vec<SearchHit>> {
|
||||||
|
let root = current_root(&state, window.label())?;
|
||||||
|
search_entries(&root, &query)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn search_entries(root: &Path, query: &str) -> WsResult<Vec<SearchHit>> {
|
||||||
let needle = query.trim().to_lowercase();
|
let needle = query.trim().to_lowercase();
|
||||||
if needle.is_empty() {
|
if needle.is_empty() {
|
||||||
return Ok(Vec::new());
|
return Ok(Vec::new());
|
||||||
}
|
}
|
||||||
let root = current_root(&state, window.label())?;
|
|
||||||
let mut hits = Vec::new();
|
let mut hits = Vec::new();
|
||||||
let walker = ignore::WalkBuilder::new(&root)
|
let walker = ignore::WalkBuilder::new(root)
|
||||||
.hidden(false)
|
.standard_filters(false)
|
||||||
.git_ignore(true)
|
|
||||||
.require_git(false)
|
|
||||||
.git_global(true)
|
|
||||||
.filter_entry(|entry| {
|
.filter_entry(|entry| {
|
||||||
entry.depth() == 0 || !is_internal_name(&entry.file_name().to_string_lossy())
|
entry.depth() == 0 || !is_internal_name(&entry.file_name().to_string_lossy())
|
||||||
})
|
})
|
||||||
@@ -887,6 +887,33 @@ mod tests {
|
|||||||
use super::*;
|
use super::*;
|
||||||
use std::path::PathBuf;
|
use std::path::PathBuf;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn ignore_files_do_not_hide_workspace_entries_or_search_results() {
|
||||||
|
let fixture = std::env::temp_dir().join(format!("rs-ignore-rules-{}", std::process::id()));
|
||||||
|
let root = fixture.join("workspace");
|
||||||
|
fs::create_dir_all(root.join(".git/info")).unwrap();
|
||||||
|
fs::write(fixture.join(".ignore"), "parent-excluded/\n").unwrap();
|
||||||
|
fs::write(root.join(".gitignore"), "papers/\n").unwrap();
|
||||||
|
fs::write(root.join(".ignore"), "local-excluded/\n").unwrap();
|
||||||
|
fs::write(root.join(".git/info/exclude"), "git-excluded/\n").unwrap();
|
||||||
|
for folder in ["papers", "local-excluded", "git-excluded", "parent-excluded", ".hidden-notes"] {
|
||||||
|
fs::create_dir_all(root.join(folder)).unwrap();
|
||||||
|
fs::write(root.join(folder).join("note.md"), "unique search phrase").unwrap();
|
||||||
|
}
|
||||||
|
fs::write(root.join("papers/.gitignore"), "note.md\n").unwrap();
|
||||||
|
let root = dunce::canonicalize(root).unwrap();
|
||||||
|
let entries = list_entries(&root, "").unwrap();
|
||||||
|
let hits = search_entries(&root, "unique search phrase").unwrap();
|
||||||
|
for folder in ["papers", "local-excluded", "git-excluded", "parent-excluded", ".hidden-notes"] {
|
||||||
|
assert!(entries.iter().any(|entry| entry.rel_path == folder && entry.kind == "folder"), "{folder}");
|
||||||
|
let note = format!("{folder}/note.md");
|
||||||
|
assert!(list_entries(&root, folder).unwrap().iter().any(|entry| entry.rel_path == note), "{note}");
|
||||||
|
assert!(hits.iter().any(|hit| hit.rel_path == note && hit.line == 1), "{note}");
|
||||||
|
}
|
||||||
|
assert!(!entries.iter().any(|entry| entry.name == ".git"));
|
||||||
|
fs::remove_dir_all(fixture).unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn windows_keep_independent_roots_and_cleanup() {
|
fn windows_keep_independent_roots_and_cleanup() {
|
||||||
let state = WorkspaceState::new();
|
let state = WorkspaceState::new();
|
||||||
|
|||||||
@@ -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.3",
|
"version": "0.1.4",
|
||||||
"identifier": "com.runestone.app",
|
"identifier": "com.runestone.app",
|
||||||
"build": {
|
"build": {
|
||||||
"beforeDevCommand": "pnpm dev",
|
"beforeDevCommand": "pnpm dev",
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
|
import { pluginHost } from "$lib/plugins/registry";
|
||||||
import { untrack } from "svelte";
|
import { untrack } from "svelte";
|
||||||
import { Compartment, EditorState } from "@codemirror/state";
|
import { Compartment, EditorState } from "@codemirror/state";
|
||||||
import { EditorView, drawSelection, keymap } from "@codemirror/view";
|
import { EditorView, drawSelection, keymap } from "@codemirror/view";
|
||||||
@@ -33,8 +34,10 @@
|
|||||||
focusLine?: number | null;
|
focusLine?: number | null;
|
||||||
tableActions?: TableContextActions;
|
tableActions?: TableContextActions;
|
||||||
shouldFocusOnMount?: () => boolean;
|
shouldFocusOnMount?: () => boolean;
|
||||||
|
focusTitle?: boolean;
|
||||||
|
onTitleFocused?: () => void;
|
||||||
};
|
};
|
||||||
let { buffer, onChange, onRenameTitle, onOpenLink, onInsertImage, focusLine = null, tableActions = {}, shouldFocusOnMount = () => true }: Props = $props();
|
let { buffer, onChange, onRenameTitle, onOpenLink, onInsertImage, focusLine = null, tableActions = {}, shouldFocusOnMount = () => true, focusTitle = false, onTitleFocused }: Props = $props();
|
||||||
let host: HTMLDivElement | undefined = $state();
|
let host: HTMLDivElement | undefined = $state();
|
||||||
let editor = $state.raw<EditorView>();
|
let editor = $state.raw<EditorView>();
|
||||||
let error = $state("");
|
let error = $state("");
|
||||||
@@ -234,7 +237,7 @@
|
|||||||
selectAll() { view.dispatch({ selection: { anchor: 0, head: view.state.doc.length } }); view.focus(); },
|
selectAll() { view.dispatch({ selection: { anchor: 0, head: view.state.doc.length } }); view.focus(); },
|
||||||
focus() { view.focus(); },
|
focus() { view.focus(); },
|
||||||
}, untrack(() => tableActions), message => { error = message; });
|
}, untrack(() => tableActions), message => { error = message; });
|
||||||
if (shouldFocusOnMount()) view.focus();
|
if (!focusTitle && shouldFocusOnMount()) view.focus();
|
||||||
}).catch(reason => { if (!cancelled) error = String(reason); });
|
}).catch(reason => { if (!cancelled) error = String(reason); });
|
||||||
return () => {
|
return () => {
|
||||||
cancelled = true;
|
cancelled = true;
|
||||||
@@ -251,12 +254,25 @@
|
|||||||
};
|
};
|
||||||
});
|
});
|
||||||
|
|
||||||
|
$effect(() => {
|
||||||
|
void $pluginHost;
|
||||||
|
editor?.dispatch({ effects: refreshImages.of() });
|
||||||
|
});
|
||||||
|
|
||||||
$effect(() => {
|
$effect(() => {
|
||||||
const name = markdownTitle(buffer.relPath);
|
const name = markdownTitle(buffer.relPath);
|
||||||
const view = editor;
|
const view = editor;
|
||||||
if (view) view.dispatch({ effects: title.reconfigure(noteTitle(name, onRenameTitle ? renameTitle : undefined)) });
|
if (view) view.dispatch({ effects: title.reconfigure(noteTitle(name, onRenameTitle ? renameTitle : undefined)) });
|
||||||
});
|
});
|
||||||
|
|
||||||
|
$effect(() => {
|
||||||
|
if (!focusTitle || !editor) return;
|
||||||
|
const button = editor.dom.querySelector<HTMLButtonElement>(".note-title-button");
|
||||||
|
if (!button) return;
|
||||||
|
button.click();
|
||||||
|
onTitleFocused?.();
|
||||||
|
});
|
||||||
|
|
||||||
$effect(() => {
|
$effect(() => {
|
||||||
const value = buffer.contents;
|
const value = buffer.contents;
|
||||||
const path = buffer.relPath;
|
const path = buffer.relPath;
|
||||||
|
|||||||
@@ -10,6 +10,9 @@ import { imageControls } from "./imageControls";
|
|||||||
import { ImagePreview, type ImageContext } from "./imagePreview";
|
import { ImagePreview, type ImageContext } from "./imagePreview";
|
||||||
import { imageSource, editImageSource, imageSourceRanges } from "./imageSource";
|
import { imageSource, editImageSource, imageSourceRanges } from "./imageSource";
|
||||||
|
|
||||||
|
import { pluginHost } from "../plugins/registry.ts";
|
||||||
|
|
||||||
|
const previewFormulas = new WeakMap<HTMLElement, unknown>();
|
||||||
export const refreshImages = StateEffect.define<void>();
|
export const refreshImages = StateEffect.define<void>();
|
||||||
const imageCleanups = new WeakMap<HTMLElement, () => void>();
|
const imageCleanups = new WeakMap<HTMLElement, () => void>();
|
||||||
|
|
||||||
@@ -54,20 +57,22 @@ class Checkbox extends WidgetType {
|
|||||||
}
|
}
|
||||||
|
|
||||||
class Preview extends WidgetType {
|
class Preview extends WidgetType {
|
||||||
|
readonly formulas = pluginHost.get("tableFormulas");
|
||||||
constructor(readonly html: string, readonly source: string, readonly actions: TableContextActions, readonly sourceVisible = false, readonly height = { value: -1 }) { super(); }
|
constructor(readonly html: string, readonly source: string, readonly actions: TableContextActions, readonly sourceVisible = false, readonly height = { value: -1 }) { super(); }
|
||||||
get estimatedHeight() { return this.height.value; }
|
get estimatedHeight() { return this.height.value; }
|
||||||
eq(other: Preview) { return other.html === this.html && other.source === this.source && other.sourceVisible === this.sourceVisible; }
|
eq(other: Preview) { return other.formulas === this.formulas && other.html === this.html && other.source === this.source && other.sourceVisible === this.sourceVisible; }
|
||||||
measure(dom: HTMLElement, view: EditorView) {
|
measure(dom: HTMLElement, view: EditorView) {
|
||||||
view.requestMeasure({ key: this.height, read: () => dom.offsetHeight, write: height => { this.height.value = height; } });
|
view.requestMeasure({ key: this.height, read: () => dom.offsetHeight, write: height => { this.height.value = height; } });
|
||||||
}
|
}
|
||||||
updateDOM(dom: HTMLElement, view: EditorView) {
|
updateDOM(dom: HTMLElement, view: EditorView) {
|
||||||
if (tableEditors.get(dom)?.source !== this.source) return false;
|
if (previewFormulas.get(dom) !== this.formulas || tableEditors.get(dom)?.source !== this.source) return false;
|
||||||
this.measure(dom, view);
|
this.measure(dom, view);
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
destroy(dom: HTMLElement) { tableEditors.get(dom)?.destroy(); imageCleanups.get(dom)?.(); }
|
destroy(dom: HTMLElement) { tableEditors.get(dom)?.destroy(); imageCleanups.get(dom)?.(); }
|
||||||
toDOM(view: EditorView) {
|
toDOM(view: EditorView) {
|
||||||
const dom = document.createElement("div");
|
const dom = document.createElement("div");
|
||||||
|
previewFormulas.set(dom, this.formulas);
|
||||||
dom.className = "reading writer-preview";
|
dom.className = "reading writer-preview";
|
||||||
dom.innerHTML = this.html;
|
dom.innerHTML = this.html;
|
||||||
tableControls(dom, view, this.source, this.actions);
|
tableControls(dom, view, this.source, this.actions);
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import type { JSONContent } from "@tiptap/core";
|
import type { JSONContent } from "@tiptap/core";
|
||||||
import { isTableFormula } from "./tableFormulas.ts";
|
// Preserve formula source even when calculation is disabled.
|
||||||
|
const isTableFormula = (text: string) => /^=(?!=)/.test(text.trim());
|
||||||
|
|
||||||
// Extract inline content into a note without confusing literal <br> in code
|
// Extract inline content into a note without confusing literal <br> in code
|
||||||
// with actual cell hard breaks.
|
// with actual cell hard breaks.
|
||||||
|
|||||||
@@ -11,8 +11,7 @@ import { tableSelectionControls } from "./tableSelectionControls";
|
|||||||
import { tableDragControls } from "./tableDragControls";
|
import { tableDragControls } from "./tableDragControls";
|
||||||
import type { TableContextActions } from "./tableCellActions";
|
import type { TableContextActions } from "./tableCellActions";
|
||||||
import { actionIcon } from "../ui/actionIcons";
|
import { actionIcon } from "../ui/actionIcons";
|
||||||
import { cellAddress, evaluateTableFormulas, formulaErrors, isTableFormula } from "./tableFormulas";
|
import { pluginHost } from "../plugins/registry.ts";
|
||||||
import { tableFormulaHtml } from "../workspace/noteHtml";
|
|
||||||
|
|
||||||
const cellFormats = ["math", "comment"].map(name => Mark.create({
|
const cellFormats = ["math", "comment"].map(name => Mark.create({
|
||||||
name,
|
name,
|
||||||
@@ -36,6 +35,7 @@ const CellImage = Image.extend({
|
|||||||
export const tableEditors = new WeakMap<HTMLElement, { source: string; enter: (forward: boolean, x?: number) => void; destroy: () => void }>();
|
export const tableEditors = new WeakMap<HTMLElement, { source: string; enter: (forward: boolean, x?: number) => void; destroy: () => void }>();
|
||||||
|
|
||||||
export function tableControls(root: HTMLElement, view: EditorView, initialSource: string, actions: TableContextActions = {}) {
|
export function tableControls(root: HTMLElement, view: EditorView, initialSource: string, actions: TableContextActions = {}) {
|
||||||
|
const formulas = pluginHost.get("tableFormulas");
|
||||||
const scroll = root.querySelector<HTMLElement>(".md-table-scroll");
|
const scroll = root.querySelector<HTMLElement>(".md-table-scroll");
|
||||||
const table = scroll?.querySelector("table");
|
const table = scroll?.querySelector("table");
|
||||||
if (!scroll || !table || !parseMarkdownTable(initialSource)) return;
|
if (!scroll || !table || !parseMarkdownTable(initialSource)) return;
|
||||||
@@ -76,17 +76,17 @@ export function tableControls(root: HTMLElement, view: EditorView, initialSource
|
|||||||
|
|
||||||
function refreshFormulas() {
|
function refreshFormulas() {
|
||||||
const parsed = parseMarkdownTable(controller.source);
|
const parsed = parseMarkdownTable(controller.source);
|
||||||
if (!parsed) return;
|
if (!parsed || !formulas) return;
|
||||||
const grid = parsed.rows.filter((_, index) => index !== 1).map(row => Array.from({ length: parsed.columns }, (_, c) => row.cells[c]?.text || ""));
|
const grid = parsed.rows.filter((_, index) => index !== 1).map(row => Array.from({ length: parsed.columns }, (_, c) => row.cells[c]?.text || ""));
|
||||||
const results = evaluateTableFormulas(grid);
|
const results = formulas.evaluateTableFormulas(grid);
|
||||||
for (const row of table!.rows) for (const cell of row.cells) {
|
for (const row of table!.rows) for (const cell of row.cells) {
|
||||||
const result = results[row.rowIndex]?.[cell.cellIndex];
|
const result = results[row.rowIndex]?.[cell.cellIndex];
|
||||||
const address = cellAddress(row.rowIndex, cell.cellIndex);
|
const address = formulas.cellAddress(row.rowIndex, cell.cellIndex);
|
||||||
cell.title = `${address} · ${result?.formula || "Click to edit · Type = for a formula"}`;
|
cell.title = `${address} · ${result?.formula || "Click to edit · Type = for a formula"}`;
|
||||||
if (result && cell !== active) cell.innerHTML = 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}` : " · Type = to calculate"}`;
|
||||||
formulaHint.textContent = result?.error ? formulaErrors[result.error] : "";
|
formulaHint.textContent = result?.error ? formulas.formulaErrors[result.error] : "";
|
||||||
formulaHint.hidden = !formulaHint.textContent;
|
formulaHint.hidden = !formulaHint.textContent;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -156,9 +156,9 @@ export function tableControls(root: HTMLElement, view: EditorView, initialSource
|
|||||||
// leave its previous active line so its Markdown markers render again.
|
// leave its previous active line so its Markdown markers render again.
|
||||||
view.dispatch({ selection: { anchor: view.posAtDOM(root) + (originalCell?.from ?? 0) }, userEvent: "select.table" });
|
view.dispatch({ selection: { anchor: view.posAtDOM(root) + (originalCell?.from ?? 0) }, userEvent: "select.table" });
|
||||||
let contentFrom = originalCell?.from, contentTo = originalCell?.to;
|
let contentFrom = originalCell?.from, contentTo = originalCell?.to;
|
||||||
const formula = originalCell && (isTableFormula(originalCell.text) || /^\\=(?!=)/.test(originalCell.text)) ? originalCell.text : undefined;
|
const formula = originalCell && (/^=(?!=)/.test(originalCell.text.trim()) || /^\\=(?!=)/.test(originalCell.text)) ? originalCell.text : undefined;
|
||||||
const html = cell.innerHTML;
|
const html = cell.innerHTML;
|
||||||
formulaStatus.textContent = `${cellAddress(row, column)} · Type = to calculate`;
|
formulaStatus.textContent = formulas ? `${formulas.cellAddress(row, column)} · Type = to calculate` : "";
|
||||||
cell.innerHTML = "";
|
cell.innerHTML = "";
|
||||||
cell.classList.add("is-editing");
|
cell.classList.add("is-editing");
|
||||||
editor = new Editor({
|
editor = new Editor({
|
||||||
@@ -239,7 +239,7 @@ export function tableControls(root: HTMLElement, view: EditorView, initialSource
|
|||||||
if (event.key === "Escape") { event.preventDefault(); leave(true); return true; }
|
if (event.key === "Escape") { event.preventDefault(); leave(true); return true; }
|
||||||
if (event.key === "Enter") {
|
if (event.key === "Enter") {
|
||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
if (isTableFormula(editor?.getText() || "")) { finish(); wrapper.focus(); }
|
if (/^=(?!=)/.test((editor?.getText() || "").trim())) { finish(); wrapper.focus(); }
|
||||||
else if (event.ctrlKey || event.metaKey) leave(true);
|
else if (event.ctrlKey || event.metaKey) leave(true);
|
||||||
else editor?.commands.setHardBreak();
|
else editor?.commands.setHardBreak();
|
||||||
return true;
|
return true;
|
||||||
@@ -301,48 +301,11 @@ export function tableControls(root: HTMLElement, view: EditorView, initialSource
|
|||||||
help.textContent = "Drag grips: move rows/columns · Drag cells: select · Right-click: actions · Arrows: move through cells · Tab: next cell · Esc: exit table";
|
help.textContent = "Drag grips: move rows/columns · Drag cells: select · Right-click: actions · Arrows: move through cells · Tab: next cell · Esc: exit table";
|
||||||
const footer = document.createElement("div");
|
const footer = document.createElement("div");
|
||||||
footer.className = "table-footer";
|
footer.className = "table-footer";
|
||||||
const formulaTools = document.createElement("div");
|
const tools = formulas?.createFormulaTools(finish, () => view.requestMeasure());
|
||||||
formulaTools.className = "table-formula-tools";
|
const formulaStatus = tools?.formulaStatus ?? document.createElement("span");
|
||||||
const formulaHelp = document.createElement("details");
|
const formulaHint = tools?.formulaHint ?? document.createElement("div");
|
||||||
formulaHelp.className = "table-formula-help";
|
footer.append(help);
|
||||||
const summary = document.createElement("summary");
|
if (tools) footer.append(tools.formulaTools, formulaHint);
|
||||||
summary.append(actionIcon("math"), document.createTextNode("Formulas"));
|
|
||||||
summary.title = "How to calculate with table cells";
|
|
||||||
// Committing a wrapped formula can shrink its row. Keep the click target in
|
|
||||||
// place until mouseup, then finish editing and give keyboard focus to help.
|
|
||||||
summary.addEventListener("mousedown", event => { if (event.button === 0) { event.preventDefault(); event.stopPropagation(); } });
|
|
||||||
summary.addEventListener("click", () => { finish(); summary.focus(); });
|
|
||||||
const instructions = document.createElement("div");
|
|
||||||
instructions.className = "table-formula-instructions";
|
|
||||||
const intro = document.createElement("p");
|
|
||||||
intro.textContent = "Start a cell with =, then press Enter or Tab. Columns are A, B, C…; the header is row 1 and the first data row is 2.";
|
|
||||||
const examples = document.createElement("dl");
|
|
||||||
for (const [formula, description] of [
|
|
||||||
["=AVERAGE(B2,C2)", "Average two values: 9 and 10 give 9.5."],
|
|
||||||
["=AVERAGE(B2:C2)", "Average every cell in the range B2 through C2."],
|
|
||||||
["=SUM(B2:B10)", "Add the values in a range."],
|
|
||||||
["=(B2+C2)/2", "Add two values and divide by two."],
|
|
||||||
["=ROUND(B2/3,2)", "Round to two decimal places."],
|
|
||||||
]) {
|
|
||||||
const term = document.createElement("dt"), code = document.createElement("code"), descriptionElement = document.createElement("dd");
|
|
||||||
code.textContent = formula; term.append(code); descriptionElement.textContent = description;
|
|
||||||
examples.append(term, descriptionElement);
|
|
||||||
}
|
|
||||||
const functions = document.createElement("p");
|
|
||||||
functions.textContent = "Functions: SUM, AVERAGE, MIN, MAX, COUNT, ABS, ROUND. Operators: + − * / ^ and %. Use commas between function arguments; use a colon for a cell range.";
|
|
||||||
const references = document.createElement("p");
|
|
||||||
references.textContent = "References stay at their written addresses when copying, inserting, deleting, sorting, or moving cells. Code-formatted expressions are literal text; formulas must start with = outside code formatting.";
|
|
||||||
instructions.append(intro, examples, functions, references);
|
|
||||||
formulaHelp.append(summary, instructions);
|
|
||||||
formulaHelp.addEventListener("toggle", () => view.requestMeasure());
|
|
||||||
const formulaStatus = document.createElement("span");
|
|
||||||
formulaStatus.className = "table-formula-status";
|
|
||||||
formulaStatus.textContent = "Type = in a cell to calculate";
|
|
||||||
const formulaHint = document.createElement("div");
|
|
||||||
formulaHint.className = "table-formula-hint";
|
|
||||||
formulaHint.hidden = true;
|
|
||||||
formulaTools.append(formulaHelp, formulaStatus);
|
|
||||||
footer.append(help, formulaTools, formulaHint);
|
|
||||||
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");
|
||||||
@@ -365,7 +328,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", `${cellAddress(row.rowIndex, cell.cellIndex)} · Row ${row.rowIndex + 1}, column ${cell.cellIndex + 1}`);
|
cell.setAttribute("aria-label", `${formulas ? formulas.cellAddress(row.rowIndex, cell.cellIndex) + " · " : ""}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 }, actions);
|
selectionControls = tableSelectionControls(root, wrapper, table, view, () => controller.source, finish, change, { get: () => editor, activate }, actions);
|
||||||
|
|||||||
@@ -33,7 +33,14 @@
|
|||||||
let { buffer, tabs, chrome, reading, focusLine, onChange, onRenameTitle, onInsertImage, onToggleReading, onToggleChrome, onOpenLink, onOpenWorkspace, onNewFile, onQuickOpen, hasWorkspace, tableActions }: Props = $props();
|
let { buffer, tabs, chrome, reading, focusLine, onChange, onRenameTitle, onInsertImage, onToggleReading, onToggleChrome, onOpenLink, onOpenWorkspace, onNewFile, onQuickOpen, hasWorkspace, tableActions }: Props = $props();
|
||||||
let previewMode = $state<"split" | "preview">("split");
|
let previewMode = $state<"split" | "preview">("split");
|
||||||
let modeControls = $state<HTMLDivElement>();
|
let modeControls = $state<HTMLDivElement>();
|
||||||
|
let titleFocusId = $state<string | null>(null);
|
||||||
const shouldFocusOnMount = () => !modeControls?.contains(document.activeElement);
|
const shouldFocusOnMount = () => !modeControls?.contains(document.activeElement);
|
||||||
|
export function focusTitle(id: string) {
|
||||||
|
titleFocusId = id;
|
||||||
|
}
|
||||||
|
$effect(() => {
|
||||||
|
if (titleFocusId !== buffer?.id) titleFocusId = null;
|
||||||
|
});
|
||||||
const previewScroll = new Map<string, { top: number; left: number }>();
|
const previewScroll = new Map<string, { top: number; left: number }>();
|
||||||
$effect(() => {
|
$effect(() => {
|
||||||
const ids = tabs.map(tab => tab.id);
|
const ids = tabs.map(tab => tab.id);
|
||||||
@@ -131,7 +138,8 @@
|
|||||||
<div class="editor-wrap" class:hidden={reading && canPreview && previewMode === "preview"}>
|
<div class="editor-wrap" class:hidden={reading && canPreview && previewMode === "preview"}>
|
||||||
{#key buffer.id}
|
{#key buffer.id}
|
||||||
{#if !isIde && canPreview && !reading}
|
{#if !isIde && canPreview && !reading}
|
||||||
<LiveWriter {buffer} {onChange} {onRenameTitle} {onInsertImage} {onOpenLink} {focusLine} {tableActions} {shouldFocusOnMount} />
|
<LiveWriter {buffer} {onChange} {onRenameTitle} {onInsertImage} {onOpenLink} {focusLine} {tableActions} {shouldFocusOnMount}
|
||||||
|
focusTitle={titleFocusId === buffer.id} onTitleFocused={() => { titleFocusId = null; }} />
|
||||||
{:else}
|
{:else}
|
||||||
<EditorHost {buffer} {chrome} {onChange} {onInsertImage} {focusLine} {tableActions} {shouldFocusOnMount} />
|
<EditorHost {buffer} {chrome} {onChange} {onInsertImage} {focusLine} {tableActions} {shouldFocusOnMount} />
|
||||||
{/if}
|
{/if}
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
|
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";
|
||||||
import { markdownImages, renderMarkdownHtml, renderMarkdownSections, type MarkdownSection } from "$lib/workspace/noteHtml";
|
import { markdownImages, renderMarkdownHtml, renderMarkdownSections, type MarkdownSection } from "$lib/workspace/noteHtml";
|
||||||
@@ -44,6 +45,7 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
$effect(() => {
|
$effect(() => {
|
||||||
|
void $pluginHost;
|
||||||
const path = noteRel;
|
const path = noteRel;
|
||||||
const text = contents;
|
const text = contents;
|
||||||
let cancelled = false;
|
let cancelled = false;
|
||||||
|
|||||||
@@ -0,0 +1,184 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import PluginManager from "$lib/plugins/PluginManager.svelte";
|
||||||
|
import { onMount, untrack } from "svelte";
|
||||||
|
import Icon from "$lib/ui/Icon.svelte";
|
||||||
|
import IconButton, { type IconName } from "$lib/ui/IconButton.svelte";
|
||||||
|
import { DEFAULT_SETTINGS, MIN_AUTOSAVE_SECONDS, MAX_AUTOSAVE_SECONDS, validAutosaveSeconds, type AppSettings } from "$lib/workspace/settings";
|
||||||
|
import { version, license } from "../../../package.json";
|
||||||
|
|
||||||
|
let { settings, help = false, onSave, onClose }: {
|
||||||
|
settings: AppSettings;
|
||||||
|
help?: boolean;
|
||||||
|
onSave: (value: AppSettings) => void;
|
||||||
|
onClose: () => void;
|
||||||
|
} = $props();
|
||||||
|
type Section = "general" | "plugins" | "about";
|
||||||
|
const sections: { id: Section; label: string; icon: IconName; keywords: string }[] = [
|
||||||
|
{ id: "general", label: "General", icon: "settings", keywords: "auto-save autosave save interval seconds files" },
|
||||||
|
{ id: "plugins", label: "Plug-ins", icon: "puzzle", keywords: "plugins extensions community" },
|
||||||
|
{ id: "about", label: "Help and about", icon: "help", keywords: "help about version shortcuts keyboard guide" },
|
||||||
|
];
|
||||||
|
let section = $state<Section>(untrack(() => help ? "about" : "general"));
|
||||||
|
let query = $state("");
|
||||||
|
let seconds = $state<number | undefined>(untrack(() => settings.autosaveSeconds));
|
||||||
|
let message = $state("");
|
||||||
|
let error = $state("");
|
||||||
|
let dialog: HTMLDialogElement;
|
||||||
|
const matches = $derived(sections.filter(item => `${item.label} ${item.keywords}`.toLowerCase().includes(query.trim().toLowerCase())));
|
||||||
|
const selected = $derived(matches.find(item => item.id === section) ?? matches[0]);
|
||||||
|
|
||||||
|
$effect(() => { seconds = settings.autosaveSeconds; });
|
||||||
|
onMount(() => {
|
||||||
|
const previous = document.activeElement instanceof HTMLElement ? document.activeElement : null;
|
||||||
|
dialog.showModal();
|
||||||
|
return () => { dialog.close(); previous?.focus(); };
|
||||||
|
});
|
||||||
|
|
||||||
|
function apply(value: AppSettings) {
|
||||||
|
error = "";
|
||||||
|
try { onSave(value); message = "Changes saved."; }
|
||||||
|
catch { error = "Could not save these settings. Your previous settings still apply. Try again."; message = ""; }
|
||||||
|
}
|
||||||
|
|
||||||
|
function changeInterval() {
|
||||||
|
if (!validAutosaveSeconds(seconds)) {
|
||||||
|
error = "Choose a whole number from 1 to 300 seconds.";
|
||||||
|
message = "";
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
apply({ ...settings, autosaveSeconds: seconds });
|
||||||
|
}
|
||||||
|
|
||||||
|
function select(next: Section) { section = next; error = ""; message = ""; seconds = settings.autosaveSeconds; }
|
||||||
|
|
||||||
|
function trapFocus(event: KeyboardEvent) {
|
||||||
|
if (event.target instanceof Element && event.target.closest("dialog") !== dialog) return;
|
||||||
|
if (event.key !== "Tab") return;
|
||||||
|
const controls = [...dialog.querySelectorAll<HTMLElement>("button:not(:disabled), input:not(:disabled), summary")]
|
||||||
|
.filter(element => element.getClientRects().length > 0);
|
||||||
|
const first = controls[0], last = controls.at(-1);
|
||||||
|
if (event.shiftKey && document.activeElement === first) { event.preventDefault(); last?.focus(); }
|
||||||
|
else if (!event.shiftKey && document.activeElement === last) { event.preventDefault(); first?.focus(); }
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<dialog bind:this={dialog} class:help aria-labelledby="settings-title" onkeydown={trapFocus} oncancel={event => { if (event.target === dialog) { event.preventDefault(); onClose(); } }}>
|
||||||
|
<header>
|
||||||
|
<h1 id="settings-title">{help ? "Help and about" : "Settings"}</h1>
|
||||||
|
<IconButton icon="close" label={help ? "Close help" : "Close settings"} onclick={onClose} />
|
||||||
|
</header>
|
||||||
|
<div class="body">
|
||||||
|
{#if !help}
|
||||||
|
<aside>
|
||||||
|
<label class="search"><Icon icon="search" /><input aria-label="Search settings" placeholder="Search settings…" bind:value={query} /></label>
|
||||||
|
<p class="nav-heading">Preferences</p>
|
||||||
|
<nav aria-label="Settings categories">
|
||||||
|
{#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>
|
||||||
|
{/each}
|
||||||
|
</nav>
|
||||||
|
<p class="scope">For all workspaces on this device.</p>
|
||||||
|
</aside>
|
||||||
|
{/if}
|
||||||
|
<div class="content">
|
||||||
|
{#if !selected}
|
||||||
|
<h2>No settings found</h2>
|
||||||
|
<p>Try “save”, “plug-ins”, or “help”.</p>
|
||||||
|
<button class="text-button" onclick={() => query = ""}>Clear search</button>
|
||||||
|
{:else if selected.id === "general"}
|
||||||
|
<h2>General</h2>
|
||||||
|
<p class="intro">Choose how RuneStone saves your work.</p>
|
||||||
|
<h3>Files</h3>
|
||||||
|
<div class="card">
|
||||||
|
<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>
|
||||||
|
<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 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 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>
|
||||||
|
</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>
|
||||||
|
<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>
|
||||||
|
{#if error}<p class="error" role="alert">{error}</p>{/if}
|
||||||
|
<p class="saved" role="status">{message}</p>
|
||||||
|
{:else if selected.id === "plugins"}
|
||||||
|
<PluginManager />
|
||||||
|
{:else}
|
||||||
|
<div class="brand"><img src="/runestone.svg" alt="" width="88" height="88" /><h2>RuneStone</h2><p>Version {version}</p></div>
|
||||||
|
<div class="card help-card">
|
||||||
|
<details open><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="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="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>
|
||||||
|
</div>
|
||||||
|
<p class="about-note">RuneStone is under development. Maintained by kwyvern-gh.</p>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</dialog>
|
||||||
|
|
||||||
|
<style>
|
||||||
|
dialog { width: min(920px, calc(100vw - 32px)); height: min(650px, calc(100dvh - 32px)); max-width: none; max-height: none; padding: 0; background: var(--rs-bg); color: var(--rs-text); border: 1px solid var(--rs-border); border-radius: 12px; box-shadow: 0 24px 80px #0008; overflow: hidden; }
|
||||||
|
dialog::backdrop { background: #0008; }
|
||||||
|
dialog.help { width: min(650px, calc(100vw - 32px)); }
|
||||||
|
header { height: 48px; padding: 0 14px 0 20px; display: flex; align-items: center; justify-content: space-between; border-bottom: 1px solid var(--rs-border); background: var(--rs-bg-elevated); }
|
||||||
|
h1 { font-size: 14px; font-weight: 600; margin: 0; }
|
||||||
|
.body { display: flex; height: calc(100% - 48px); }
|
||||||
|
aside { width: 220px; flex-shrink: 0; padding: 18px 12px; background: var(--rs-bg-elevated); border-right: 1px solid var(--rs-border); display: flex; flex-direction: column; overflow: auto; }
|
||||||
|
.search { display: flex; gap: 7px; align-items: center; background: var(--rs-bg-active); border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); padding: 8px; color: var(--rs-text-dim); }
|
||||||
|
.search:focus-within { outline: 2px solid var(--rs-accent); }
|
||||||
|
.search input { width: 100%; min-width: 0; border: 0; padding: 0; outline: none; background: transparent; color: var(--rs-text); }
|
||||||
|
.nav-heading { margin: 24px 10px 8px; font-size: 11px; color: var(--rs-text-dim); }
|
||||||
|
nav { display: flex; flex-direction: column; gap: 4px; }
|
||||||
|
nav button { display: flex; align-items: center; gap: 10px; width: 100%; padding: 10px; border: 0; border-radius: var(--rs-control-radius); background: transparent; text-align: left; }
|
||||||
|
nav button:hover { background: var(--rs-bg-active); }
|
||||||
|
nav button.active { background: var(--rs-item-selection-bg); box-shadow: inset 0 0 0 var(--rs-item-selection-width) var(--rs-item-selection-border); border-radius: var(--rs-item-selection-radius); }
|
||||||
|
.scope { margin: auto 10px 0; padding-top: 24px; color: var(--rs-text-dim); font-size: 12px; }
|
||||||
|
.content { padding: 30px 32px; flex: 1; min-width: 0; overflow-y: auto; }
|
||||||
|
h2 { margin: 0; font-size: 23px; font-weight: 600; color: var(--rs-text-strong); }
|
||||||
|
h3 { margin: 28px 0 12px; font-size: 14px; font-weight: 600; }
|
||||||
|
p { color: var(--rs-text-dim); line-height: 1.6; }
|
||||||
|
.intro { margin: 7px 0 24px; }
|
||||||
|
.card { padding: 0 20px; background: var(--rs-bg-elevated); border: 1px solid var(--rs-border); border-radius: 10px; }
|
||||||
|
.setting-row { display: flex; align-items: center; justify-content: space-between; gap: 24px; padding: 22px 0; }
|
||||||
|
.setting-row + .setting-row { border-top: 1px solid var(--rs-border); }
|
||||||
|
.setting-row label { font-weight: 500; }
|
||||||
|
.setting-row p { margin: 5px 0 0; font-size: 12px; }
|
||||||
|
.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:checked { background: var(--rs-accent); border-color: var(--rs-accent); }
|
||||||
|
.switch:checked::before { transform: translateX(16px); background: var(--rs-bg); }
|
||||||
|
.interval { display: flex; flex-direction: column; align-items: flex-end; gap: 5px; font-size: 11px; color: var(--rs-text-dim); }
|
||||||
|
.interval input { width: 84px; padding: 9px; border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); background: var(--rs-bg); color: var(--rs-text); font-size: 14px; }
|
||||||
|
.interval input:disabled { opacity: .45; }
|
||||||
|
.note, .section-footer, .about-note { font-size: 12px; }
|
||||||
|
.note { margin: 16px 0 24px; }
|
||||||
|
.section-footer { display: flex; flex-wrap: wrap; gap: 12px; align-items: center; justify-content: space-between; color: var(--rs-text-dim); }
|
||||||
|
.text-button { border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); background: var(--rs-bg-elevated); padding: 8px 12px; color: var(--rs-text); }
|
||||||
|
.text-button:hover { background: var(--rs-bg-active); }
|
||||||
|
.saved { font-size: 12px; color: var(--rs-ok); min-height: 20px; }
|
||||||
|
.error { color: var(--rs-error); }
|
||||||
|
.brand { text-align: center; margin-bottom: 26px; }
|
||||||
|
.brand h2 { font-size: 28px; margin-top: 4px; }
|
||||||
|
.brand p { margin: 6px 0; font-size: 12px; }
|
||||||
|
.help-card details + details { border-top: 1px solid var(--rs-border); }
|
||||||
|
summary { display: flex; align-items: center; gap: 12px; padding: 18px 0; cursor: pointer; list-style: none; border-radius: var(--rs-control-radius); }
|
||||||
|
summary::after { content: "+"; margin-left: auto; color: var(--rs-text-dim); }
|
||||||
|
details[open] summary::after { content: "−"; }
|
||||||
|
.help-copy, dl { margin: 0 0 18px 28px; font-size: 12px; }
|
||||||
|
.help-copy p:first-child { margin-top: 0; }
|
||||||
|
dl div { display: flex; justify-content: space-between; gap: 12px; margin: 10px 0; }
|
||||||
|
dd { margin: 0; }
|
||||||
|
kbd { font-family: var(--rs-font-mono); color: var(--rs-text-dim); }
|
||||||
|
.about-note { text-align: center; margin: 20px 0 0; }
|
||||||
|
@media (max-width: 660px) {
|
||||||
|
.body { flex-direction: column; }
|
||||||
|
aside { width: 100%; padding: 12px; border-right: 0; border-bottom: 1px solid var(--rs-border); flex-shrink: 0; }
|
||||||
|
nav { flex-direction: row; margin-top: 10px; }
|
||||||
|
nav button { width: auto; flex: 1; padding: 8px; gap: 6px; }
|
||||||
|
.nav-heading, .scope { display: none; }
|
||||||
|
.content { padding: 24px 18px; }
|
||||||
|
.setting-row { gap: 14px; }
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -1,7 +1,10 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
|
import TerminalSlot from "$lib/plugins/TerminalSlot.svelte";
|
||||||
|
import PluginTools from "$lib/plugins/PluginTools.svelte";
|
||||||
import { onMount, tick } from "svelte";
|
import { onMount, tick } from "svelte";
|
||||||
import { selectedEditorText } from "$lib/editor/selection";
|
import { selectedEditorText } from "$lib/editor/selection";
|
||||||
import { terminalShortcut } from "$lib/terminal/model";
|
import { pluginHost } from "$lib/plugins/registry";
|
||||||
|
import type { Contributions } from "$lib/plugins/contracts";
|
||||||
import { isTauri } from "@tauri-apps/api/core";
|
import { isTauri } from "@tauri-apps/api/core";
|
||||||
import { getCurrentWindow } from "@tauri-apps/api/window";
|
import { getCurrentWindow } from "@tauri-apps/api/window";
|
||||||
import { confirm } from "@tauri-apps/plugin-dialog";
|
import { confirm } from "@tauri-apps/plugin-dialog";
|
||||||
@@ -13,6 +16,8 @@
|
|||||||
import TextDialog from "./TextDialog.svelte";
|
import TextDialog from "./TextDialog.svelte";
|
||||||
import QuickOpen from "./QuickOpen.svelte";
|
import QuickOpen from "./QuickOpen.svelte";
|
||||||
import WorkspacePicker from "./WorkspacePicker.svelte";
|
import WorkspacePicker from "./WorkspacePicker.svelte";
|
||||||
|
import SettingsDialog from "./SettingsDialog.svelte";
|
||||||
|
import { DEFAULT_SETTINGS, SETTINGS_KEY, parseSettings, saveSettings, type AppSettings } from "$lib/workspace/settings";
|
||||||
import FileTree from "./FileTree.svelte";
|
import FileTree from "./FileTree.svelte";
|
||||||
import EditorPane from "./EditorPane.svelte";
|
import EditorPane from "./EditorPane.svelte";
|
||||||
import TabBar from "./TabBar.svelte";
|
import TabBar from "./TabBar.svelte";
|
||||||
@@ -21,7 +26,7 @@
|
|||||||
import WindowControls from "$lib/ui/WindowControls.svelte";
|
import WindowControls from "$lib/ui/WindowControls.svelte";
|
||||||
import SearchPane from "./SearchPane.svelte";
|
import SearchPane from "./SearchPane.svelte";
|
||||||
import BookmarksPane from "./BookmarksPane.svelte";
|
import BookmarksPane from "./BookmarksPane.svelte";
|
||||||
import TerminalDock from "./TerminalDock.svelte";
|
|
||||||
import { buildOutline } from "$lib/workspace/outline";
|
import { buildOutline } from "$lib/workspace/outline";
|
||||||
import {
|
import {
|
||||||
onWorkspaceEvent,
|
onWorkspaceEvent,
|
||||||
@@ -46,6 +51,9 @@
|
|||||||
|
|
||||||
let workspace = $state<WorkspaceInfo | null>(null);
|
let workspace = $state<WorkspaceInfo | null>(null);
|
||||||
let workspacePicker: WorkspacePicker;
|
let workspacePicker: WorkspacePicker;
|
||||||
|
let preferences = $state<"settings" | "help" | null>(null);
|
||||||
|
let settings = $state<AppSettings>({ ...DEFAULT_SETTINGS });
|
||||||
|
let settingsReady = $state(false);
|
||||||
let workspaceAnchor: HTMLDivElement | undefined = $state();
|
let workspaceAnchor: HTMLDivElement | undefined = $state();
|
||||||
const desktop = isTauri();
|
const desktop = isTauri();
|
||||||
let tabs = $state<OpenBuffer[]>([]);
|
let tabs = $state<OpenBuffer[]>([]);
|
||||||
@@ -67,7 +75,16 @@
|
|||||||
let quickOpen = $state(false);
|
let quickOpen = $state(false);
|
||||||
let terminalStarted = $state(false);
|
let terminalStarted = $state(false);
|
||||||
let terminalMaximized = $state(false);
|
let terminalMaximized = $state(false);
|
||||||
let terminalDock: TerminalDock | undefined = $state();
|
let terminalDock: TerminalSlot | undefined = $state();
|
||||||
|
const terminalContribution = $derived.by(() => { void $pluginHost; return pluginHost.get("terminal"); });
|
||||||
|
const terminalEnabled = $derived(!!terminalContribution);
|
||||||
|
|
||||||
|
$effect(() => {
|
||||||
|
if (!terminalEnabled) {
|
||||||
|
terminalOpen = false; terminalStarted = false; terminalMaximized = false;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
let saving = $state(false);
|
let saving = $state(false);
|
||||||
let switching = false;
|
let switching = false;
|
||||||
let documents: Documents | null = null;
|
let documents: Documents | null = null;
|
||||||
@@ -110,18 +127,20 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
function toggleTerminal() {
|
function toggleTerminal() {
|
||||||
|
if (!terminalEnabled) return;
|
||||||
terminalOpen = !terminalOpen;
|
terminalOpen = !terminalOpen;
|
||||||
if (terminalOpen) terminalStarted = true;
|
if (terminalOpen) { terminalStarted = true; }
|
||||||
if (terminalOpen && bottomHeight < 220) bottomHeight = 260;
|
if (terminalOpen && bottomHeight < 220) bottomHeight = 260;
|
||||||
}
|
}
|
||||||
|
|
||||||
async function terminalAction(action: Exclude<ReturnType<typeof terminalShortcut>, null | "toggle">) {
|
async function terminalAction(action: Exclude<ReturnType<Contributions["terminal"]["shortcut"]>, null | "toggle">) {
|
||||||
|
if (!terminalEnabled) return;
|
||||||
if (!workspace) { error = "Open a workspace to start a terminal."; return; }
|
if (!workspace) { error = "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;
|
||||||
await tick();
|
await tick();
|
||||||
if (action !== "new" || started) await terminalDock?.command(action);
|
if (terminalEnabled && (action !== "new" || started)) await terminalDock?.command(action);
|
||||||
}
|
}
|
||||||
|
|
||||||
async function terminalFile(): Promise<string | null> {
|
async function terminalFile(): Promise<string | null> {
|
||||||
@@ -269,6 +288,14 @@
|
|||||||
} catch (err) { if (documents === current) error = String(err); }
|
} catch (err) { if (documents === current) error = String(err); }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function openCreatedFile(entry: TreeEntry) {
|
||||||
|
const current = documents;
|
||||||
|
await openFile(entry);
|
||||||
|
if (documents !== current || current?.active?.relPath !== entry.rel_path || !isMarkdownPath(entry.rel_path)) return;
|
||||||
|
reading = false;
|
||||||
|
editorPane?.focusTitle(current.active.id);
|
||||||
|
}
|
||||||
|
|
||||||
function readFileDataUrl(file: File): Promise<string> {
|
function readFileDataUrl(file: File): Promise<string> {
|
||||||
return new Promise((resolve, reject) => {
|
return new Promise((resolve, reject) => {
|
||||||
const reader = new FileReader();
|
const reader = new FileReader();
|
||||||
@@ -384,7 +411,7 @@
|
|||||||
try {
|
try {
|
||||||
await workspaceCreate(name.replaceAll("\\", "/"), "file");
|
await workspaceCreate(name.replaceAll("\\", "/"), "file");
|
||||||
refreshToken += 1;
|
refreshToken += 1;
|
||||||
await openFile({
|
await openCreatedFile({
|
||||||
name: name.split("/").pop() ?? name,
|
name: name.split("/").pop() ?? name,
|
||||||
rel_path: name.replaceAll("\\", "/"),
|
rel_path: name.replaceAll("\\", "/"),
|
||||||
kind: "file",
|
kind: "file",
|
||||||
@@ -394,9 +421,19 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function onPreferencesKeydown(event: KeyboardEvent) {
|
||||||
|
if (event.target instanceof Element && event.target.closest("dialog, [role=dialog], [role=menu]")) return;
|
||||||
|
if ((event.ctrlKey || event.metaKey) && !event.shiftKey && !event.altKey && event.key === ",") {
|
||||||
|
event.preventDefault(); event.stopPropagation(); preferences = "settings";
|
||||||
|
}
|
||||||
|
if (event.key === "F1" && !event.ctrlKey && !event.metaKey && !event.altKey && !event.shiftKey) {
|
||||||
|
event.preventDefault(); event.stopPropagation(); preferences = "help";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
function onKeydown(event: KeyboardEvent) {
|
function onKeydown(event: KeyboardEvent) {
|
||||||
if (event.target instanceof Element && event.target.closest("dialog, [role=dialog], [role=menu]")) return;
|
if (event.target instanceof Element && event.target.closest("dialog, [role=dialog], [role=menu]")) return;
|
||||||
const action = terminalShortcut(event);
|
const action = pluginHost.get("terminal")?.shortcut(event);
|
||||||
const terminalTarget = event.target instanceof Element && !!event.target.closest(".dock");
|
const terminalTarget = event.target instanceof Element && !!event.target.closest(".dock");
|
||||||
if (action && (["toggle", "new", "split", "window"].includes(action) || terminalTarget)) {
|
if (action && (["toggle", "new", "split", "window"].includes(action) || terminalTarget)) {
|
||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
@@ -431,7 +468,7 @@
|
|||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
toggleChrome();
|
toggleChrome();
|
||||||
}
|
}
|
||||||
if ((event.ctrlKey || event.metaKey) && event.key === "`") {
|
if (terminalEnabled && (event.ctrlKey || event.metaKey) && event.key === "`") {
|
||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
toggleTerminal();
|
toggleTerminal();
|
||||||
}
|
}
|
||||||
@@ -540,14 +577,38 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function updateSettings(next: AppSettings) {
|
||||||
|
saveSettings(localStorage, next);
|
||||||
|
settings = { ...next };
|
||||||
|
}
|
||||||
|
|
||||||
|
onMount(() => {
|
||||||
|
try { settings = parseSettings(localStorage.getItem(SETTINGS_KEY)); }
|
||||||
|
catch { error = "Could not read your settings. Default settings apply until you save new settings."; }
|
||||||
|
settingsReady = true;
|
||||||
|
const syncSettings = (event: StorageEvent) => {
|
||||||
|
if (event.storageArea === localStorage && (event.key === SETTINGS_KEY || event.key === null)) settings = parseSettings(event.newValue);
|
||||||
|
};
|
||||||
|
window.addEventListener("storage", syncSettings);
|
||||||
|
window.addEventListener("keydown", onPreferencesKeydown, true);
|
||||||
|
return () => {
|
||||||
|
window.removeEventListener("storage", syncSettings);
|
||||||
|
window.removeEventListener("keydown", onPreferencesKeydown, true);
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
$effect(() => {
|
||||||
|
if (!desktop || !settingsReady || !settings.autosaveEnabled) return;
|
||||||
|
const timer = setInterval(() => { void autosave(); }, settings.autosaveSeconds * 1000);
|
||||||
|
return () => clearInterval(timer);
|
||||||
|
});
|
||||||
|
|
||||||
onMount(() => {
|
onMount(() => {
|
||||||
if (!isTauri()) { status = "Desktop features require pnpm tauri dev"; return; }
|
if (!isTauri()) { status = "Desktop features require pnpm tauri dev"; return; }
|
||||||
void restoreLast();
|
void restoreLast();
|
||||||
let disposed = false;
|
let disposed = false;
|
||||||
const unlisteners: (() => void)[] = [];
|
const unlisteners: (() => void)[] = [];
|
||||||
let refreshTimer: ReturnType<typeof setTimeout>;
|
let refreshTimer: ReturnType<typeof setTimeout>;
|
||||||
// A fixed interval also saves during continuous typing; clean files never write.
|
|
||||||
const autosaveTimer = setInterval(() => { void autosave(); }, 5_000);
|
|
||||||
const register = (off: () => void) => { if (disposed) off(); else unlisteners.push(off); };
|
const register = (off: () => void) => { if (disposed) off(); else unlisteners.push(off); };
|
||||||
void onWorkspaceEvent((event) => {
|
void onWorkspaceEvent((event) => {
|
||||||
if (event.root !== workspace?.root || event.kind === "access") return;
|
if (event.root !== workspace?.root || event.kind === "access") return;
|
||||||
@@ -576,7 +637,6 @@
|
|||||||
documents?.dispose();
|
documents?.dispose();
|
||||||
clearTimeout(refreshTimer);
|
clearTimeout(refreshTimer);
|
||||||
unlisteners.forEach(off => off());
|
unlisteners.forEach(off => off());
|
||||||
clearInterval(autosaveTimer);
|
|
||||||
window.removeEventListener("focus", focus);
|
window.removeEventListener("focus", focus);
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
@@ -586,6 +646,7 @@
|
|||||||
<svelte:window onkeydown={onKeydown} onbeforeunload={(event) => { if (hasDirty) { event.preventDefault(); event.returnValue = ""; } }} />
|
<svelte:window onkeydown={onKeydown} onbeforeunload={(event) => { if (hasDirty) { event.preventDefault(); event.returnValue = ""; } }} />
|
||||||
<TextDialog />
|
<TextDialog />
|
||||||
<WorkspacePicker bind:this={workspacePicker} currentRoot={workspace?.root} anchor={workspaceAnchor} onOpen={openPath} />
|
<WorkspacePicker bind:this={workspacePicker} currentRoot={workspace?.root} anchor={workspaceAnchor} onOpen={openPath} />
|
||||||
|
{#if preferences}<SettingsDialog {settings} help={preferences === "help"} onSave={updateSettings} onClose={() => preferences = null} />{/if}
|
||||||
{#if quickOpen && workspace}<QuickOpen onOpen={(entry) => void openFile(entry)} onClose={() => quickOpen = false} />{/if}
|
{#if quickOpen && workspace}<QuickOpen onOpen={(entry) => void openFile(entry)} onClose={() => quickOpen = false} />{/if}
|
||||||
|
|
||||||
<div
|
<div
|
||||||
@@ -632,8 +693,9 @@
|
|||||||
{#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>
|
||||||
|
<PluginTools />
|
||||||
<IconButton icon="save" label="Save" disabled={!dirty || saving} onclick={() => void save()} />
|
<IconButton icon="save" label="Save" disabled={!dirty || saving} onclick={() => void save()} />
|
||||||
<IconButton icon="terminal" label="Terminal" active={terminalOpen} onclick={toggleTerminal} />
|
{#if terminalEnabled}<IconButton icon="terminal" label="Terminal" active={terminalOpen} onclick={toggleTerminal} />{/if}
|
||||||
<IconButton
|
<IconButton
|
||||||
icon="panel-right"
|
icon="panel-right"
|
||||||
label={rightOpen ? "Hide outline" : "Show outline"}
|
label={rightOpen ? "Hide outline" : "Show outline"}
|
||||||
@@ -659,7 +721,7 @@
|
|||||||
{refreshToken}
|
{refreshToken}
|
||||||
keysActive={leftView === "files"}
|
keysActive={leftView === "files"}
|
||||||
onCreated={(entry) => {
|
onCreated={(entry) => {
|
||||||
void openFile(entry);
|
void openCreatedFile(entry);
|
||||||
}}
|
}}
|
||||||
onStatus={(message) => {
|
onStatus={(message) => {
|
||||||
status = message;
|
status = message;
|
||||||
@@ -682,6 +744,10 @@
|
|||||||
<IconButton icon="folder-open" label="Open folder" onclick={chooseWorkspace} />
|
<IconButton icon="folder-open" label="Open folder" onclick={chooseWorkspace} />
|
||||||
<span class="ws">{workspace ? workspace.name : "No workspace"}</span>
|
<span class="ws">{workspace ? workspace.name : "No workspace"}</span>
|
||||||
</div>
|
</div>
|
||||||
|
<div class="footer-actions">
|
||||||
|
<IconButton icon="help" label="Help and about (F1)" onclick={() => preferences = "help"} />
|
||||||
|
<IconButton icon="settings" label="Settings (Ctrl+,)" onclick={() => preferences = "settings"} />
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</aside>
|
</aside>
|
||||||
|
|
||||||
@@ -727,7 +793,7 @@
|
|||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
</main>
|
</main>
|
||||||
{#if terminalStarted}
|
{#if terminalContribution && terminalStarted}
|
||||||
<div
|
<div
|
||||||
class="gutter gutter-h" class:terminal-hidden={!terminalOpen}
|
class="gutter gutter-h" class:terminal-hidden={!terminalOpen}
|
||||||
role="separator"
|
role="separator"
|
||||||
@@ -736,7 +802,7 @@
|
|||||||
<section class="bottom" class:terminal-hidden={!terminalOpen}>
|
<section class="bottom" class:terminal-hidden={!terminalOpen}>
|
||||||
{#if workspace}
|
{#if workspace}
|
||||||
{#key workspace.root}
|
{#key workspace.root}
|
||||||
<TerminalDock bind:this={terminalDock} cwd={workspace.root} visible={terminalOpen} onClose={toggleTerminal}
|
<TerminalSlot contribution={terminalContribution} bind:this={terminalDock} cwd={workspace.root} visible={terminalOpen} onClose={toggleTerminal}
|
||||||
maximized={terminalMaximized} onMaximize={() => terminalMaximized = !terminalMaximized}
|
maximized={terminalMaximized} onMaximize={() => terminalMaximized = !terminalMaximized}
|
||||||
activeFile={buffer?.kind === "text" && !reading} onRunFile={terminalFile}
|
activeFile={buffer?.kind === "text" && !reading} onRunFile={terminalFile}
|
||||||
getSelection={() => selectedEditorText(buffer?.id)} onConfigureTasks={configureTasks} />
|
getSelection={() => selectedEditorText(buffer?.id)} onConfigureTasks={configureTasks} />
|
||||||
@@ -973,12 +1039,16 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
.footer-start {
|
.footer-start {
|
||||||
|
flex: 1;
|
||||||
display: flex;
|
display: flex;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
gap: 2px;
|
gap: 2px;
|
||||||
min-width: 0;
|
min-width: 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.footer-actions { display: flex; align-items: center; gap: 4px; flex-shrink: 0; }
|
||||||
|
.footer-actions :global(.icon-btn) { width: 32px; height: 32px; flex-basis: 32px; }
|
||||||
|
|
||||||
.placeholder {
|
.placeholder {
|
||||||
margin: 12px;
|
margin: 12px;
|
||||||
color: var(--rs-text-dim);
|
color: var(--rs-text-dim);
|
||||||
|
|||||||
@@ -0,0 +1,177 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import { onDestroy } from "svelte";
|
||||||
|
import { invoke, isTauri } from "@tauri-apps/api/core";
|
||||||
|
import Icon from "$lib/ui/Icon.svelte";
|
||||||
|
import IconButton from "$lib/ui/IconButton.svelte";
|
||||||
|
import { installedPlugins, externalErrors, pluginServiceError, restartPlugins, refreshPlugins, setPluginEnabled } from "./external";
|
||||||
|
import type { Candidate, RemovalPlan, InstalledPlugin } from "./sdk";
|
||||||
|
const desktop = isTauri();
|
||||||
|
let busy = $state(false);
|
||||||
|
let error = $state("");
|
||||||
|
let message = $state("");
|
||||||
|
let candidates = $state<Candidate[]>([]);
|
||||||
|
let selected = $state<string[]>([]);
|
||||||
|
let plan = $state<RemovalPlan | null>(null);
|
||||||
|
let modal: HTMLDialogElement | undefined = $state();
|
||||||
|
let cancelButton: HTMLButtonElement | undefined = $state();
|
||||||
|
let previous: HTMLElement | null = null;
|
||||||
|
const external = $derived($installedPlugins.plugins);
|
||||||
|
$effect(() => {
|
||||||
|
if (modal && (plan || candidates.length)) {
|
||||||
|
if (!modal.open) { previous = document.activeElement instanceof HTMLElement ? document.activeElement : null; modal.showModal(); }
|
||||||
|
if (!busy) cancelButton?.focus();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
function tokens() { return [...candidates.map(item => item.token), ...(plan ? [plan.token] : [])]; }
|
||||||
|
async function cancel() {
|
||||||
|
if (busy) return;
|
||||||
|
const pending = tokens();
|
||||||
|
plan = null; candidates = []; selected = [];
|
||||||
|
modal?.close(); previous?.focus();
|
||||||
|
if (pending.length) await invoke("plugins_cancel", { tokens: pending }).catch(reason => error = String(reason));
|
||||||
|
}
|
||||||
|
onDestroy(() => { const pending = tokens(); if (pending.length) void invoke("plugins_cancel", { tokens: pending }).catch(() => {}); });
|
||||||
|
async function run(action: () => Promise<void>) {
|
||||||
|
busy = true; error = ""; message = "";
|
||||||
|
try { await action(); } catch (reason) { error = String(reason); }
|
||||||
|
finally { busy = false; }
|
||||||
|
}
|
||||||
|
async function choose(folder: boolean) {
|
||||||
|
await run(async () => {
|
||||||
|
candidates = await invoke<Candidate[]>("plugins_choose", { folder });
|
||||||
|
selected = candidates.filter(item => !item.error && item.manifest).map(item => item.token);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
async function install(enabled: boolean) {
|
||||||
|
await run(async () => {
|
||||||
|
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(" ");
|
||||||
|
error = result.filter(item => item.error).map(item => `${item.name}: ${item.error}`).join("\n");
|
||||||
|
await invoke("plugins_cancel", { tokens: candidates.map(item => item.token) });
|
||||||
|
candidates = []; selected = []; await refreshPlugins(); previous?.focus();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
async function toggle(id: string, enabled: boolean, hash?: string) {
|
||||||
|
await run(async () => {
|
||||||
|
await setPluginEnabled(id, enabled, hash);
|
||||||
|
message = "Changes saved.";
|
||||||
|
});
|
||||||
|
}
|
||||||
|
async function prepare(plugin: InstalledPlugin) {
|
||||||
|
await run(async () => { plan = await invoke<RemovalPlan>("plugins_prepare_remove", { id: plugin.manifest.id }); });
|
||||||
|
}
|
||||||
|
async function remove() {
|
||||||
|
if (!plan) return;
|
||||||
|
const current = plan;
|
||||||
|
await run(async () => {
|
||||||
|
try { await invoke("plugins_remove", { token: current.token }); message = `${current.plugin.manifest.name} uninstalled. Settings and workspace documents were kept.`; }
|
||||||
|
finally { plan = null; await refreshPlugins(); previous?.focus(); }
|
||||||
|
});
|
||||||
|
}
|
||||||
|
async function reveal(id?: string) { await run(async () => { await invoke("plugins_reveal", { id: id ?? null }); }); }
|
||||||
|
function trap(event: KeyboardEvent) {
|
||||||
|
event.stopPropagation();
|
||||||
|
if (event.repeat && (event.key === "Enter" || event.key === " ")) event.preventDefault();
|
||||||
|
if (event.key !== "Tab" || !modal) return;
|
||||||
|
const controls = [...modal.querySelectorAll<HTMLElement>("button:not(:disabled),input:not(:disabled)")];
|
||||||
|
const first = controls[0], last = controls.at(-1);
|
||||||
|
if (event.shiftKey && document.activeElement === first) { event.preventDefault(); last?.focus(); }
|
||||||
|
else if (!event.shiftKey && document.activeElement === last) { event.preventDefault(); first?.focus(); }
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<h2>Plug-ins</h2>
|
||||||
|
<p>Install a package file or select a folder containing plugins.</p>
|
||||||
|
<div class="toolbar">
|
||||||
|
<button disabled={!desktop || busy} onclick={() => choose(false)}><Icon icon="file-plus" />Install from file</button>
|
||||||
|
<button disabled={!desktop || busy} onclick={() => choose(true)}><Icon icon="folder-plus" />Install from folder</button>
|
||||||
|
<IconButton icon="folder-open" label="Open plugins folder" disabled={!desktop || busy} onclick={() => reveal()} />
|
||||||
|
<button disabled={!desktop || busy} onclick={() => run(refreshPlugins)}><Icon icon="refresh" />Refresh</button>
|
||||||
|
</div>
|
||||||
|
{#if $installedPlugins.root}<p class="path">{$installedPlugins.root}</p>{/if}
|
||||||
|
{#if !desktop}<p>Installation requires the RuneStone desktop app.</p>{/if}
|
||||||
|
{#if $pluginServiceError}<p class="error" role="alert">{$pluginServiceError}</p>{/if}
|
||||||
|
<h3>Installed plugins</h3>
|
||||||
|
<p class="note">Plugins run with RuneStone's access. Only enable code you trust.</p>
|
||||||
|
{#if !external.length}<p>No plugins installed.</p>{/if}
|
||||||
|
{#each external as plugin (plugin.manifest.id)}
|
||||||
|
<div class="card">
|
||||||
|
<div class="row">
|
||||||
|
<div><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>
|
||||||
|
<input id={`external-${plugin.manifest.id}`} type="checkbox" role="switch" checked={plugin.enabled} disabled={busy || plugin.removal} onchange={event => { const value = event.currentTarget.checked; event.currentTarget.checked = plugin.enabled; void toggle(plugin.manifest.id, value, plugin.hash); }} />
|
||||||
|
</div>
|
||||||
|
<p class="path">{plugin.path}</p>
|
||||||
|
{#if plugin.error || $externalErrors[plugin.manifest.id]}<p class="error" role="alert">{plugin.error || $externalErrors[plugin.manifest.id]}</p>{/if}
|
||||||
|
<div class="actions">
|
||||||
|
<span class="badge">{plugin.removal ? "Removal incomplete" : plugin.enabled ? "Enabled" : "Disabled"}</span>
|
||||||
|
<button disabled={busy || plugin.removal} onclick={() => reveal(plugin.manifest.id)}><Icon icon="folder-open" />Show files</button>
|
||||||
|
{#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>
|
||||||
|
{:else}
|
||||||
|
<button class="danger" disabled={busy} aria-label={`Uninstall ${plugin.manifest.name}`} onclick={() => prepare(plugin)}><Icon icon="trash" />Uninstall</button>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{/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 error}<p class="error" role="alert">{error}</p>{/if}
|
||||||
|
<p class="saved" role="status">{message}</p>
|
||||||
|
|
||||||
|
{#if candidates.length || plan}
|
||||||
|
<dialog bind:this={modal} aria-labelledby="plugin-dialog-title" onkeydown={trap} oncancel={event => { event.preventDefault(); event.stopPropagation(); void cancel(); }}>
|
||||||
|
{#if plan}
|
||||||
|
<h2 id="plugin-dialog-title">{`Uninstall ${plan.plugin.manifest.name}?`}</h2>
|
||||||
|
<p>{plan.plugin.manifest.author} · {plan.plugin.manifest.version}</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>
|
||||||
|
{#if error}<p class="error" role="alert">{error}</p>{/if}
|
||||||
|
<footer>
|
||||||
|
<button bind:this={cancelButton} disabled={busy} onclick={() => cancel()}>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 class="danger" disabled={busy} onclick={event => { if (event.detail < 2) void remove(); }}>{busy ? "Removing…" : "Uninstall and delete files"}</button>
|
||||||
|
</footer>
|
||||||
|
{:else}
|
||||||
|
<h2 id="plugin-dialog-title">Review plugin installation</h2>
|
||||||
|
<p>Plugins run with RuneStone's access. Only enable code you trust.</p>
|
||||||
|
{#each candidates as candidate (candidate.token)}
|
||||||
|
<div class="candidate">
|
||||||
|
<label><input type="checkbox" bind:group={selected} value={candidate.token} disabled={busy || !!candidate.error} />{candidate.manifest?.name ?? "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}
|
||||||
|
<p class="path">Source: {candidate.source}</p>
|
||||||
|
{#if candidate.error}<p class="error">{candidate.error}</p>{/if}
|
||||||
|
</div>
|
||||||
|
{/each}
|
||||||
|
{#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>
|
||||||
|
{/if}
|
||||||
|
</dialog>
|
||||||
|
{/if}
|
||||||
|
|
||||||
|
<style>
|
||||||
|
h2 { margin: 0; font-size: 23px; color: var(--rs-text-strong); }
|
||||||
|
h3 { font-size: 14px; margin: 24px 0 10px; }
|
||||||
|
p { color: var(--rs-text-dim); line-height: 1.6; }
|
||||||
|
button { display: inline-flex; align-items: center; justify-content: center; gap: 7px; padding: 8px 10px; color: var(--rs-text); background: var(--rs-bg-elevated); border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); }
|
||||||
|
button:hover:not(:disabled) { background: var(--rs-bg-active); }
|
||||||
|
button:disabled { opacity: .5; }
|
||||||
|
.toolbar, .actions, footer { display: flex; align-items: center; flex-wrap: wrap; gap: 8px; }
|
||||||
|
.card { background: var(--rs-bg-elevated); border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); padding: 0 18px 14px; margin-bottom: 12px; }
|
||||||
|
.row { display: flex; align-items: center; justify-content: space-between; gap: 20px; padding: 18px 0; }
|
||||||
|
.row p { margin: 5px 0; font-size: 12px; }
|
||||||
|
label { font-weight: 500; }
|
||||||
|
.path { overflow-wrap: anywhere; font-size: 11px; }
|
||||||
|
small, .badge, .note { color: var(--rs-text-dim); font-size: 12px; }
|
||||||
|
.badge { margin-right: auto; }
|
||||||
|
.error { color: var(--rs-error); white-space: pre-wrap; }
|
||||||
|
.saved { color: var(--rs-ok); min-height: 20px; }
|
||||||
|
.danger { color: var(--rs-error); }
|
||||||
|
input[role=switch] { appearance: none; width: 38px; height: 22px; flex: 0 0 38px; border-radius: 20px; background: var(--rs-bg-active); border: 1px solid var(--rs-text-dim); cursor: pointer; }
|
||||||
|
input[role=switch]::before { content: ""; display: block; width: 16px; height: 16px; margin: 2px; background: var(--rs-text); border-radius: 50%; }
|
||||||
|
input[role=switch]:checked { background: var(--rs-accent); border-color: var(--rs-accent); }
|
||||||
|
input[role=switch]:checked::before { transform: translateX(16px); background: var(--rs-bg); }
|
||||||
|
dialog { width: min(650px, 90vw); max-height: 85vh; padding: 24px; color: var(--rs-text); background: var(--rs-bg); border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); }
|
||||||
|
dialog::backdrop { background: #0009; }
|
||||||
|
footer { justify-content: flex-end; margin-top: 24px; }
|
||||||
|
.candidate { padding: 16px 0; border-bottom: 1px solid var(--rs-border); }
|
||||||
|
.candidate label { display: flex; gap: 8px; }
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,64 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import { onMount } from "svelte";
|
||||||
|
import Icon from "$lib/ui/Icon.svelte";
|
||||||
|
import IconButton from "$lib/ui/IconButton.svelte";
|
||||||
|
import { pluginTools, pluginView, openPluginView, runPluginCommand, mountPluginView } from "./external";
|
||||||
|
let menu = $state(false);
|
||||||
|
let error = $state("");
|
||||||
|
let dialog: HTMLDialogElement | undefined = $state();
|
||||||
|
let host: HTMLDivElement | undefined = $state();
|
||||||
|
let previous: HTMLElement | null = null;
|
||||||
|
$effect(() => {
|
||||||
|
const view = $pluginView;
|
||||||
|
const element = host;
|
||||||
|
const modal = dialog;
|
||||||
|
if (!view || !element || !modal) return;
|
||||||
|
previous = document.activeElement instanceof HTMLElement ? document.activeElement : null;
|
||||||
|
modal.showModal(); error = "";
|
||||||
|
let cancelled = false;
|
||||||
|
let cleanup: (() => void | Promise<void>) | undefined;
|
||||||
|
void mountPluginView(view.owner, view.id, element).then(dispose => {
|
||||||
|
if (cancelled) void Promise.resolve(dispose()).catch(reason => error = String(reason)); else cleanup = dispose;
|
||||||
|
}).catch(reason => { if (!cancelled) error = String(reason); });
|
||||||
|
return () => { cancelled = true; void Promise.resolve(cleanup?.()).catch(reason => error = String(reason)); modal.close(); previous?.focus(); };
|
||||||
|
});
|
||||||
|
onMount(() => {
|
||||||
|
const close = (event: PointerEvent) => { if (!(event.target as Element)?.closest(".plugin-tools")) menu = false; };
|
||||||
|
window.addEventListener("pointerdown", close);
|
||||||
|
return () => window.removeEventListener("pointerdown", close);
|
||||||
|
});
|
||||||
|
</script>
|
||||||
|
|
||||||
|
{#if $pluginTools.length}
|
||||||
|
<div class="plugin-tools">
|
||||||
|
<IconButton icon="puzzle" label="Plugin commands and views" active={menu} onclick={() => menu = !menu} />
|
||||||
|
{#if menu}
|
||||||
|
<div class="tools" role="group" aria-label="Plugin commands and views">
|
||||||
|
{#each $pluginTools as tool (`${tool.owner}:${tool.kind}:${tool.id}`)}
|
||||||
|
<button onkeydown={event => { if (event.key === "Escape") menu = false; }} onclick={() => { menu = false; if (tool.kind === "view") openPluginView(tool.owner, tool.id); else void runPluginCommand(tool.owner, tool.id).catch(reason => error = String(reason)); }}><Icon icon={tool.kind === "view" ? "panel-right" : "code"} /><span>{tool.title}<small>{tool.owner}</small></span></button>
|
||||||
|
{/each}
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
{#if error && !$pluginView}<p class="error" role="alert">{error}<button onclick={() => error = ""}>Dismiss</button></p>{/if}
|
||||||
|
{#if $pluginView}
|
||||||
|
<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>
|
||||||
|
{#if error}<p class="error" role="alert">{error}</p>{/if}
|
||||||
|
<div class="plugin-content" bind:this={host}></div>
|
||||||
|
</dialog>
|
||||||
|
{/if}
|
||||||
|
<style>
|
||||||
|
.plugin-tools { position: relative; }
|
||||||
|
.tools { position: absolute; right: 0; top: 38px; width: 280px; max-height: 60vh; overflow: auto; z-index: 50; padding: 6px; background: var(--rs-bg-elevated); border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); box-shadow: 0 8px 24px #0008; }
|
||||||
|
.tools button { display: flex; gap: 10px; align-items: center; text-align: left; width: 100%; padding: 9px; border: 0; border-radius: var(--rs-control-radius); background: transparent; }
|
||||||
|
.tools button:hover { background: var(--rs-bg-active); }
|
||||||
|
small { display: block; color: var(--rs-text-dim); margin-top: 4px; }
|
||||||
|
dialog { width: min(800px, 90vw); max-height: 85vh; padding: 20px; color: var(--rs-text); background: var(--rs-bg); border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); }
|
||||||
|
dialog::backdrop { background: #0008; }
|
||||||
|
header { display: flex; justify-content: space-between; align-items: center; }
|
||||||
|
h2 { font-size: 18px; }
|
||||||
|
.plugin-content { min-height: 140px; }
|
||||||
|
.error { color: var(--rs-error); }
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import { onMount } from "svelte";
|
||||||
|
import type { Contributions, TerminalProps, TerminalMount, TerminalAction } from "./contracts";
|
||||||
|
let { contribution, ...props }: TerminalProps & { contribution: Contributions["terminal"] } = $props();
|
||||||
|
let container: HTMLDivElement;
|
||||||
|
let mounted = $state.raw<TerminalMount>();
|
||||||
|
let error = $state("");
|
||||||
|
onMount(() => {
|
||||||
|
try { mounted = contribution.mount(container, { ...props }); }
|
||||||
|
catch (reason) { error = String(reason); }
|
||||||
|
return () => { void Promise.resolve(mounted?.dispose()).catch(reason => error = String(reason)); mounted = undefined; };
|
||||||
|
});
|
||||||
|
$effect(() => { mounted?.update({ ...props }); });
|
||||||
|
export async function command(action: Exclude<TerminalAction, "toggle">) { await mounted?.command(action); }
|
||||||
|
</script>
|
||||||
|
{#if error}<p role="alert">{error}</p>{/if}
|
||||||
|
<div class="plugin-terminal" bind:this={container}></div>
|
||||||
|
<style>.plugin-terminal { display: flex; flex-direction: column; flex: 1; height: 100%; min-height: 0; min-width: 0; }</style>
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
import type { Token } from "markdown-it";
|
||||||
|
import type { Dispose } from "./sdk.ts";
|
||||||
|
|
||||||
|
export type TerminalAction = "toggle" | "new" | "window" | "split" | "previous" | "next" | "commands" | "directories";
|
||||||
|
export interface TerminalProps {
|
||||||
|
cwd: string; visible: boolean; maximized?: boolean; standalone?: boolean;
|
||||||
|
onClose: () => void; onMaximize?: () => void; activeFile?: boolean;
|
||||||
|
onRunFile?: () => Promise<string | null>; getSelection?: () => string; onConfigureTasks?: () => Promise<void>;
|
||||||
|
}
|
||||||
|
export interface TerminalMount {
|
||||||
|
update(props: TerminalProps): void;
|
||||||
|
command(action: Exclude<TerminalAction, "toggle">): void | Promise<void>;
|
||||||
|
dispose: Dispose;
|
||||||
|
}
|
||||||
|
export type FormulaErrorCode = "#ERROR!" | "#REF!" | "#VALUE!" | "#NAME?" | "#DIV/0!" | "#CYCLE!" | "#NUM!" | "#LIMIT!";
|
||||||
|
export type FormulaResult = { formula: string; text: string; value?: number; error?: FormulaErrorCode };
|
||||||
|
export interface Contributions {
|
||||||
|
terminal: {
|
||||||
|
mount(container: HTMLElement, props: TerminalProps): TerminalMount;
|
||||||
|
shortcut(event: Pick<KeyboardEvent, "ctrlKey" | "metaKey" | "altKey" | "shiftKey" | "code" | "key">): TerminalAction | null;
|
||||||
|
};
|
||||||
|
tableFormulas: {
|
||||||
|
formulaErrors: Record<FormulaErrorCode, string>;
|
||||||
|
isTableFormula(text: string): boolean;
|
||||||
|
cellAddress(row: number, column: number): string;
|
||||||
|
evaluateTableFormulas(rows: string[][]): (FormulaResult | null)[][];
|
||||||
|
tableFormulaHtml(result: FormulaResult): string;
|
||||||
|
renderTableFormulas(tokens: Token[]): void;
|
||||||
|
createFormulaTools(finish: () => void, measure: () => void): { formulaTools: HTMLDivElement; formulaStatus: HTMLSpanElement; formulaHint: HTMLDivElement };
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,127 @@
|
|||||||
|
import { writable } from "svelte/store";
|
||||||
|
import { invoke, isTauri } from "@tauri-apps/api/core";
|
||||||
|
import { listen } from "@tauri-apps/api/event";
|
||||||
|
import { workspaceList, workspaceRead, workspaceWrite } from "../workspace/api";
|
||||||
|
import { ExternalSession, deadline } from "./externalSession";
|
||||||
|
import type { PluginModule, PluginSnapshot, InstalledPlugin, Dispose } from "./sdk";
|
||||||
|
|
||||||
|
export const installedPlugins = writable<PluginSnapshot>({ root: "", plugins: [] });
|
||||||
|
export const externalErrors = writable<Record<string, string>>({});
|
||||||
|
export const pluginTools = writable<{ owner: string; id: string; title: string; kind: "command" | "view" }[]>([]);
|
||||||
|
export const pluginView = writable<{ owner: string; id: string; title: string } | null>(null);
|
||||||
|
export const pluginServiceError = writable("");
|
||||||
|
export const restartPlugins = writable<string[]>([]);
|
||||||
|
const sessions = new Map<string, { hash: string; session: ExternalSession }>();
|
||||||
|
const failures = new Map<string, string>();
|
||||||
|
const errors: Record<string, string> = {};
|
||||||
|
const restarted = new Set<string>();
|
||||||
|
let queue: Promise<void> = Promise.resolve();
|
||||||
|
let started = false;
|
||||||
|
let generation = 0;
|
||||||
|
|
||||||
|
function publish() {
|
||||||
|
pluginTools.set([...sessions].flatMap(([owner, { session }]) => [
|
||||||
|
...[...session.commands.values()].map(({ id, title }) => ({ owner, id, title, kind: "command" as const })),
|
||||||
|
...[...session.views.values()].map(({ id, title }) => ({ owner, id, title, kind: "view" as const })),
|
||||||
|
]));
|
||||||
|
externalErrors.set({ ...errors });
|
||||||
|
}
|
||||||
|
function report(id: string, reason: unknown) { errors[id] = String(reason); publish(); }
|
||||||
|
async function release(id: string, error?: string) {
|
||||||
|
await invoke("plugins_release", { id, error: error ?? null });
|
||||||
|
}
|
||||||
|
async function stop(id: string) {
|
||||||
|
const loaded = sessions.get(id);
|
||||||
|
if (!loaded) return;
|
||||||
|
sessions.delete(id);
|
||||||
|
pluginView.update(view => view?.owner === id ? null : view);
|
||||||
|
restarted.add(id); restartPlugins.set([...restarted]);
|
||||||
|
let error: string | undefined;
|
||||||
|
try { await loaded.session.stop(); } catch (reason) { error = String(reason); report(id, reason); }
|
||||||
|
await release(id, error); publish();
|
||||||
|
}
|
||||||
|
function show(owner: string, id: string) {
|
||||||
|
const view = sessions.get(owner)?.session.views.get(id);
|
||||||
|
if (view) pluginView.set({ owner, id, title: view.title });
|
||||||
|
}
|
||||||
|
async function activate(row: InstalledPlugin) {
|
||||||
|
const id = row.manifest.id;
|
||||||
|
let leased = false;
|
||||||
|
const session = new ExternalSession(id, {
|
||||||
|
workspace: { list: path => workspaceList(path ?? ""), read: workspaceRead, write: workspaceWrite },
|
||||||
|
settings: {
|
||||||
|
read: async () => JSON.parse(await invoke<string>("plugins_data", { id, value: null })),
|
||||||
|
write: async value => { const json = JSON.stringify(value); if (json === undefined) throw new Error("Plugin settings must be JSON data."); await invoke("plugins_data", { id, value: json }); },
|
||||||
|
},
|
||||||
|
assets: { read: async path => Uint8Array.from(atob(await invoke<string>("plugins_asset", { id, path })), char => char.charCodeAt(0)) },
|
||||||
|
}, publish, view => show(id, view));
|
||||||
|
try {
|
||||||
|
const code = await invoke<string>("plugins_load", { id, hash: row.hash }); leased = true;
|
||||||
|
const url = URL.createObjectURL(new Blob([code], { type: "text/javascript" }));
|
||||||
|
let module: PluginModule;
|
||||||
|
try { module = await deadline(import(/* @vite-ignore */ url)); }
|
||||||
|
catch (reason) { await release(id, String(reason)); leased = false; throw reason; }
|
||||||
|
finally { URL.revokeObjectURL(url); }
|
||||||
|
sessions.set(id, { hash: row.hash, session });
|
||||||
|
await session.start(module);
|
||||||
|
delete errors[id]; publish();
|
||||||
|
} catch (reason) {
|
||||||
|
failures.set(id, row.hash); report(id, reason);
|
||||||
|
let cleanupError: string | undefined;
|
||||||
|
try { await session.stop(); } catch (error) { cleanupError = String(error); }
|
||||||
|
sessions.delete(id);
|
||||||
|
if (leased) await release(id, cleanupError);
|
||||||
|
publish();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
export function refreshPlugins(): Promise<void> {
|
||||||
|
if (!isTauri()) return Promise.resolve();
|
||||||
|
const version = generation;
|
||||||
|
const job = async () => {
|
||||||
|
try {
|
||||||
|
const snapshot = await invoke<PluginSnapshot | null>("plugins_snapshot");
|
||||||
|
if (!snapshot || version !== generation) return;
|
||||||
|
installedPlugins.set(snapshot); pluginServiceError.set("");
|
||||||
|
for (const id of sessions.keys()) {
|
||||||
|
const row = snapshot.plugins.find(row => row.manifest.id === id);
|
||||||
|
if (!row?.enabled || row.hash !== sessions.get(id)?.hash) await stop(id);
|
||||||
|
}
|
||||||
|
for (const row of snapshot.plugins) {
|
||||||
|
const id = row.manifest.id;
|
||||||
|
if (!row.enabled) { failures.delete(id); continue; }
|
||||||
|
if (!sessions.has(id) && failures.get(id) !== row.hash && version === generation) await activate(row);
|
||||||
|
}
|
||||||
|
} catch (reason) { pluginServiceError.set(String(reason)); }
|
||||||
|
};
|
||||||
|
queue = queue.then(job, job);
|
||||||
|
return queue;
|
||||||
|
}
|
||||||
|
export async function setPluginEnabled(id: string, enabled: boolean, hash?: string) {
|
||||||
|
await invoke("plugins_set_enabled", { id, enabled, hash: hash ?? null });
|
||||||
|
await refreshPlugins();
|
||||||
|
}
|
||||||
|
export async function runPluginCommand(owner: string, id: string) {
|
||||||
|
try { await sessions.get(owner)?.session.run(id); } catch (error) { report(owner, error); throw error; }
|
||||||
|
}
|
||||||
|
export function openPluginView(owner: string, id: string) { show(owner, id); }
|
||||||
|
export async function mountPluginView(owner: string, id: string, element: HTMLElement): Promise<Dispose> {
|
||||||
|
const session = sessions.get(owner)?.session;
|
||||||
|
if (!session) throw new Error("The plugin is disabled.");
|
||||||
|
return session.mount(id, element);
|
||||||
|
}
|
||||||
|
export function startExternalPlugins(): () => void {
|
||||||
|
if (!isTauri() || started) return () => {};
|
||||||
|
started = true;
|
||||||
|
let disposed = false;
|
||||||
|
let off: (() => void) | undefined;
|
||||||
|
void listen("plugins-changed", () => { void refreshPlugins(); }).then(unlisten => { if (disposed) unlisten(); else off = unlisten; }).catch(reason => pluginServiceError.set(String(reason)));
|
||||||
|
void refreshPlugins();
|
||||||
|
const focus = () => { void refreshPlugins(); };
|
||||||
|
window.addEventListener("focus", focus);
|
||||||
|
// Also detects changes made in a file manager while this window stays open.
|
||||||
|
const timer = setInterval(focus, 5000);
|
||||||
|
return () => {
|
||||||
|
disposed = true; started = false; generation++; off?.(); clearInterval(timer); window.removeEventListener("focus", focus);
|
||||||
|
for (const id of [...sessions.keys()]) void stop(id).catch(reason => report(id, reason));
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,99 @@
|
|||||||
|
import { pluginHost, type ContributionRegistry } from "./registry.ts";
|
||||||
|
import type { Dispose, PluginApi, PluginCommand, PluginModule, PluginView } from "./sdk.ts";
|
||||||
|
|
||||||
|
export function deadline<T>(work: Promise<T>, milliseconds = 5000): Promise<T> {
|
||||||
|
let timer: ReturnType<typeof setTimeout>;
|
||||||
|
return Promise.race([work, new Promise<never>((_, reject) => { timer = setTimeout(() => reject(new Error("Plugin cleanup or activation timed out. Restart RuneStone.")), milliseconds); })]).finally(() => clearTimeout(timer));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Revokes host access before cleanup, including when activation is still pending. */
|
||||||
|
export class ExternalSession {
|
||||||
|
readonly controller = new AbortController();
|
||||||
|
readonly commands = new Map<string, PluginCommand>();
|
||||||
|
readonly views = new Map<string, PluginView>();
|
||||||
|
private cleanups: Dispose[] = [];
|
||||||
|
private stopped = false;
|
||||||
|
private activation: Promise<void> = Promise.resolve();
|
||||||
|
private stopping?: Promise<void>;
|
||||||
|
private lateCleanup?: Promise<void>;
|
||||||
|
private mounted = new Set<Dispose>();
|
||||||
|
private contributions: Dispose[] = [];
|
||||||
|
private registry: ContributionRegistry;
|
||||||
|
readonly id: string;
|
||||||
|
private services: Pick<PluginApi, "workspace" | "settings" | "assets">;
|
||||||
|
private changed: () => void;
|
||||||
|
private show: (id: string) => void;
|
||||||
|
constructor(id: string, services: Pick<PluginApi, "workspace" | "settings" | "assets">, changed: () => void, show: (id: string) => void, registry: ContributionRegistry = pluginHost) {
|
||||||
|
this.registry = registry; this.id = id; this.services = services; this.changed = changed; this.show = show;
|
||||||
|
}
|
||||||
|
private check() { if (this.stopped) throw new Error("This plugin is disabled."); }
|
||||||
|
async start(module: PluginModule) {
|
||||||
|
const register = <T extends { id: string; title: string }>(map: Map<string, T>, item: T) => {
|
||||||
|
this.check();
|
||||||
|
if (!/^[a-z][a-z0-9.-]*$/.test(item.id) || !item.title?.trim() || map.has(item.id)) throw new Error("Invalid or duplicate plugin contribution.");
|
||||||
|
map.set(item.id, item); this.changed();
|
||||||
|
};
|
||||||
|
const api: PluginApi = {
|
||||||
|
id: this.id, signal: this.controller.signal,
|
||||||
|
contribute: (key, value) => { this.check(); this.contributions.push(this.registry.register(this.id, key, value)); },
|
||||||
|
registerCommand: item => { if (typeof item.run !== "function") throw new Error("A command needs a run function."); register(this.commands, item); },
|
||||||
|
registerView: item => { if (typeof item.mount !== "function") throw new Error("A view needs a mount function."); register(this.views, item); },
|
||||||
|
openView: id => { this.check(); if (!this.views.has(id)) throw new Error("Unknown plugin view."); this.show(id); },
|
||||||
|
onDispose: cleanup => { this.check(); if (typeof cleanup !== "function") throw new Error("Cleanup must be a function."); this.cleanups.push(cleanup); },
|
||||||
|
workspace: {
|
||||||
|
list: path => { this.check(); return this.services.workspace.list(path); },
|
||||||
|
read: path => { this.check(); return this.services.workspace.read(path); },
|
||||||
|
write: (path, value, expected) => { this.check(); if (typeof expected !== "string") throw new Error("Supply the original file text before writing."); return this.services.workspace.write(path, value, expected); },
|
||||||
|
},
|
||||||
|
settings: {
|
||||||
|
read: () => { this.check(); return this.services.settings.read(); },
|
||||||
|
write: value => { this.check(); return this.services.settings.write(value); },
|
||||||
|
},
|
||||||
|
assets: { read: path => { this.check(); return this.services.assets.read(path); } },
|
||||||
|
};
|
||||||
|
this.activation = Promise.resolve().then(() => {
|
||||||
|
if (typeof module.activate !== "function") throw new Error("The plugin must export activate(api).");
|
||||||
|
this.check(); return module.activate(api);
|
||||||
|
}).then(async cleanup => {
|
||||||
|
if (typeof cleanup === "function") {
|
||||||
|
if (this.stopped) { this.lateCleanup = Promise.resolve().then(cleanup); await this.lateCleanup; } else this.cleanups.push(cleanup);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
await deadline(this.activation);
|
||||||
|
}
|
||||||
|
async run(id: string) { this.check(); const command = this.commands.get(id); if (!command) throw new Error("Unknown plugin command."); await command.run(); }
|
||||||
|
async mount(id: string, element: HTMLElement): Promise<Dispose> {
|
||||||
|
this.check(); const view = this.views.get(id); if (!view) throw new Error("Unknown plugin view.");
|
||||||
|
let cleaning: Promise<void> | undefined;
|
||||||
|
const pending = Promise.resolve().then(() => { this.check(); return view.mount(element); });
|
||||||
|
const cleanup = () => {
|
||||||
|
cleaning ??= (async () => {
|
||||||
|
const dispose = await pending;
|
||||||
|
if (typeof dispose === "function") await dispose();
|
||||||
|
element.replaceChildren(); this.mounted.delete(cleanup);
|
||||||
|
})();
|
||||||
|
return cleaning;
|
||||||
|
};
|
||||||
|
this.mounted.add(cleanup);
|
||||||
|
try { await deadline(pending); } catch (error) { await deadline(cleanup()).catch(() => {}); throw error; }
|
||||||
|
if (this.stopped) await cleanup();
|
||||||
|
return cleanup;
|
||||||
|
}
|
||||||
|
stop(): Promise<void> {
|
||||||
|
if (this.stopping) return this.stopping;
|
||||||
|
this.stopped = true; this.controller.abort(); this.commands.clear(); this.views.clear(); this.changed();
|
||||||
|
for (const remove of this.contributions.splice(0)) remove();
|
||||||
|
this.stopping = (async () => {
|
||||||
|
const errors: unknown[] = [];
|
||||||
|
// Activation rejection is reported by start. A timeout still blocks removal.
|
||||||
|
try { await deadline(this.activation.catch(() => {})); } catch (error) { errors.push(error); }
|
||||||
|
if (this.lateCleanup) { try { await deadline(this.lateCleanup); } catch (error) { errors.push(error); } }
|
||||||
|
for (const cleanup of [...this.mounted, ...this.cleanups.reverse()]) {
|
||||||
|
try { await deadline(Promise.resolve().then(cleanup)); } catch (error) { errors.push(error); }
|
||||||
|
}
|
||||||
|
this.cleanups = [];
|
||||||
|
if (errors.length) throw new Error(errors.map(String).join("\n"));
|
||||||
|
})();
|
||||||
|
return this.stopping;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
import type { Contributions } from "./contracts.ts";
|
||||||
|
|
||||||
|
/** Contributions belong to installed package sessions. This registry never loads code. */
|
||||||
|
export class ContributionRegistry {
|
||||||
|
private entries = new Map<keyof Contributions, { owner: string; value: Contributions[keyof Contributions] }>();
|
||||||
|
private listeners = new Set<(revision: number) => void>();
|
||||||
|
private revision = 0;
|
||||||
|
get<K extends keyof Contributions>(key: K): Contributions[K] | undefined {
|
||||||
|
return this.entries.get(key)?.value as Contributions[K] | undefined;
|
||||||
|
}
|
||||||
|
register<K extends keyof Contributions>(owner: string, key: K, value: Contributions[K]): () => void {
|
||||||
|
if (key !== "terminal" && key !== "tableFormulas") throw new Error("Unknown plugin contribution.");
|
||||||
|
if (this.entries.has(key)) throw new Error(`Contribution already registered: ${key}`);
|
||||||
|
const entry = { owner, value };
|
||||||
|
this.entries.set(key, entry); this.emit();
|
||||||
|
return () => {
|
||||||
|
if (this.entries.get(key) !== entry) return;
|
||||||
|
this.entries.delete(key); this.emit();
|
||||||
|
};
|
||||||
|
}
|
||||||
|
subscribe = (listener: (revision: number) => void) => {
|
||||||
|
this.listeners.add(listener); listener(this.revision);
|
||||||
|
return () => { this.listeners.delete(listener); };
|
||||||
|
};
|
||||||
|
private emit() { this.revision++; for (const listener of this.listeners) listener(this.revision); }
|
||||||
|
}
|
||||||
|
export const pluginHost = new ContributionRegistry();
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
import type { Contributions } from "./contracts.ts";
|
||||||
|
/** Package API v1. Compiled plugins export activate(api). */
|
||||||
|
export type Dispose = () => void | Promise<void>;
|
||||||
|
export interface PluginCommand { id: string; title: string; run: () => void | Promise<void> }
|
||||||
|
export interface PluginView { id: string; title: string; mount: (container: HTMLElement) => void | Dispose | Promise<void | Dispose> }
|
||||||
|
export interface PluginApi {
|
||||||
|
readonly id: string;
|
||||||
|
readonly signal: AbortSignal;
|
||||||
|
contribute<K extends keyof Contributions>(key: K, value: Contributions[K]): void;
|
||||||
|
registerCommand(command: PluginCommand): void;
|
||||||
|
registerView(view: PluginView): void;
|
||||||
|
openView(id: string): void;
|
||||||
|
onDispose(cleanup: Dispose): void;
|
||||||
|
workspace: {
|
||||||
|
list(path?: string): Promise<{ name: string; rel_path: string; kind: string }[]>;
|
||||||
|
read(path: string): Promise<string>;
|
||||||
|
write(path: string, contents: string, expected: string): Promise<void>;
|
||||||
|
};
|
||||||
|
settings: { read(): Promise<unknown>; write(value: unknown): Promise<void> };
|
||||||
|
assets: { read(path: string): Promise<Uint8Array> };
|
||||||
|
}
|
||||||
|
export interface PluginModule { activate(api: PluginApi): void | Dispose | Promise<void | Dispose> }
|
||||||
|
export interface ExternalManifest {
|
||||||
|
schemaVersion: 1; id: string; name: string; author: string; description: string;
|
||||||
|
version: string; apiVersion: 1; entry: string; access: "full-app";
|
||||||
|
}
|
||||||
|
export interface InstalledPlugin { manifest: ExternalManifest; hash: string; enabled: boolean; path: string; error: string | null; removal: boolean }
|
||||||
|
export interface PluginSnapshot { root: string; plugins: InstalledPlugin[] }
|
||||||
|
export interface Candidate { token: string; source: string; manifest: ExternalManifest | null; error: string | null }
|
||||||
|
export interface RemovalPlan { token: string; plugin: InstalledPlugin }
|
||||||
@@ -1,19 +0,0 @@
|
|||||||
<script lang="ts">
|
|
||||||
import { getCurrentWindow } from "@tauri-apps/api/window";
|
|
||||||
import TerminalDock from "$lib/layout/TerminalDock.svelte";
|
|
||||||
import { terminalShortcut } from "./model";
|
|
||||||
let { cwd }: { cwd: string } = $props();
|
|
||||||
let dock: TerminalDock;
|
|
||||||
let error = $state("");
|
|
||||||
function keydown(event: KeyboardEvent) {
|
|
||||||
if (event.target instanceof Element && event.target.closest("dialog, [role=menu]")) return;
|
|
||||||
const action = terminalShortcut(event);
|
|
||||||
if (action && action !== "toggle") { event.preventDefault(); void dock.command(action); }
|
|
||||||
}
|
|
||||||
</script>
|
|
||||||
<svelte:window onkeydown={keydown} />
|
|
||||||
<div class="window">
|
|
||||||
{#if error}<p role="alert">{error}</p>{/if}
|
|
||||||
<TerminalDock bind:this={dock} {cwd} visible standalone onClose={() => void getCurrentWindow().destroy().catch(reason => error = String(reason))} />
|
|
||||||
</div>
|
|
||||||
<style>.window { height: 100vh; display: flex; flex-direction: column; }</style>
|
|
||||||
@@ -4,7 +4,13 @@
|
|||||||
let { icon }: { icon: IconName } = $props();
|
let { icon }: { icon: IconName } = $props();
|
||||||
</script>
|
</script>
|
||||||
<svg viewBox="0 0 24 24" aria-hidden="true">
|
<svg viewBox="0 0 24 24" aria-hidden="true">
|
||||||
{#if icon === "up" || icon === "down"}
|
{#if icon === "settings"}
|
||||||
|
<path d="m9 3-1 3-3 1-2 3 2 2v3l3 2 1 4h5l1-3 3-1 3-4-2-2V8l-3-2-1-3Z" /><circle cx="12" cy="12" r="3" />
|
||||||
|
{:else if icon === "help"}
|
||||||
|
<circle cx="12" cy="12" r="9" /><path d="M9.5 9a2.5 2.5 0 1 1 4 2c-1 .6-1.5 1-1.5 3M12 17h.01" />
|
||||||
|
{:else if icon === "puzzle"}
|
||||||
|
<path d="M9 3H4v6a3 3 0 1 1 0 6v5h6a3 3 0 1 1 6 0h4v-6a3 3 0 1 0 0-6V3h-5a3 3 0 1 1-6 0Z" />
|
||||||
|
{:else if icon === "up" || icon === "down"}
|
||||||
{@html actionIcons[icon]}
|
{@html actionIcons[icon]}
|
||||||
{:else if icon === "more"}
|
{:else if icon === "more"}
|
||||||
<circle cx="5" cy="12" r="1" /><circle cx="12" cy="12" r="1" /><circle cx="19" cy="12" r="1" />
|
<circle cx="5" cy="12" r="1" /><circle cx="12" cy="12" r="1" /><circle cx="19" cy="12" r="1" />
|
||||||
@@ -25,6 +31,8 @@
|
|||||||
<path d="M12 4v16M6 8h3M6 12h3M15 8h3M15 12h3M15 16h3" />
|
<path d="M12 4v16M6 8h3M6 12h3M15 8h3M15 12h3M15 16h3" />
|
||||||
{:else if icon === "text"}
|
{:else if icon === "text"}
|
||||||
<path d="M4 6h16M4 10h16M4 14h10M4 18h13" />
|
<path d="M4 6h16M4 10h16M4 14h10M4 18h13" />
|
||||||
|
{:else if icon === "refresh"}
|
||||||
|
<path d="M20 7v5h-5M4 17v-5h5M6 7a7 7 0 0 1 12-1l2 3M4 15l2 3a7 7 0 0 0 12-1" />
|
||||||
{:else if icon === "folder-open"}
|
{:else if icon === "folder-open"}
|
||||||
<path d="M6 14l1.5-2.9A2 2 0 0 1 9.2 10H20a2 2 0 0 1 1.8 2.8l-1.5 3.2A2 2 0 0 1 18.5 17H4a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h3.7a2 2 0 0 1 1.4.6L10 6h8a2 2 0 0 1 2 2" />
|
<path d="M6 14l1.5-2.9A2 2 0 0 1 9.2 10H20a2 2 0 0 1 1.8 2.8l-1.5 3.2A2 2 0 0 1 18.5 17H4a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h3.7a2 2 0 0 1 1.4.6L10 6h8a2 2 0 0 1 2 2" />
|
||||||
{:else if icon === "file-plus"}
|
{:else if icon === "file-plus"}
|
||||||
|
|||||||
@@ -2,6 +2,9 @@
|
|||||||
import { onDestroy } from "svelte";
|
import { onDestroy } from "svelte";
|
||||||
import Icon from "./Icon.svelte";
|
import Icon from "./Icon.svelte";
|
||||||
export type IconName =
|
export type IconName =
|
||||||
|
| "settings"
|
||||||
|
| "help"
|
||||||
|
| "puzzle"
|
||||||
| "split"
|
| "split"
|
||||||
| "more"
|
| "more"
|
||||||
| "chevron-down"
|
| "chevron-down"
|
||||||
@@ -12,6 +15,7 @@
|
|||||||
| "window-maximize"
|
| "window-maximize"
|
||||||
| "window-restore"
|
| "window-restore"
|
||||||
| "restore"
|
| "restore"
|
||||||
|
| "refresh"
|
||||||
| "text"
|
| "text"
|
||||||
| "folder-open"
|
| "folder-open"
|
||||||
| "file-plus"
|
| "file-plus"
|
||||||
|
|||||||
@@ -95,30 +95,6 @@ export function workspaceSearch(query: string): Promise<SearchHit[]> {
|
|||||||
return invoke("workspace_search", { query });
|
return invoke("workspace_search", { query });
|
||||||
}
|
}
|
||||||
|
|
||||||
export function ptyOpen(id: string, cols: number, rows: number, cwd: string, profile?: string, directory?: string): Promise<void> {
|
|
||||||
return invoke("pty_open", { id, cols, rows, cwd, profile, directory });
|
|
||||||
}
|
|
||||||
|
|
||||||
export function ptyProfiles(): Promise<import("$lib/terminal/model").ShellProfile[]> {
|
|
||||||
return invoke("pty_profiles");
|
|
||||||
}
|
|
||||||
export function ptyNewWindow(): Promise<void> {
|
|
||||||
return invoke("pty_new_window", { id: crypto.randomUUID() });
|
|
||||||
}
|
|
||||||
export function ptyDictation(): Promise<void> { return invoke("pty_dictation"); }
|
|
||||||
|
|
||||||
export function ptyWrite(id: string, data: string): Promise<void> {
|
|
||||||
return invoke("pty_write", { id, data });
|
|
||||||
}
|
|
||||||
|
|
||||||
export function ptyResize(id: string, cols: number, rows: number): Promise<void> {
|
|
||||||
return invoke("pty_resize", { id, cols, rows });
|
|
||||||
}
|
|
||||||
|
|
||||||
export function ptyClose(id: string): Promise<void> {
|
|
||||||
return invoke("pty_close", { id });
|
|
||||||
}
|
|
||||||
|
|
||||||
export function onWorkspaceEvent(
|
export function onWorkspaceEvent(
|
||||||
handler: (event: WorkspaceEvent) => void,
|
handler: (event: WorkspaceEvent) => void,
|
||||||
): Promise<UnlistenFn> {
|
): Promise<UnlistenFn> {
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import MarkdownIt from "markdown-it";
|
import MarkdownIt from "markdown-it";
|
||||||
import type { Token } from "markdown-it";
|
import type { Token } from "markdown-it";
|
||||||
import { inlineMathEnd } from "./inlineMath.ts";
|
import { inlineMathEnd } from "./inlineMath.ts";
|
||||||
import { evaluateTableFormulas, formulaErrors, type FormulaResult } from "../editor/tableFormulas.ts";
|
import { pluginHost } from "../plugins/registry.ts";
|
||||||
|
|
||||||
const markdown = new MarkdownIt({ html: false, linkify: true, breaks: false });
|
const markdown = new MarkdownIt({ html: false, linkify: true, breaks: false });
|
||||||
export const escapeHtml = markdown.utils.escapeHtml;
|
export const escapeHtml = markdown.utils.escapeHtml;
|
||||||
@@ -156,31 +156,8 @@ markdown.renderer.rules.image = (tokens, index, _options, env, renderer) => {
|
|||||||
markdown.renderer.rules.table_open = () => '<div class="md-table-scroll"><table>\n';
|
markdown.renderer.rules.table_open = () => '<div class="md-table-scroll"><table>\n';
|
||||||
markdown.renderer.rules.table_close = () => '</table></div>\n';
|
markdown.renderer.rules.table_close = () => '</table></div>\n';
|
||||||
|
|
||||||
export function tableFormulaHtml(result: FormulaResult): string {
|
|
||||||
const label = `${result.formula} → ${result.error ? formulaErrors[result.error] : result.text}`;
|
|
||||||
return `<span class="md-table-formula${result.error ? " is-error" : ""}" title="${escapeHtml(label)}" aria-label="${escapeHtml(label)}">${escapeHtml(result.text)}</span>`;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Work from raw inline content, before Markdown formatting can interpret * or $.
|
|
||||||
// Each table gets its own reference scope, including in nested lists/callouts.
|
|
||||||
markdown.core.ruler.after("inline", "table_formulas", state => {
|
markdown.core.ruler.after("inline", "table_formulas", state => {
|
||||||
let rows: Token[][] | undefined;
|
pluginHost.get("tableFormulas")?.renderTableFormulas(state.tokens);
|
||||||
for (const token of state.tokens) {
|
|
||||||
if (token.type === "table_open") rows = [];
|
|
||||||
else if (rows && token.type === "tr_open") rows.push([]);
|
|
||||||
else if (rows && token.type === "inline") rows.at(-1)?.push(token);
|
|
||||||
else if (rows && token.type === "table_close") {
|
|
||||||
const results = evaluateTableFormulas(rows.map(row => row.map(cell => cell.content)));
|
|
||||||
rows.forEach((row, r) => row.forEach((cell, c) => {
|
|
||||||
const result = results[r][c];
|
|
||||||
if (!result) return;
|
|
||||||
const output = new MarkdownIt.Token("html_inline", "", 0);
|
|
||||||
output.content = tableFormulaHtml(result);
|
|
||||||
cell.children = [output];
|
|
||||||
}));
|
|
||||||
rows = undefined;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
});
|
||||||
|
|
||||||
function documentParts(contents: string) {
|
function documentParts(contents: string) {
|
||||||
|
|||||||
@@ -0,0 +1,35 @@
|
|||||||
|
export const SETTINGS_KEY = "runestone.settings";
|
||||||
|
export const MIN_AUTOSAVE_SECONDS = 1;
|
||||||
|
export const MAX_AUTOSAVE_SECONDS = 300;
|
||||||
|
|
||||||
|
export interface AppSettings {
|
||||||
|
autosaveEnabled: boolean;
|
||||||
|
autosaveSeconds: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const DEFAULT_SETTINGS: Readonly<AppSettings> = {
|
||||||
|
autosaveEnabled: true,
|
||||||
|
autosaveSeconds: 5,
|
||||||
|
};
|
||||||
|
|
||||||
|
export function validAutosaveSeconds(value: unknown): value is number {
|
||||||
|
return typeof value === "number" && Number.isInteger(value)
|
||||||
|
&& value >= MIN_AUTOSAVE_SECONDS && value <= MAX_AUTOSAVE_SECONDS;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function parseSettings(raw: string | null): AppSettings {
|
||||||
|
try {
|
||||||
|
const value = JSON.parse(raw ?? "null");
|
||||||
|
return {
|
||||||
|
autosaveEnabled: typeof value?.autosaveEnabled === "boolean" ? value.autosaveEnabled : DEFAULT_SETTINGS.autosaveEnabled,
|
||||||
|
autosaveSeconds: validAutosaveSeconds(value?.autosaveSeconds) ? value.autosaveSeconds : DEFAULT_SETTINGS.autosaveSeconds,
|
||||||
|
};
|
||||||
|
} catch { return { ...DEFAULT_SETTINGS }; }
|
||||||
|
}
|
||||||
|
|
||||||
|
export function saveSettings(storage: Pick<Storage, "setItem">, settings: AppSettings): void {
|
||||||
|
if (!validAutosaveSeconds(settings.autosaveSeconds) || typeof settings.autosaveEnabled !== "boolean") {
|
||||||
|
throw new Error("Choose a whole number from 1 to 300 seconds.");
|
||||||
|
}
|
||||||
|
storage.setItem(SETTINGS_KEY, JSON.stringify(settings));
|
||||||
|
}
|
||||||
+27
-3
@@ -1,7 +1,31 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
|
import { startExternalPlugins } from "$lib/plugins/external";
|
||||||
|
import { onMount } from "svelte";
|
||||||
|
import { getCurrentWindow } from "@tauri-apps/api/window";
|
||||||
import Workbench from "$lib/layout/Workbench.svelte";
|
import Workbench from "$lib/layout/Workbench.svelte";
|
||||||
import TerminalWindow from "$lib/terminal/TerminalWindow.svelte";
|
import TerminalSlot from "$lib/plugins/TerminalSlot.svelte";
|
||||||
|
import { pluginHost } from "$lib/plugins/registry";
|
||||||
const terminalRoot = new URLSearchParams(location.search).get("terminalWindow");
|
const terminalRoot = new URLSearchParams(location.search).get("terminalWindow");
|
||||||
|
let dock: TerminalSlot | undefined = $state();
|
||||||
|
let error = $state("");
|
||||||
|
const terminal = $derived.by(() => { void $pluginHost; return pluginHost.get("terminal"); });
|
||||||
|
onMount(startExternalPlugins);
|
||||||
|
function keydown(event: KeyboardEvent) {
|
||||||
|
if (!terminalRoot || event.target instanceof Element && event.target.closest("dialog, [role=menu]")) return;
|
||||||
|
const action = terminal?.shortcut(event);
|
||||||
|
if (action && action !== "toggle") { event.preventDefault(); void dock?.command(action).catch(reason => error = String(reason)); }
|
||||||
|
}
|
||||||
</script>
|
</script>
|
||||||
|
<svelte:window onkeydown={keydown} />
|
||||||
{#if terminalRoot}<TerminalWindow cwd={terminalRoot} />{:else}<Workbench />{/if}
|
{#if terminalRoot}
|
||||||
|
<div class="terminal-window">
|
||||||
|
{#if error}<p role="alert">{error}</p>{/if}
|
||||||
|
{#if terminal}
|
||||||
|
{#key terminal}
|
||||||
|
<TerminalSlot bind:this={dock} contribution={terminal} cwd={terminalRoot} visible standalone
|
||||||
|
onClose={() => void getCurrentWindow().destroy().catch(reason => error = String(reason))} />
|
||||||
|
{/key}
|
||||||
|
{:else}<p>Install and enable the Terminal plugin in Settings → Plug-ins in the main window.</p>{/if}
|
||||||
|
</div>
|
||||||
|
{:else}<Workbench />{/if}
|
||||||
|
<style>.terminal-window { height: 100vh; display: flex; flex-direction: column; }</style>
|
||||||
|
|||||||
@@ -0,0 +1,5 @@
|
|||||||
|
{
|
||||||
|
"extends": "./tsconfig.json",
|
||||||
|
"compilerOptions": { "types": ["svelte", "vite/client"] },
|
||||||
|
"include": ["src/**/*.d.ts", "plugins/**/*.ts", "plugins/**/*.svelte"]
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user