Release RuneStone 0.1.7 with plugin documents and shared menus
This commit is contained in:
@@ -8,6 +8,18 @@ product plans in `docs/`, with links from the README.
|
|||||||
Keep the roadmap visual and organized around goals, user outcomes, and milestones.
|
Keep the roadmap visual and organized around goals, user outcomes, and milestones.
|
||||||
Keep detailed capability lists and design constraints in the product scope reference.
|
Keep detailed capability lists and design constraints in the product scope reference.
|
||||||
|
|
||||||
|
## Plugin packages
|
||||||
|
|
||||||
|
Use `docs/plugins.md` as the package and release reference for all plugin work.
|
||||||
|
Distribute one standard `.zip` per plugin, with `plugin.json` at the archive root.
|
||||||
|
Use `pnpm package:plugin <compiled-folder> [output-folder]` to create release files.
|
||||||
|
Use Settings → Plug-ins for local ZIP and experimental Gitea-link installation.
|
||||||
|
Do not introduce custom extensions, loose JSON installation, or folder installation instructions.
|
||||||
|
Keep the manifest and entry module readable. Include the assets and dependencies needed to run the plugin.
|
||||||
|
Follow the Gitea release standard in `docs/plugins.md`: one plugin ZIP per published release, with an explicit tag for prerelease trials.
|
||||||
|
Keep the download source separate from package validation and installation.
|
||||||
|
GitHub and GitLab adapters remain future work. Do not add untested host support.
|
||||||
|
|
||||||
## UI work: prefer meaningful icons
|
## UI work: prefer meaningful icons
|
||||||
|
|
||||||
Apply these rules whenever designing, implementing, modifying, or reviewing RuneStone UI.
|
Apply these rules whenever designing, implementing, modifying, or reviewing RuneStone UI.
|
||||||
@@ -61,3 +73,33 @@ Apply them automatically without requiring the user to repeat them.
|
|||||||
- Keep the fill continuous within each selected region.
|
- Keep the fill continuous within each selected region.
|
||||||
Ordinary table grid lines can remain, but must not become highlighted selection borders inside the region.
|
Ordinary table grid lines can remain, but must not become highlighted selection borders inside the region.
|
||||||
- Check single items, contiguous ranges, separated selections, and nested rows.
|
- Check single items, contiguous ranges, separated selections, and nested rows.
|
||||||
|
|
||||||
|
## UI work: use one menu design
|
||||||
|
|
||||||
|
Apply these rules to context menus, action menus, and their submenus.
|
||||||
|
Apply them automatically when you add, change, or review a menu.
|
||||||
|
|
||||||
|
- Use `src/lib/ui/actionMenu.ts` for action menus.
|
||||||
|
Svelte callers can use `src/lib/layout/ContextMenu.svelte`.
|
||||||
|
Keep presentation in `src/lib/ui/menu.css` and theme values in `src/lib/theme/tokens.css`.
|
||||||
|
Do not create a separate menu renderer or local style overrides for individual features.
|
||||||
|
- Use the same font, row height, padding, icon size, label alignment, separators, and shadow throughout a menu family.
|
||||||
|
Use `--rs-menu-*` tokens and `--rs-control-radius`.
|
||||||
|
Keep a padding inset around every row so hover and focus backgrounds do not touch the panel border.
|
||||||
|
Menu width can change when content requires more space. Keep the other shared measurements.
|
||||||
|
- Use the same action icon for the same function across menus.
|
||||||
|
Give recognizable actions an icon and a concise label.
|
||||||
|
Reserve the icon column when an item has no suitable icon.
|
||||||
|
Keep submenu arrows and shortcut text in separate trailing columns.
|
||||||
|
- Give enabled rows the same hover and keyboard focus treatment.
|
||||||
|
Keep disabled rows readable, skip them during keyboard navigation, and prevent their activation.
|
||||||
|
Use the same inset separators between related groups.
|
||||||
|
- Support arrow keys, Home, End, Enter, Space, and Escape.
|
||||||
|
Open submenus with the Right arrow and return with the Left arrow.
|
||||||
|
Restore focus on keyboard dismissal. Keep menus within the viewport and scroll long menus.
|
||||||
|
- Check file, folder, pane, tab, editor, table, and submenu examples after changes to shared menu code.
|
||||||
|
Check both themes, disabled items, icon alignment, keyboard focus, and viewport edges.
|
||||||
|
Run `scripts/menuConsistency.smoke.mjs` against the development server to compare shared styles and behavior.
|
||||||
|
|
||||||
|
Rich pickers and dialogs can use their own layouts when they contain search fields, descriptions, or forms.
|
||||||
|
Plugin menus should use these rules where the host API permits shared components.
|
||||||
|
|||||||
@@ -33,8 +33,9 @@ The [user guide](docs/user-guide.md) covers current features and limitations.
|
|||||||
|
|
||||||
## Get started
|
## Get started
|
||||||
|
|
||||||
RuneStone runs on Windows 10 and 11 (64-bit). There is no public installer download yet.
|
RuneStone runs on Windows 10 and 11 (64-bit).
|
||||||
If you have a supplied installer:
|
Download the [0.1.7 installer](https://git.knottywyvern.com/kwyvern-gitea/RuneStone/releases/tag/v0.1.7) from Gitea.
|
||||||
|
Repository access is required. Then:
|
||||||
|
|
||||||
1. Open `RuneStone_<version>_x64-setup.exe`.
|
1. Open `RuneStone_<version>_x64-setup.exe`.
|
||||||
2. Follow the setup steps.
|
2. Follow the setup steps.
|
||||||
|
|||||||
+4
-1
@@ -45,6 +45,7 @@ The frontend uses port 1420, and Tauri loads `http://localhost:1420`.
|
|||||||
| --- | --- |
|
| --- | --- |
|
||||||
| Svelte, TypeScript, or CSS under `src/` | Save the source file. Vite updates the interface without a Rust rebuild. |
|
| Svelte, TypeScript, or CSS under `src/` | Save the source file. Vite updates the interface without a Rust rebuild. |
|
||||||
| Feature source under `plugins/` | Run `pnpm build:plugins`, then uninstall and install the changed package through Settings. |
|
| Feature source under `plugins/` | Run `pnpm build:plugins`, then uninstall and install the changed package through Settings. |
|
||||||
|
| Table formulas source in `../RuneStone_TableFormulas/` | Install that checkout's dependencies, then run `pnpm build:plugins` in RuneStone. Reinstall the changed ZIP through Settings. |
|
||||||
| Rust code under `src-tauri/src/` | Save the source file. Tauri rebuilds the changed Rust code and restarts the app. |
|
| Rust code under `src-tauri/src/` | Save the source file. Tauri rebuilds the changed Rust code and restarts the app. |
|
||||||
| Rust dependencies or build settings | Allow Cargo to compile the affected dependencies. These changes can take longer. |
|
| Rust dependencies or build settings | Allow Cargo to compile the affected dependencies. These changes can take longer. |
|
||||||
| JavaScript dependencies after a pull or branch change | Stop development, run `pnpm install --frozen-lockfile`, then start `pnpm tauri dev` again. |
|
| JavaScript dependencies after a pull or branch change | Stop development, run `pnpm install --frozen-lockfile`, then start `pnpm tauri dev` again. |
|
||||||
@@ -131,6 +132,8 @@ A browser can show the interface, but real folder access, file writes, and termi
|
|||||||
Use `pnpm tauri dev` for manual tests of those features.
|
Use `pnpm tauri dev` for manual tests of those features.
|
||||||
|
|
||||||
Run `pnpm build:plugins` before tests that use Terminal or Table formulas.
|
Run `pnpm build:plugins` before tests that use Terminal or Table formulas.
|
||||||
|
Clone [RuneStone_TableFormulas](https://git.knottywyvern.com/kwyvern-gitea/RuneStone_TableFormulas) beside RuneStone and install its dependencies first.
|
||||||
|
Set `RUNESTONE_TABLE_FORMULAS_ROOT` if that checkout is elsewhere.
|
||||||
These tests load the compiled packages through the production module loader.
|
These tests load the compiled packages through the production module loader.
|
||||||
The browser tests use the real interface with mocked desktop communication.
|
The browser tests use the real interface with mocked desktop communication.
|
||||||
They do not replace native desktop tests.
|
They do not replace native desktop tests.
|
||||||
@@ -156,7 +159,7 @@ node scripts/workbench.smoke.mjs
|
|||||||
| `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/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/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 |
|
| `../RuneStone_Terminal/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 |
|
||||||
|
|
||||||
|
|||||||
@@ -6,7 +6,8 @@
|
|||||||
|
|
||||||
RuneStone supports Windows 10 and 11 on 64-bit Intel and AMD computers.
|
RuneStone supports Windows 10 and 11 on 64-bit Intel and AMD computers.
|
||||||
The installer contains the app and its interface. You do not need developer tools or a terminal.
|
The installer contains the app and its interface. You do not need developer tools or a terminal.
|
||||||
There is no public download yet. Get the setup file from the maintainer who supplied your release.
|
Get the setup file from the [0.1.7 release](https://git.knottywyvern.com/kwyvern-gitea/RuneStone/releases/tag/v0.1.7).
|
||||||
|
Repository access is required.
|
||||||
|
|
||||||
1. Save `RuneStone_<version>_x64-setup.exe` to your Downloads folder.
|
1. Save `RuneStone_<version>_x64-setup.exe` to your Downloads folder.
|
||||||
2. Double-click the file.
|
2. Double-click the file.
|
||||||
|
|||||||
+193
-16
@@ -2,32 +2,52 @@
|
|||||||
|
|
||||||
[Back to development](development.md)
|
[Back to development](development.md)
|
||||||
|
|
||||||
RuneStone installs local JavaScript plugins from package files or folders.
|
RuneStone installs JavaScript plugins from local ZIP files and experimental Gitea release downloads.
|
||||||
Open Settings → Plug-ins to install, enable, disable, or uninstall them.
|
Open Settings → Plug-ins to install, enable, disable, or uninstall them.
|
||||||
Terminal and Table formulas use the same installed package system as all other plugins.
|
Terminal and Table formulas use the same installed package system as all other plugins.
|
||||||
|
|
||||||
## Build and install the feature packages
|
## Build and install the feature packages
|
||||||
|
|
||||||
1. Run `pnpm build:plugins` from the repository root.
|
1. Clone `RuneStone_TableFormulas` beside RuneStone and run `pnpm install --frozen-lockfile` in that checkout.
|
||||||
2. In Settings → Plug-ins, choose Install from folder and select `plugin-packages/`.
|
2. Run `pnpm build:plugins` from the RuneStone repository root for Table formulas.
|
||||||
3. Review both packages, then choose Install and enable.
|
3. In Settings → Plug-ins, choose Install plugin ZIP.
|
||||||
|
4. Select the ZIP files in `plugin-packages/`, then choose Install and enable.
|
||||||
|
|
||||||
|
The build creates `runestone.table-formulas-0.1.0.zip`.
|
||||||
|
Table formulas is a development package in its [own repository](https://git.knottywyvern.com/kwyvern-gitea/RuneStone_TableFormulas).
|
||||||
|
Set `RUNESTONE_TABLE_FORMULAS_ROOT` to use a different checkout location.
|
||||||
|
That repository also supports `pnpm package:plugin`, with `RUNESTONE_ROOT` selecting the host packager.
|
||||||
|
The folders beside them contain build output for inspection and tests.
|
||||||
|
Use the ZIP files for installation and releases.
|
||||||
|
|
||||||
|
Terminal development lives in the separate [RuneStone_Terminal repository](https://git.knottywyvern.com/kwyvern-gitea/RuneStone_Terminal).
|
||||||
|
In that repository, run `pnpm install --frozen-lockfile`, then `pnpm build`.
|
||||||
|
Install `releases/runestone.terminal-0.1.0.zip` through the same plugin ZIP installer.
|
||||||
|
Version 0.1.0 marks Terminal as a development package.
|
||||||
|
The local source folder is `../RuneStone_Terminal/` when both repositories share a parent directory.
|
||||||
|
|
||||||
No plugin starts automatically in a fresh installation.
|
No plugin starts automatically in a fresh installation.
|
||||||
The application build does not include these packages. Package builds include their JavaScript dependencies and terminal styles.
|
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.
|
Build them again after source changes, then uninstall the old version and install the new ZIP.
|
||||||
The old bundled switches no longer apply. Existing terminal appearance settings remain available after installation.
|
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.
|
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.
|
Native pseudo-terminal services remain in the desktop host. The Terminal package supplies the interface, shortcuts, and session controls.
|
||||||
|
|
||||||
## Install a plugin
|
## Install a plugin
|
||||||
|
|
||||||
1. Choose Install from file or Install from folder.
|
1. In Settings → Plug-ins, choose Install plugin ZIP.
|
||||||
2. Select the packages to install in the review dialog.
|
2. Select one or more `.zip` files, then review the packages.
|
||||||
3. Choose Install to keep them disabled, or Install and enable to run them.
|
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.
|
Each ZIP contains one plugin, with `plugin.json` at its root.
|
||||||
You can also select `plugin.json`, its containing folder, or a collection folder containing plugin folders and package files.
|
You can open the ZIP with an archive tool to read its manifest, JavaScript, and other files.
|
||||||
Collection discovery checks one level and accepts at most 100 entries.
|
You do not need to extract it before installation.
|
||||||
|
The picker accepts at most 100 ZIP files at once.
|
||||||
|
Folders and loose `plugin.json` files are not installation inputs.
|
||||||
|
|
||||||
|
Earlier `.runestone-plugin` files already used ZIP format. Rename those files to `.zip` before installation.
|
||||||
|
Installed plugins keep working. This change does not alter their files or saved settings.
|
||||||
|
|
||||||
RuneStone copies packages into its per-user application data directory. It never modifies the selected source.
|
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.
|
The review shows the author, version, source, destination, and access level.
|
||||||
|
|
||||||
@@ -39,8 +59,8 @@ Plugins cannot overwrite an existing ID. Uninstall the previous package before i
|
|||||||
Each package succeeds or fails independently. The result identifies any failures.
|
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.
|
A changed source requires a new review. Cancelling the review removes its temporary copies.
|
||||||
|
|
||||||
Try the example in `fixtures/plugins/workspace-overview/`.
|
Try the example with `pnpm package:plugin fixtures/plugins/workspace-overview`.
|
||||||
Install that folder, then choose Install and enable.
|
Install the resulting ZIP from `plugin-packages/`, then choose Install and enable.
|
||||||
Use the puzzle button in the main toolbar to run Show workspace overview or open the Workspace overview view.
|
Use the puzzle button in the main toolbar to run Show workspace overview or open the Workspace overview view.
|
||||||
|
|
||||||
## Uninstall with one confirmation
|
## Uninstall with one confirmation
|
||||||
@@ -107,7 +127,7 @@ Install and removal operations share one native service and serialize their stat
|
|||||||
|
|
||||||
## Package contract
|
## Package contract
|
||||||
|
|
||||||
Place `plugin.json` at the root of the folder or archive:
|
Place `plugin.json` at the root of the ZIP archive:
|
||||||
|
|
||||||
```json
|
```json
|
||||||
{
|
{
|
||||||
@@ -124,6 +144,11 @@ Place `plugin.json` at the root of the folder or archive:
|
|||||||
```
|
```
|
||||||
|
|
||||||
The package API is version 1. Its interface lives in `src/lib/plugins/sdk.ts`.
|
The package API is version 1. Its interface lives in `src/lib/plugins/sdk.ts`.
|
||||||
|
RuneStone 0.1.5 adds optional `placement: "editor"` for views that belong beside documents.
|
||||||
|
These views open in the editor area with a tab. Document tabs retain their buffers when users switch views.
|
||||||
|
Closing the plugin tab or disabling the package disposes the view.
|
||||||
|
The default placement is `"dialog"`, so existing packages keep their current behavior.
|
||||||
|
Older hosts ignore the placement field. Plugins that require editor placement need RuneStone 0.1.5 or later.
|
||||||
All packages use one API and the same installation, enable, disable, and removal lifecycle.
|
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.
|
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.
|
The `runestone.*` prefix follows the same rules as other package IDs. It does not prove the publisher's identity.
|
||||||
@@ -138,6 +163,120 @@ 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.
|
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.
|
Raw TypeScript, Svelte source, native libraries, plugin dependencies, and automatic updates are unsupported.
|
||||||
|
|
||||||
|
## Build and release a plugin
|
||||||
|
|
||||||
|
Use the same package contract for in-house and community plugins.
|
||||||
|
The ZIP is the release file. Its `plugin.json` describes the contents and is not a separate installer.
|
||||||
|
|
||||||
|
```text
|
||||||
|
org.example.hello-1.0.0.zip
|
||||||
|
plugin.json
|
||||||
|
main.js
|
||||||
|
assets/
|
||||||
|
README.md
|
||||||
|
LICENSE
|
||||||
|
```
|
||||||
|
|
||||||
|
The manifest and entry module are required. Assets, a README, and a license are optional package files.
|
||||||
|
Include a README with the host requirement, purpose, install steps, and help contact.
|
||||||
|
Keep JavaScript readable where practical. Avoid minification and obfuscation that make inspection harder.
|
||||||
|
|
||||||
|
1. Compile the plugin into a clean folder with `plugin.json`, its entry module, and the required assets.
|
||||||
|
2. Run `pnpm package:plugin <compiled-folder> [output-folder]` from the RuneStone repository.
|
||||||
|
3. Install the resulting ZIP in RuneStone and test its features, disable action, and uninstall action.
|
||||||
|
4. Share that same ZIP as the release file.
|
||||||
|
|
||||||
|
Use Node.js 24 or later for the packaging command. The default output folder is `plugin-packages/`.
|
||||||
|
It checks the manifest, paths, entry module, and size limits before it writes `<id>-<version>.zip`.
|
||||||
|
It includes every file in the input folder. Keep dependencies, credentials, and unrelated build files outside that folder.
|
||||||
|
The output folder must be outside the input folder.
|
||||||
|
The command replaces an existing ZIP with the same ID and version. Increase the version for each published release.
|
||||||
|
Repeated runs with unchanged input produce the same archive bytes.
|
||||||
|
The native installer checks the package again before installation.
|
||||||
|
|
||||||
|
Other build tools can create the same ZIP layout. Do not add a parent folder above `plugin.json`.
|
||||||
|
Do not tell users to load JSON, select a build folder, rename a new release, or install dependencies.
|
||||||
|
Authors in other repositories can run `node <RuneStone-path>/scripts/packagePlugin.mjs <compiled-folder> <output-folder>`.
|
||||||
|
|
||||||
|
## Experimental installation from a Gitea link
|
||||||
|
|
||||||
|
Gitea repository links now supply ZIP packages to the existing review and installation flow.
|
||||||
|
This trial supports Gitea at the host root, including the personal Gitea server.
|
||||||
|
GitHub and GitLab support remain future work. Their release APIs need separate tests.
|
||||||
|
|
||||||
|
1. In Settings → Plug-ins, choose Install from Git link.
|
||||||
|
2. Enter the repository root link, such as `https://git.knottywyvern.com/kwyvern-gitea/RuneStone_Terminal`.
|
||||||
|
3. Enter a release tag for a specific version, or leave it empty for the latest release.
|
||||||
|
4. For a private repository, enter a Gitea access token with repository read access.
|
||||||
|
5. Choose Review release, then choose Install or Install and enable after you review the package.
|
||||||
|
|
||||||
|
The link can end in `.git`. SSH links, branch links, source archives, and links with credentials are not installation inputs.
|
||||||
|
Use an explicit tag for a prerelease trial. The [Gitea latest-release endpoint](https://docs.gitea.com/api/operations/repo-get-latest-release/) excludes drafts and prereleases.
|
||||||
|
RuneStone clears the token after each request and when the form closes. It does not save the token.
|
||||||
|
Use HTTPS. HTTP is available for trusted local servers, but it sends the token and package without encryption.
|
||||||
|
Credentials go only to the original API origin. Redirects to another origin do not receive the token.
|
||||||
|
A release attachment on another private host needs its own access method and is outside this trial.
|
||||||
|
|
||||||
|
The downloader reads release metadata, then downloads one attached ZIP.
|
||||||
|
It does not clone the repository, compile code, install dependencies, or run scripts.
|
||||||
|
Downloads have size limits, time limits, and a redirect limit.
|
||||||
|
The metadata limit is 2 MiB. The compressed ZIP limit is 100 MiB.
|
||||||
|
The existing package limits still apply to the extracted files.
|
||||||
|
HTTPS links cannot redirect or select an attachment over HTTP.
|
||||||
|
|
||||||
|
The review shows the repository, release tag, attachment link, manifest, and destination.
|
||||||
|
It pins the downloaded content. Installation checks that the staged files still match the reviewed hash.
|
||||||
|
Changing a remote release after review does not change the pending installation.
|
||||||
|
The same duplicate-ID, enable, removal, and cleanup rules apply to local and remote packages.
|
||||||
|
|
||||||
|
### Release standard for plugin writers and agents
|
||||||
|
|
||||||
|
Use one plugin repository and one standard plugin ZIP per release for this trial.
|
||||||
|
Keep the package contract above. No repository manifest or special branch layout is required.
|
||||||
|
|
||||||
|
1. Build the plugin from the source commit that you intend to tag.
|
||||||
|
2. Run `pnpm package:plugin <compiled-folder> [output-folder]` from RuneStone.
|
||||||
|
3. Attach the resulting `<id>-<version>.zip` to a Gitea release.
|
||||||
|
4. Publish the release with a tag that identifies its source commit.
|
||||||
|
5. Test its repository link and explicit tag in RuneStone.
|
||||||
|
|
||||||
|
Use `v<version>` for ordinary release tags. Use a clearly named trial tag for temporary prereleases.
|
||||||
|
Keep the manifest version and package version equal. Keep published release files unchanged.
|
||||||
|
Increase the version before publishing different package contents as an ordinary release.
|
||||||
|
A prerelease can use the same numeric manifest version while the installer uses its explicit trial tag.
|
||||||
|
|
||||||
|
The ZIP must contain `plugin.json` at its root, the compiled entry module, and all required assets and dependencies.
|
||||||
|
Do not attach a source ZIP as the plugin package. Gitea's automatic source archives do not count as release attachments.
|
||||||
|
The installer rejects releases with no attached ZIP or more than one attached ZIP.
|
||||||
|
Other attachments, such as checksums and release notes, can accompany the single ZIP.
|
||||||
|
The installer rejects drafts. Private repositories require read access to the metadata and attachment.
|
||||||
|
|
||||||
|
Test local ZIP installation before publication. After publication, test download, review, disabled installation, enable, disable, and removal.
|
||||||
|
Check that cancellation leaves no installed package. Check that an existing plugin ID blocks another installation.
|
||||||
|
Keep release notes short. State the host requirement, plugin version, changes, and known limits.
|
||||||
|
|
||||||
|
### Trial checks
|
||||||
|
|
||||||
|
The four local packages passed a simulated Gitea release download and isolated native installation on October 5, 2026.
|
||||||
|
The test checked the installed hashes and kept all four plugins disabled.
|
||||||
|
|
||||||
|
| Plugin | Package version |
|
||||||
|
| --- | --- |
|
||||||
|
| Terminal | 0.1.0 |
|
||||||
|
| Table formulas | 0.1.0 |
|
||||||
|
| PDF viewer | 0.0.1 |
|
||||||
|
| Project management | 0.2.3 |
|
||||||
|
|
||||||
|
The authenticated check of the personal Gitea server found no releases in these four repositories.
|
||||||
|
Live Gitea installation still needs published release attachments. No releases or tags were created during this check.
|
||||||
|
The browser smoke test covers the link form, download errors, token clearing, cancellation, focus, and disabled installation.
|
||||||
|
Native tests cover URL parsing, release selection, redirects, credential boundaries, size limits, changed staging files, and invalid ZIPs.
|
||||||
|
|
||||||
|
Run the focused native checks with `cargo test --manifest-path src-tauri/Cargo.toml --lib plugin`.
|
||||||
|
To repeat the four-package trial, place exactly these four ZIPs in a folder and set `RUNESTONE_GIT_TRIAL_PACKAGES` to its absolute path.
|
||||||
|
Then run `cargo test --manifest-path src-tauri/Cargo.toml --lib four_plugin_release_trial -- --ignored --nocapture`.
|
||||||
|
Run `node scripts/pluginInstall.smoke.mjs` against the development server for the browser checks.
|
||||||
|
|
||||||
## Plugin API
|
## Plugin API
|
||||||
|
|
||||||
The entry exports `activate(api)`. Activation can return a cleanup function or a promise for that function.
|
The entry exports `activate(api)`. Activation can return a cleanup function or a promise for that function.
|
||||||
@@ -170,16 +309,49 @@ export function activate(api) {
|
|||||||
| `api.signal` | An abort signal triggered before shutdown |
|
| `api.signal` | An abort signal triggered before shutdown |
|
||||||
| `contribute(key, value)` | Register a typed terminal or table formula contribution |
|
| `contribute(key, value)` | Register a typed terminal or table formula contribution |
|
||||||
| `registerCommand({ id, title, run })` | Add a command to the toolbar's plugin menu |
|
| `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 |
|
| `registerView({ id, title, placement?, mount })` | Add a view in a dialog or the editor area |
|
||||||
|
| `registerView({ navigation: true, icon?, ... })` | Add an icon button to the ribbon left of the navigation pane |
|
||||||
|
| `registerDocumentType(type)` | Recognize document content, supply a navigation icon, and mount a document editor |
|
||||||
|
| `openDocument(path)` | Open a recognized document in its own tab |
|
||||||
|
| `renameDocument({ id, path }, name)` | Rename a recognized document and return its new workspace path. Optional API |
|
||||||
| `openView(id)` | Open one of the plugin's registered views |
|
| `openView(id)` | Open one of the plugin's registered views |
|
||||||
| `onDispose(callback)` | Register synchronous or asynchronous cleanup |
|
| `onDispose(callback)` | Register synchronous or asynchronous cleanup |
|
||||||
| `workspace.list(path?)` | List a directory in this window's active workspace |
|
| `workspace.list(path?)` | List a directory in this window's active workspace |
|
||||||
| `workspace.read(path)` | Read a workspace text file |
|
| `workspace.read(path)` | Read a workspace text file |
|
||||||
|
| `workspace.readBytes(path)` | Read workspace bytes as a Uint8Array, with a 64 MiB limit. Requires the binary document host update |
|
||||||
|
| `workspace.readOptional(path)` | Read text, or return null when the file is absent. Added in 0.1.6 |
|
||||||
|
| `workspace.create(path, contents)` | Create complete text without replacing an existing file. Added in 0.1.6 |
|
||||||
| `workspace.write(path, contents, expected)` | Save only if the file still matches the original text |
|
| `workspace.write(path, contents, expected)` | Save only if the file still matches the original text |
|
||||||
|
| `workspace.subscribe(listener)` | Receive workspace change notifications. Returns a cleanup function |
|
||||||
| `settings.read()` / `settings.write(value)` | Read or write retained JSON settings, with a 1 MiB limit |
|
| `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` |
|
| `assets.read(path)` | Read package bytes as a `Uint8Array` |
|
||||||
|
|
||||||
Command and view IDs must be unique within their respective plugin collections.
|
Command and view IDs must be unique within their respective plugin collections.
|
||||||
|
Document type IDs must also be unique within their collection.
|
||||||
|
Document types declare file extensions, an `identify` function, and a `mount` function.
|
||||||
|
The identify function returns a stable document ID or null. Invalid documents remain available through the text editor.
|
||||||
|
An optional creation action supplies complete file text. Creation never replaces an existing file.
|
||||||
|
Each document opens in its own editor tab. Opening the same document focuses its existing tab.
|
||||||
|
Closing one tab disposes only that mount. Disabling the plugin disposes all its mounts and removes its navigation entries.
|
||||||
|
The host rejects plugin writes when a note has unsaved editor changes.
|
||||||
|
These document APIs require the current host source. The earlier 0.1.6 installer does not include them.
|
||||||
|
The optional API method `renameDocument({ id, path }, name)` renames a recognized document and returns its new workspace path.
|
||||||
|
The host checks the document ID and plugin owner. It keeps the folder and extension, rejects name collisions, and updates open tabs.
|
||||||
|
Names can contain dots. Hidden names and reserved filename characters are invalid.
|
||||||
|
Unsaved text edits block plugin renames. This method requires the updated host source.
|
||||||
|
Binary document types set `content: "binary"`. Text remains the default.
|
||||||
|
For binary types, `identify(path, source)` receives an empty source string and recognizes the path without reading its contents.
|
||||||
|
The mount reads bytes with `workspace.readBytes(path)` and reports invalid document data in its own view.
|
||||||
|
This avoids UTF-8 conversion and full file reads while the file tree identifies binary documents.
|
||||||
|
The native read command checks the active window's workspace boundary and rejects directories and files larger than 64 MiB.
|
||||||
|
Binary document support requires the updated host source. The earlier 0.1.6 installer does not include it.
|
||||||
|
Check for `api.workspace.readBytes` during activation and report a clear host update error when it is absent.
|
||||||
|
|
||||||
|
Navigation views appear as icon buttons in the ribbon left of the navigation pane.
|
||||||
|
The optional view `icon` accepts `list`, `kanban`, or `puzzle`. The default is `puzzle`.
|
||||||
|
Buttons show the view title in a tooltip on hover and keyboard focus.
|
||||||
|
The ribbon remains available when the navigation pane is closed.
|
||||||
|
|
||||||
Views can return asynchronous cleanup. Closing a view and disabling its plugin share the same cleanup promise.
|
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.
|
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.
|
The SDK rejects calls after shutdown starts, but it does not isolate JavaScript with full application access.
|
||||||
@@ -202,10 +374,15 @@ The plugin must stop its mounted controls and native sessions in `onDispose` bef
|
|||||||
| `src/lib/plugins/PluginTools.svelte` | External commands and views |
|
| `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/registry.ts` / `contracts.ts` | Shared feature contributions and their types |
|
||||||
| `src/lib/plugins/TerminalSlot.svelte` | The host element for terminal controls |
|
| `src/lib/plugins/TerminalSlot.svelte` | The host element for terminal controls |
|
||||||
| `plugins/terminal/` / `plugins/table-formulas/` | Separate feature packages |
|
| `../RuneStone_Terminal/src/` | Terminal plugin source in its own repository |
|
||||||
| `scripts/buildPlugins.mjs` | Package compilation into `plugin-packages/` |
|
| `../RuneStone_TableFormulas/` | Table formulas source, unit tests, and package build |
|
||||||
|
| `scripts/buildPlugins.mjs` | Table formulas compilation and ZIP release in `plugin-packages/` |
|
||||||
|
| `scripts/packagePlugin.mjs` | Shared checks and ZIP creation for plugin authors |
|
||||||
|
|
||||||
Run `pnpm build:plugins`, `pnpm check`, `pnpm test`, `pnpm build`, and `cargo test --manifest-path src-tauri/Cargo.toml --lib --offline`.
|
Run `pnpm build:plugins`, `pnpm check`, `pnpm test`, `pnpm build`, and `cargo test --manifest-path src-tauri/Cargo.toml --lib --offline`.
|
||||||
|
Run `pnpm check`, `pnpm test`, and `pnpm build` in `RuneStone_Terminal` for terminal checks.
|
||||||
|
Build Terminal before host browser tests. They read `../RuneStone_Terminal/dist/` by default.
|
||||||
|
Set `RUNESTONE_TERMINAL_DIST` to use another compiled terminal folder.
|
||||||
The Rust tests use real temporary files and archives. Browser tests mock desktop calls and exercise the real UI and module loader.
|
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.
|
Run `scripts/pluginInstall.smoke.mjs`, `scripts/plugins.smoke.mjs`, and `scripts/settings.smoke.mjs` against the development server.
|
||||||
|
|
||||||
|
|||||||
+11
-7
@@ -51,13 +51,19 @@ External JavaScript packages can add commands and views. See the [plugin guide](
|
|||||||
Terminal and Table formulas use the same installed package system as all other plugins.
|
Terminal and Table formulas use the same installed package system as all other plugins.
|
||||||
External JavaScript packages now support local installation, commands, views, retained settings, and removal with one confirmation.
|
External JavaScript packages now support local installation, commands, views, retained settings, and removal with one confirmation.
|
||||||
Users can enable or disable each plugin. A marketplace is outside the planned scope.
|
Users can enable or disable each plugin. A marketplace is outside the planned scope.
|
||||||
Installation accepts plugin packages or folders and stores copies in the application data directory.
|
Installation accepts standard ZIP packages and stores copies in the application data directory.
|
||||||
|
Experimental Gitea repository links download one release ZIP into the same review flow.
|
||||||
|
Local trials passed with four plugin packages. Live Gitea testing still needs published releases.
|
||||||
|
GitHub and GitLab support remain future work.
|
||||||
Uninstall requires one confirmation before RuneStone removes the installed plugin files.
|
Uninstall requires one confirmation before RuneStone removes the installed plugin files.
|
||||||
Cancel preserves the plugin. Removal keeps settings, source packages, and workspace documents.
|
Cancel preserves the plugin. Removal keeps settings, source packages, and workspace documents.
|
||||||
See the [installation and removal guide](plugins.md#uninstall-with-one-confirmation).
|
See the [installation and removal guide](plugins.md#uninstall-with-one-confirmation).
|
||||||
|
|
||||||
### Plugin to-do list
|
### Plugin to-do list
|
||||||
|
|
||||||
|
- [x] Standardize plugin releases and installation on readable ZIP packages.
|
||||||
|
- [x] Add experimental Gitea release downloads and test the four plugin packages locally.
|
||||||
|
- [ ] Complete the live Gitea release trial.
|
||||||
- [x] Use one package system with API version checks, cleanup, saved preferences, and enable controls.
|
- [x] Use one package system with API version checks, cleanup, saved preferences, and enable controls.
|
||||||
- [x] Add external package loading, exact API compatibility checks, and retained plugin settings.
|
- [x] Add external package loading, exact API compatibility checks, and retained plugin settings.
|
||||||
- [x] Define an external API for commands, views, and workspace files.
|
- [x] Define an external API for commands, views, and workspace files.
|
||||||
@@ -67,14 +73,12 @@ See the [installation and removal guide](plugins.md#uninstall-with-one-confirmat
|
|||||||
- [ ] Move native terminal services into a separate in-house package.
|
- [ ] Move native terminal services into a separate in-house package.
|
||||||
- [x] Move formula evaluation, rendered results, and help controls into an external Table formulas package.
|
- [x] Move formula evaluation, rendered results, and help controls into an external Table formulas package.
|
||||||
- [ ] Move the remaining spreadsheet operations into a separate in-house package.
|
- [ ] Move the remaining spreadsheet operations into a separate in-house package.
|
||||||
- [ ] Add a Kanban plugin for boards, columns, and task cards.
|
- [ ] Add one Project management plugin with connected Kanban, Gantt, and Calendar views.
|
||||||
- [ ] Add a Gantt plugin for task timelines and dependencies.
|
|
||||||
- [ ] Add a Calendar plugin for dated tasks and events.
|
|
||||||
- [ ] Add a virtual tabletop system plugin.
|
- [ ] Add a virtual tabletop system plugin.
|
||||||
|
|
||||||
Keep basic Markdown table editing and rendering in the core. Users must retain access to workspace files when plugins are disabled.
|
Keep basic Markdown table editing and rendering in the core. Users must retain access to workspace files when plugins are disabled.
|
||||||
Kanban, Gantt, and Calendar are separate plugins that share a task index.
|
Kanban, Gantt, and Calendar belong to one optional Project management package with shared items.
|
||||||
Kanban boards are Markdown files. Headings are columns. Task list items are cards.
|
The PM plugin has a separate development project. See its [design and scope](../../RuneStone_PM/project-management.md).
|
||||||
|
|
||||||
### Planned plugin lineup
|
### Planned plugin lineup
|
||||||
|
|
||||||
@@ -87,7 +91,7 @@ No plugin starts automatically in a fresh installation. The planned lineup inclu
|
|||||||
|
|
||||||
Planned plugins disabled by default:
|
Planned plugins disabled by default:
|
||||||
|
|
||||||
- Kanban, Gantt, and Calendar. Separate views for task organization and schedules.
|
- Project management. Connected Kanban, Gantt, and Calendar views within one package.
|
||||||
- Virtual tabletop. Tools for tabletop play within the workspace.
|
- Virtual tabletop. Tools for tabletop play within the workspace.
|
||||||
- Graph. Draw wiki-link edges from the file index.
|
- Graph. Draw wiki-link edges from the file index.
|
||||||
- Canvas. Store `.canvas` files in JSON Canvas 1.0.
|
- Canvas. Store `.canvas` files in JSON Canvas 1.0.
|
||||||
|
|||||||
@@ -0,0 +1,9 @@
|
|||||||
|
# RuneStone 0.1.7
|
||||||
|
|
||||||
|
- Install plugins from standard ZIP files or experimental Gitea release links.
|
||||||
|
- Open plugin documents in editor tabs, with navigation icons and rename support.
|
||||||
|
- Read binary workspace files through the plugin API, with a 64 MiB limit.
|
||||||
|
- Use consistent menus with icons, keyboard controls, rounded rows, and shared theme styles.
|
||||||
|
- Install Terminal and Table formulas from their separate plugin packages.
|
||||||
|
|
||||||
|
The Windows installer is unsigned. Clean-account installation and upgrade checks remain untested.
|
||||||
+2
-1
@@ -48,7 +48,8 @@ See [Tauri's Windows installer documentation](https://v2.tauri.app/distribute/wi
|
|||||||
5. Attach the setup file and release notes to the repository release or your chosen download page.
|
5. Attach the setup file and release notes to the repository release or your chosen download page.
|
||||||
|
|
||||||
Keep `com.runestone.app` as the app identifier so upgrades retain the same app identity.
|
Keep `com.runestone.app` as the app identifier so upgrades retain the same app identity.
|
||||||
No public download location or automatic release upload is configured yet.
|
The [Gitea releases](https://git.knottywyvern.com/kwyvern-gitea/RuneStone/releases) contain installers and release notes.
|
||||||
|
Repository access is required. Release uploads are manual.
|
||||||
After you publish an installer, add its download link to the README.
|
After you publish an installer, add its download link to the README.
|
||||||
|
|
||||||
Local installers are unsigned until the maintainer configures Windows code signing.
|
Local installers are unsigned until the maintainer configures Windows code signing.
|
||||||
|
|||||||
@@ -52,6 +52,8 @@ Restricted permissions and the remaining spreadsheet modules are still planned.
|
|||||||
**Milestone:** A user can enable a packaged plugin, use it with workspace files,
|
**Milestone:** A user can enable a packaged plugin, use it with workspace files,
|
||||||
and disable it while retaining access to those files in the core editor.
|
and disable it while retaining access to those files in the core editor.
|
||||||
|
|
||||||
|
Project management plugin planning lives in the separate [RuneStone_PM roadmap](../../RuneStone_PM/roadmap.md).
|
||||||
|
|
||||||
## Why this order?
|
## Why this order?
|
||||||
|
|
||||||
Reliable daily work establishes trust. Better navigation then helps users understand larger projects.
|
Reliable daily work establishes trust. Better navigation then helps users understand larger projects.
|
||||||
|
|||||||
+2
-1
@@ -19,7 +19,8 @@ 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.
|
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.
|
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.
|
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.
|
Use Install plugin ZIP for local packages, or Install from Git link for an experimental Gitea release download.
|
||||||
|
The puzzle button opens installed plugin commands and views. See the [plugin guide](plugins.md#experimental-installation-from-a-gitea-link) for release and private-access requirements.
|
||||||
Uninstall requires one confirmation and preserves settings, source packages, and workspace documents.
|
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.
|
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.
|
Help and about includes the app version, basic instructions, and keyboard shortcuts.
|
||||||
|
|||||||
+3
-4
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "runestone",
|
"name": "runestone",
|
||||||
"version": "0.1.4",
|
"version": "0.1.7",
|
||||||
"description": "Desktop editor for a local workspace",
|
"description": "Desktop editor for a local workspace",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
@@ -13,7 +13,8 @@
|
|||||||
"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"
|
"build:plugins": "node scripts/buildPlugins.mjs",
|
||||||
|
"package:plugin": "node scripts/packagePlugin.mjs"
|
||||||
},
|
},
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
@@ -40,8 +41,6 @@
|
|||||||
"@tiptap/extension-task-list": "^3.31.3",
|
"@tiptap/extension-task-list": "^3.31.3",
|
||||||
"@tiptap/pm": "^3.31.3",
|
"@tiptap/pm": "^3.31.3",
|
||||||
"@tiptap/starter-kit": "^3.31.3",
|
"@tiptap/starter-kit": "^3.31.3",
|
||||||
"@xterm/addon-fit": "^0.11.0",
|
|
||||||
"@xterm/xterm": "^6.0.0",
|
|
||||||
"markdown-it": "^15.0.2",
|
"markdown-it": "^15.0.2",
|
||||||
"mermaid": "^12.0.0",
|
"mermaid": "^12.0.0",
|
||||||
"monaco-editor": "^0.56.0"
|
"monaco-editor": "^0.56.0"
|
||||||
|
|||||||
@@ -1,46 +0,0 @@
|
|||||||
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 };
|
|
||||||
}
|
|
||||||
@@ -1,151 +0,0 @@
|
|||||||
// Formulas are plain Markdown cell text. No JavaScript evaluation or external data.
|
|
||||||
export const formulaErrors = {
|
|
||||||
"#ERROR!": "Invalid formula syntax or function arguments",
|
|
||||||
"#REF!": "Cell reference is outside this table",
|
|
||||||
"#VALUE!": "Expected a number",
|
|
||||||
"#NAME?": "Unknown function or cell name",
|
|
||||||
"#DIV/0!": "Cannot divide by zero or average an empty range",
|
|
||||||
"#CYCLE!": "Circular cell reference",
|
|
||||||
"#NUM!": "Result is not a finite number",
|
|
||||||
"#LIMIT!": "Formula is too complex",
|
|
||||||
} as const;
|
|
||||||
type ErrorCode = keyof typeof formulaErrors;
|
|
||||||
export type FormulaResult = { formula: string; text: string; value?: number; error?: ErrorCode };
|
|
||||||
class FormulaError extends Error {
|
|
||||||
code: ErrorCode;
|
|
||||||
constructor(code: ErrorCode) { super(formulaErrors[code]); this.code = code; }
|
|
||||||
}
|
|
||||||
function fail(code: ErrorCode): never { throw new FormulaError(code); }
|
|
||||||
export const isTableFormula = (text: string) => /^=(?!=)/.test(text.trim());
|
|
||||||
|
|
||||||
export function cellAddress(row: number, column: number): string {
|
|
||||||
let letters = "";
|
|
||||||
for (let n = column + 1; n > 0; n = Math.floor((n - 1) / 26)) letters = String.fromCharCode(65 + (n - 1) % 26) + letters;
|
|
||||||
return letters + (row + 1);
|
|
||||||
}
|
|
||||||
|
|
||||||
type Scalar = number | string | null;
|
|
||||||
type Value = Scalar | Scalar[];
|
|
||||||
const number = (value: Value): number => typeof value === "number" ? value : value === null ? 0 : fail("#VALUE!");
|
|
||||||
const finite = (value: number) => Number.isFinite(value) ? value : fail("#NUM!");
|
|
||||||
const numeric = /^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i;
|
|
||||||
|
|
||||||
// Header is row 1; the Markdown separator is not a spreadsheet row.
|
|
||||||
export function evaluateTableFormulas(grid: string[][]): (FormulaResult | null)[][] {
|
|
||||||
const cache = new Map<string, Scalar | FormulaError>();
|
|
||||||
const visiting = new Set<string>();
|
|
||||||
let budget = 50000;
|
|
||||||
const spend = () => { if (--budget < 0) fail("#LIMIT!"); };
|
|
||||||
function reference(address: string): [number, number] {
|
|
||||||
const match = /^\$?([A-Z]+)\$?([1-9]\d*)$/i.exec(address) || fail("#REF!");
|
|
||||||
let column = 0;
|
|
||||||
for (const letter of match[1].toUpperCase()) column = column * 26 + letter.charCodeAt(0) - 64;
|
|
||||||
const row = Number(match[2]);
|
|
||||||
if (row > grid.length || column > (grid[0]?.length || 0)) fail("#REF!");
|
|
||||||
return [row - 1, column - 1];
|
|
||||||
}
|
|
||||||
function cell(row: number, column: number): Scalar {
|
|
||||||
spend();
|
|
||||||
const key = `${row}:${column}`;
|
|
||||||
if (visiting.has(key)) fail("#CYCLE!");
|
|
||||||
if (visiting.size >= 128) fail("#LIMIT!");
|
|
||||||
const cached = cache.get(key);
|
|
||||||
if (cached instanceof FormulaError) throw cached;
|
|
||||||
if (cache.has(key)) return cached!;
|
|
||||||
const source = (grid[row]?.[column] || "").trim();
|
|
||||||
if (!isTableFormula(source)) return source === "" ? null : numeric.test(source) ? finite(Number(source)) : source;
|
|
||||||
visiting.add(key);
|
|
||||||
try {
|
|
||||||
const value = parse(source.slice(1));
|
|
||||||
cache.set(key, value);
|
|
||||||
return value;
|
|
||||||
} catch (error) {
|
|
||||||
const problem = error instanceof FormulaError ? error : new FormulaError("#LIMIT!");
|
|
||||||
cache.set(key, problem);
|
|
||||||
throw problem;
|
|
||||||
} finally { visiting.delete(key); }
|
|
||||||
}
|
|
||||||
function parse(source: string): number {
|
|
||||||
if (source.length > 2048) fail("#LIMIT!");
|
|
||||||
const tokens: string[] = [];
|
|
||||||
const pattern = /\s*(\$?[A-Za-z]+\$?\d+|[A-Za-z_]+|(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?|[+\-*/^%(),:])/y;
|
|
||||||
let offset = 0;
|
|
||||||
while (offset < source.trimEnd().length) {
|
|
||||||
pattern.lastIndex = offset;
|
|
||||||
const match = pattern.exec(source) || fail("#ERROR!");
|
|
||||||
tokens.push(match[1]); offset = pattern.lastIndex;
|
|
||||||
}
|
|
||||||
let position = 0, depth = 0;
|
|
||||||
const peek = () => tokens[position];
|
|
||||||
const take = () => { spend(); return tokens[position++]; };
|
|
||||||
const expect = (token: string) => { if (take() !== token) fail("#ERROR!"); };
|
|
||||||
function expression(min = 0): Value {
|
|
||||||
if (++depth > 64) fail("#LIMIT!");
|
|
||||||
let left: Value;
|
|
||||||
const token = take();
|
|
||||||
if (token === "+" || token === "-") left = number(expression(3)) * (token === "-" ? -1 : 1);
|
|
||||||
else if (token === "(") { left = expression(); expect(")"); }
|
|
||||||
else if (token && numeric.test(token)) left = finite(Number(token));
|
|
||||||
else if (token && /^\$?[a-z]+\$?\d+$/i.test(token)) {
|
|
||||||
const [row, column] = reference(token);
|
|
||||||
if (peek() === ":") {
|
|
||||||
take(); const [endRow, endColumn] = reference(take() || "");
|
|
||||||
const values: Scalar[] = [];
|
|
||||||
for (let r = Math.min(row, endRow); r <= Math.max(row, endRow); r++) {
|
|
||||||
for (let c = Math.min(column, endColumn); c <= Math.max(column, endColumn); c++) values.push(cell(r, c));
|
|
||||||
}
|
|
||||||
left = values;
|
|
||||||
} else left = cell(row, column);
|
|
||||||
} else if (token && /^[a-z_]+$/i.test(token)) {
|
|
||||||
if (peek() !== "(") fail("#NAME?");
|
|
||||||
take(); const args: Value[] = [];
|
|
||||||
if (peek() !== ")") {
|
|
||||||
do { args.push(expression()); if (peek() !== ",") break; take(); } while (true);
|
|
||||||
}
|
|
||||||
expect(")");
|
|
||||||
left = call(token.toUpperCase(), args);
|
|
||||||
} else fail("#ERROR!");
|
|
||||||
while (true) {
|
|
||||||
const op = peek();
|
|
||||||
if (op === "%") { take(); left = number(left) / 100; continue; }
|
|
||||||
const precedence = op === "+" || op === "-" ? 1 : op === "*" || op === "/" ? 2 : op === "^" ? 3 : -1;
|
|
||||||
if (precedence < min) break;
|
|
||||||
take();
|
|
||||||
const right = number(expression(precedence + (op === "^" ? 0 : 1))), a = number(left);
|
|
||||||
left = finite(op === "+" ? a + right : op === "-" ? a - right : op === "*" ? a * right : op === "/" ? (right === 0 ? fail("#DIV/0!") : a / right) : a ** right);
|
|
||||||
}
|
|
||||||
depth--;
|
|
||||||
return left;
|
|
||||||
}
|
|
||||||
const result = finite(number(expression()));
|
|
||||||
if (position !== tokens.length) fail("#ERROR!");
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
function call(name: string, args: Value[]): number {
|
|
||||||
if (name === "ABS") return args.length === 1 ? Math.abs(number(args[0])) : fail("#ERROR!");
|
|
||||||
if (name === "ROUND") {
|
|
||||||
if (args.length < 1 || args.length > 2) fail("#ERROR!");
|
|
||||||
const value = number(args[0]), digits = args.length === 2 ? number(args[1]) : 0;
|
|
||||||
if (!Number.isInteger(digits) || Math.abs(digits) > 100) fail("#NUM!");
|
|
||||||
const factor = 10 ** digits, scaled = Math.abs(value) * factor;
|
|
||||||
return finite(Math.sign(value) * Math.round(scaled + Number.EPSILON * scaled) / factor);
|
|
||||||
}
|
|
||||||
if (!["SUM", "AVERAGE", "MIN", "MAX", "COUNT"].includes(name)) fail("#NAME?");
|
|
||||||
const values = args.flat().filter((value): value is number => typeof value === "number");
|
|
||||||
if (name === "COUNT") return values.length;
|
|
||||||
if (name === "MIN" || name === "MAX") return values.length ? values.reduce((a, b) => name === "MIN" ? Math.min(a, b) : Math.max(a, b)) : 0;
|
|
||||||
const sum = finite(values.reduce((a, b) => a + b, 0));
|
|
||||||
return name === "AVERAGE" ? (values.length ? sum / values.length : fail("#DIV/0!")) : sum;
|
|
||||||
}
|
|
||||||
return grid.map((row, r) => row.map((source, c) => {
|
|
||||||
if (!isTableFormula(source)) return null;
|
|
||||||
const formula = source.trim();
|
|
||||||
try {
|
|
||||||
const value = number(cell(r, c));
|
|
||||||
return { formula, value, text: String(Number(value.toPrecision(12))) };
|
|
||||||
} catch (error) {
|
|
||||||
const code = error instanceof FormulaError ? error.code : "#LIMIT!";
|
|
||||||
return { formula, text: code, error: code };
|
|
||||||
}
|
|
||||||
}));
|
|
||||||
}
|
|
||||||
@@ -1,8 +0,0 @@
|
|||||||
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 });
|
|
||||||
}
|
|
||||||
@@ -1,11 +0,0 @@
|
|||||||
{
|
|
||||||
"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"
|
|
||||||
}
|
|
||||||
@@ -1,29 +0,0 @@
|
|||||||
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;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,11 +0,0 @@
|
|||||||
<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} />
|
|
||||||
@@ -1,261 +0,0 @@
|
|||||||
<script lang="ts">
|
|
||||||
import { onMount, tick } from "svelte";
|
|
||||||
import IconButton from "$lib/ui/IconButton.svelte";
|
|
||||||
import { actionMenu, type ActionMenuItem } from "$lib/ui/actionMenu";
|
|
||||||
import { workspaceRead } from "$lib/workspace/api";
|
|
||||||
import { ptyProfiles, ptyNewWindow, ptyDictation } from "./api";
|
|
||||||
import { directoryCommand, fileCommand, parseTasks, readSettings, remember, type ShellProfile, type TerminalControl, type TerminalSettings as Settings } from "./model";
|
|
||||||
import TerminalPicker from "./TerminalPicker.svelte";
|
|
||||||
import TerminalSettings from "./TerminalSettings.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 Picker = { title: string; items: { label: string; detail?: string; value: string }[]; onPick: (value: string) => void; empty?: string };
|
|
||||||
let { cwd, visible, maximized = false, standalone = false, onClose, onMaximize = () => {}, activeFile = false, onRunFile, getSelection = () => "", onConfigureTasks }: {
|
|
||||||
cwd: string; visible: boolean; maximized?: boolean; standalone?: boolean; onClose: () => void; onMaximize?: () => void;
|
|
||||||
activeFile?: boolean; onRunFile?: () => Promise<string | null>; getSelection?: () => string; onConfigureTasks?: () => Promise<void>;
|
|
||||||
} = $props();
|
|
||||||
let sessions = $state<Session[]>([]);
|
|
||||||
let profiles = $state<ShellProfile[]>([]);
|
|
||||||
let settings = $state(readSettings());
|
|
||||||
let activeId = $state("");
|
|
||||||
let loading = $state(true);
|
|
||||||
let error = $state("");
|
|
||||||
let railWidth = $state(205);
|
|
||||||
let picker = $state<Picker | null>(null);
|
|
||||||
let showSettings = $state(false);
|
|
||||||
let recentCommands = $state<string[]>([]);
|
|
||||||
let recentDirectories = $state<string[]>([]);
|
|
||||||
let menu: HTMLElement | undefined;
|
|
||||||
let menuAnchor: HTMLElement | undefined;
|
|
||||||
let profileAnchor: HTMLDivElement;
|
|
||||||
let moreAnchor: HTMLDivElement;
|
|
||||||
let panes: HTMLDivElement;
|
|
||||||
let sequence = 0;
|
|
||||||
let stopResize: (() => void) | undefined;
|
|
||||||
let ready: Promise<void> = Promise.resolve();
|
|
||||||
const controls = new Map<string, TerminalControl>();
|
|
||||||
const active = $derived(sessions.find(session => session.id === activeId));
|
|
||||||
const group = $derived(sessions.filter(session => session.group === active?.group));
|
|
||||||
const totalWeight = $derived(group.reduce((sum, session) => sum + session.weight, 0));
|
|
||||||
|
|
||||||
function report(reason: unknown) { error = String(reason); }
|
|
||||||
function persist(next: Settings) {
|
|
||||||
settings = { ...next };
|
|
||||||
try { localStorage.setItem("runestone.terminal", JSON.stringify(settings)); } catch (reason) { report(reason); }
|
|
||||||
}
|
|
||||||
function defaultProfile() { return profiles.find(profile => profile.id === settings.defaultProfile) || profiles.find(profile => profile.kind !== "node") || profiles[0]; }
|
|
||||||
export function addSession(profile = defaultProfile(), split = false, command?: string, title?: string) {
|
|
||||||
if (!profile) return;
|
|
||||||
const id = crypto.randomUUID();
|
|
||||||
const next = { id, group: split && active ? active.group : id, title: title || `${profile.title} ${++sequence}`, state: "Starting", profile,
|
|
||||||
directory: split && active ? active.directory : cwd, weight: 1, command };
|
|
||||||
if (split) for (const member of group) member.weight = 1;
|
|
||||||
sessions = [...sessions, next]; activeId = id;
|
|
||||||
recentDirectories = remember(recentDirectories, next.directory);
|
|
||||||
}
|
|
||||||
function killSession(id: string) {
|
|
||||||
const previous = sessions.findIndex(session => session.id === id);
|
|
||||||
const sibling = sessions.find(session => session.group === sessions[previous]?.group && session.id !== id);
|
|
||||||
sessions = sessions.filter(session => session.id !== id);
|
|
||||||
if (activeId === id) activeId = sibling?.id || sessions[Math.max(0, previous - 1)]?.id || "";
|
|
||||||
void tick().then(() => controls.get(activeId)?.focus());
|
|
||||||
}
|
|
||||||
function select(id: string) { activeId = id; }
|
|
||||||
function closeMenu(focus = false) { menu?.remove(); menu = undefined; if (focus) menuAnchor?.querySelector<HTMLButtonElement>("button")?.focus(); }
|
|
||||||
function showMenu(anchor: HTMLElement, items: ActionMenuItem[], name: string) {
|
|
||||||
const same = menu && menuAnchor === anchor; closeMenu(); if (same) return;
|
|
||||||
menuAnchor = anchor;
|
|
||||||
const wrap = (entries: ActionMenuItem[]): ActionMenuItem[] => entries.map(item => "separator" in item ? item : { ...item,
|
|
||||||
children: item.children ? wrap(item.children) : undefined,
|
|
||||||
run: item.run ? () => { closeMenu(); item.run?.(); } : undefined });
|
|
||||||
const bounds = anchor.getBoundingClientRect();
|
|
||||||
menu = actionMenu(bounds.right - 430, bounds.bottom + 4, wrap(items), () => closeMenu(true), name);
|
|
||||||
}
|
|
||||||
function profileMenu() {
|
|
||||||
showMenu(profileAnchor, [
|
|
||||||
{ label: "New Terminal", icon: "plus", shortcut: "Ctrl+Shift+`", run: () => addSession() },
|
|
||||||
{ label: "New Terminal Window", icon: "external", shortcut: "Ctrl+Shift+Alt+`", run: () => void ptyNewWindow().catch(report) },
|
|
||||||
{ label: "Split Terminal", icon: "column", shortcut: "Ctrl+Shift+5", disabled: !active, run: () => addSession(active?.profile, true) },
|
|
||||||
{ separator: true },
|
|
||||||
...profiles.map(profile => ({ label: profile.title, icon: "code" as const, title: profile.kind === "node" ? "Node.js REPL with a local inspector. Attach using an external debugger." : undefined, run: () => addSession(profile) })),
|
|
||||||
{ label: "Split Terminal with Profile", icon: "column", disabled: !active, children: profiles.map(profile => ({ label: profile.title, icon: "code", run: () => addSession(profile, true) })) },
|
|
||||||
{ separator: true },
|
|
||||||
{ label: "Configure Terminal Settings", icon: "format", run: () => showSettings = true },
|
|
||||||
{ label: "Select Default Profile", icon: "select", run: () => picker = { title: "Select default terminal profile", items: profiles.filter(profile => profile.kind !== "node").map(profile => ({ label: profile.title, value: profile.id, detail: profile.id === settings.defaultProfile ? "Default" : undefined })), onPick: value => persist({ ...settings, defaultProfile: value }) } },
|
|
||||||
{ separator: true },
|
|
||||||
{ label: "Run Task…", icon: "task", run: () => void runTask() },
|
|
||||||
{ label: "Configure Tasks…", icon: "code", disabled: !onConfigureTasks, run: () => void onConfigureTasks?.().catch(report) },
|
|
||||||
], "Terminal profiles");
|
|
||||||
}
|
|
||||||
async function runFile() {
|
|
||||||
const target = active;
|
|
||||||
if (!target || !onRunFile) return;
|
|
||||||
try { const path = await onRunFile(); if (path) controls.get(target.id)?.send(fileCommand(path, target.profile.kind)); } catch (reason) { report(reason); }
|
|
||||||
}
|
|
||||||
function runSelection() {
|
|
||||||
const text = getSelection();
|
|
||||||
if (!text) { error = "Select text in the editor first."; return; }
|
|
||||||
controls.get(activeId)?.send(text);
|
|
||||||
}
|
|
||||||
function historyPicker(kind: "commands" | "directories") {
|
|
||||||
const target = active;
|
|
||||||
if (!target) return;
|
|
||||||
picker = { title: kind === "commands" ? "Run recent command" : "Go to recent directory",
|
|
||||||
items: (kind === "commands" ? recentCommands : recentDirectories).map(value => ({ label: value, value })),
|
|
||||||
empty: kind === "commands" ? "No commands yet. Shell commands appear after the next prompt." : "No directories yet.",
|
|
||||||
onPick: value => { try { controls.get(target.id)?.send(kind === "commands" ? value : directoryCommand(value, target.profile.kind)); } catch (reason) { report(reason); } } };
|
|
||||||
}
|
|
||||||
async function runTask() {
|
|
||||||
try {
|
|
||||||
const tasks = parseTasks(await workspaceRead(".runestone/tasks.json"));
|
|
||||||
picker = { title: "Run task", items: tasks.map((task, index) => ({ label: task.label, detail: task.command, value: String(index) })), empty: "No tasks configured. Choose Configure Tasks… to add one.", onPick: index => {
|
|
||||||
const task = tasks[Number(index)];
|
|
||||||
const profile = task.profile ? profiles.find(profile => profile.id === task.profile) : defaultProfile();
|
|
||||||
if (!profile) { error = `Task profile is unavailable: ${task.profile}`; return; }
|
|
||||||
addSession(profile, false, task.command, task.label);
|
|
||||||
} };
|
|
||||||
} catch (reason) { error = `Cannot load .runestone/tasks.json. Use Configure Tasks… to create or edit it. ${String(reason)}`; }
|
|
||||||
}
|
|
||||||
function moreMenu() {
|
|
||||||
showMenu(moreAnchor, [
|
|
||||||
{ label: "Scroll to Previous Command", icon: "up", shortcut: "Ctrl+UpArrow", disabled: !active, run: () => controls.get(activeId)?.scrollCommand(-1) },
|
|
||||||
{ label: "Scroll to Next Command", icon: "down", shortcut: "Ctrl+DownArrow", disabled: !active, run: () => controls.get(activeId)?.scrollCommand(1) },
|
|
||||||
{ label: "Clear Terminal", icon: "clear", disabled: !active, run: () => controls.get(activeId)?.clear() },
|
|
||||||
{ label: "Run Active File", icon: "code", disabled: !active || !activeFile, run: () => void runFile() },
|
|
||||||
{ label: "Run Selected Text", icon: "select", disabled: !active || !activeFile, run: runSelection },
|
|
||||||
{ label: "Start Dictation", icon: "comment", disabled: !active, title: "Start Windows voice typing in the focused terminal", run: () => { controls.get(activeId)?.focus(); void ptyDictation().catch(report); } },
|
|
||||||
{ separator: true },
|
|
||||||
{ label: "Go to Recent Directory…", icon: "external", shortcut: "Ctrl+G", disabled: !active, run: () => historyPicker("directories") },
|
|
||||||
{ label: "Run Recent Command…", icon: "task", shortcut: "Ctrl+Alt+R", disabled: !active, run: () => historyPicker("commands") },
|
|
||||||
], "Terminal actions");
|
|
||||||
}
|
|
||||||
export async function command(action: "new" | "split" | "window" | "previous" | "next" | "commands" | "directories") {
|
|
||||||
await ready;
|
|
||||||
if (action === "new") addSession();
|
|
||||||
else if (action === "split") addSession(active?.profile || defaultProfile(), !!active);
|
|
||||||
else if (action === "window") void ptyNewWindow().catch(report);
|
|
||||||
else if (action === "previous" || action === "next") controls.get(activeId)?.scrollCommand(action === "previous" ? -1 : 1);
|
|
||||||
else historyPicker(action);
|
|
||||||
}
|
|
||||||
function beginResize(event: PointerEvent, update: (x: number) => void) {
|
|
||||||
if (event.button !== 0) return;
|
|
||||||
event.preventDefault(); stopResize?.();
|
|
||||||
const move = (event: PointerEvent) => update(event.clientX);
|
|
||||||
stopResize = () => { window.removeEventListener("pointermove", move); window.removeEventListener("pointerup", stop); window.removeEventListener("pointercancel", stop); stopResize = undefined; };
|
|
||||||
const stop = () => stopResize?.();
|
|
||||||
window.addEventListener("pointermove", move); window.addEventListener("pointerup", stop); window.addEventListener("pointercancel", stop);
|
|
||||||
}
|
|
||||||
function resizeRail(event: PointerEvent) { const x = event.clientX, width = railWidth; beginResize(event, next => railWidth = Math.min(340, Math.max(140, width + x - next))); }
|
|
||||||
function resizeSplit(event: PointerEvent, session: Session) {
|
|
||||||
const index = group.indexOf(session), previous = group[index - 1];
|
|
||||||
if (!previous) return;
|
|
||||||
const x = event.clientX, before = previous.weight, after = session.weight, width = panes.clientWidth, total = totalWeight;
|
|
||||||
beginResize(event, next => { const change = (next - x) / width * total; previous.weight = Math.min(before + after - .15, Math.max(.15, before + change)); session.weight = before + after - previous.weight; });
|
|
||||||
}
|
|
||||||
function paneLeft(session: Session) { return group.slice(0, group.indexOf(session)).reduce((sum, item) => sum + item.weight, 0) / totalWeight * 100; }
|
|
||||||
onMount(() => {
|
|
||||||
let disposed = false;
|
|
||||||
ready = ptyProfiles().then(found => {
|
|
||||||
if (disposed) return;
|
|
||||||
profiles = found;
|
|
||||||
if (!profiles.some(profile => profile.id === settings.defaultProfile)) settings.defaultProfile = defaultProfile()?.id || "";
|
|
||||||
if (profiles.length) addSession(); else error = "No supported shells were found on PATH.";
|
|
||||||
}).catch(report).finally(() => loading = false);
|
|
||||||
const outside = (event: PointerEvent) => { if (menu && !menu.contains(event.target as Node) && !menuAnchor?.contains(event.target as Node)) closeMenu(); };
|
|
||||||
const resize = () => closeMenu();
|
|
||||||
window.addEventListener("pointerdown", outside); window.addEventListener("resize", resize);
|
|
||||||
return () => { disposed = true; closeMenu(); stopResize?.(); window.removeEventListener("pointerdown", outside); window.removeEventListener("resize", resize); };
|
|
||||||
});
|
|
||||||
$effect(() => { if (!visible) { closeMenu(); picker = null; showSettings = false; } });
|
|
||||||
</script>
|
|
||||||
|
|
||||||
<div class="dock" style:--rail="{railWidth}px">
|
|
||||||
<header class="ribbon">
|
|
||||||
<span class="label" title={cwd}>Terminal</span><span class="directory" title={active?.directory || cwd}>{active?.directory || cwd}</span>
|
|
||||||
<div class="actions">
|
|
||||||
{#if sessions.length === 1}<span class="single-session" title={`${active?.title} · ${active?.state}`}>{active?.profile.title}</span>{/if}
|
|
||||||
<IconButton icon="plus" label="New terminal" disabled={loading || !profiles.length} onclick={() => addSession()} />
|
|
||||||
<div bind:this={profileAnchor}><IconButton icon="chevron-down" label="Terminal profiles and tasks" disabled={loading} onclick={profileMenu} /></div>
|
|
||||||
<IconButton icon="split" label="Split terminal (Ctrl+Shift+5)" disabled={!active} onclick={() => addSession(active?.profile, true)} />
|
|
||||||
<div bind:this={moreAnchor}><IconButton icon="more" label="More terminal actions" onclick={moreMenu} /></div>
|
|
||||||
<IconButton icon="trash" label="Kill terminal" disabled={!active} onclick={() => killSession(activeId)} />
|
|
||||||
{#if !standalone}<IconButton icon={maximized ? "restore" : "maximize"} label={maximized ? "Restore panel" : "Maximize panel"} onclick={onMaximize} />{/if}
|
|
||||||
<IconButton icon="close" label={standalone ? "Close terminal window" : "Hide terminal (sessions keep running)"} onclick={onClose} />
|
|
||||||
</div>
|
|
||||||
</header>
|
|
||||||
{#if error}<div class="error" role="alert"><span>{error}</span><button aria-label="Dismiss terminal error" onclick={() => error = ""}>×</button></div>{/if}
|
|
||||||
<div class="body">
|
|
||||||
<div class="panes" bind:this={panes}>
|
|
||||||
{#each sessions as session (session.id)}
|
|
||||||
<div class="pane" class:shown={session.group === active?.group} class:focused={session.id === activeId}
|
|
||||||
style:left="{session.group === active?.group ? paneLeft(session) : 0}%" style:width="{session.group === active?.group ? session.weight / totalWeight * 100 : 100}%">
|
|
||||||
{#if group.length > 1 && session.group === active?.group}<div class="pane-label">{session.title}</div>{/if}
|
|
||||||
<TerminalPane id={session.id} {cwd} directory={session.directory} profile={session.profile} {settings}
|
|
||||||
active={visible && session.group === active?.group} focused={session.id === activeId} onFocus={() => activeId = session.id}
|
|
||||||
onState={state => { session.state = state; if (state === "Running" && session.command) { controls.get(session.id)?.send(session.command); session.command = undefined; } }}
|
|
||||||
onControl={control => { if (control) controls.set(session.id, control); else controls.delete(session.id); }}
|
|
||||||
onCommand={command => recentCommands = remember(recentCommands, command)}
|
|
||||||
onDirectory={directory => { session.directory = directory; recentDirectories = remember(recentDirectories, directory); }} />
|
|
||||||
{#if session.group === active?.group && group.indexOf(session) > 0}
|
|
||||||
<div class="split-gutter" role="separator" aria-label="Resize split terminals" aria-orientation="vertical" onpointerdown={event => resizeSplit(event, session)}></div>
|
|
||||||
{/if}
|
|
||||||
</div>
|
|
||||||
{/each}
|
|
||||||
{#if !sessions.length}<div class="empty"><p>{loading ? "Detecting terminal profiles…" : "No terminal sessions."}</p><button disabled={loading || !profiles.length} onclick={() => addSession()}>Start a terminal</button></div>{/if}
|
|
||||||
</div>
|
|
||||||
{#if sessions.length > 1}
|
|
||||||
<div class="gutter" role="separator" aria-orientation="vertical" aria-label="Resize terminal list" onpointerdown={resizeRail}></div>
|
|
||||||
<nav class="rail" aria-label="Terminal list">
|
|
||||||
{#each sessions as session (session.id)}
|
|
||||||
<div class="item" data-session={session.id} class:active={session.id === activeId} class:grouped={sessions.filter(item => item.group === session.group).length > 1}>
|
|
||||||
<button class="pick" aria-pressed={session.id === activeId} title={`${session.title} · ${session.state} · ${session.directory}`} onclick={() => select(session.id)}
|
|
||||||
onkeydown={event => {
|
|
||||||
if (event.key === "Delete") { event.preventDefault(); killSession(session.id); }
|
|
||||||
if (event.key === "ArrowDown" || event.key === "ArrowUp") { event.preventDefault(); const next = sessions[(sessions.indexOf(session) + (event.key === "ArrowDown" ? 1 : sessions.length - 1)) % sessions.length]; activeId = next.id; (event.currentTarget.closest("nav")?.querySelector(`[data-session="${next.id}"] .pick`) as HTMLButtonElement)?.focus(); }
|
|
||||||
}}><span class="shell-icon" aria-hidden="true">›_</span><span class="session-name">{session.title}<small>{session.state}</small></span></button>
|
|
||||||
<div class="row-actions">
|
|
||||||
<IconButton icon="split" label={`Split ${session.title}`} onclick={() => { activeId = session.id; addSession(session.profile, true); }} />
|
|
||||||
<IconButton icon="trash" label={`Kill ${session.title} (Del)`} onclick={() => killSession(session.id)} />
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
{/each}
|
|
||||||
</nav>
|
|
||||||
{/if}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
{#if picker}<TerminalPicker {...picker} onClose={() => picker = null} />{/if}
|
|
||||||
{#if showSettings}<TerminalSettings {settings} {profiles} onSave={persist} onClose={() => showSettings = false} />{/if}
|
|
||||||
<style>
|
|
||||||
.dock { display: flex; flex-direction: column; height: 100%; min-height: 0; }
|
|
||||||
.ribbon { display: flex; align-items: center; gap: 10px; flex: 0 0 36px; padding: 0 8px; background: var(--rs-bg-elevated); }
|
|
||||||
.label { font-size: 13px; color: var(--rs-text-strong); }
|
|
||||||
.directory { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: var(--rs-text-dim); font-size: 12px; }
|
|
||||||
.actions, .row-actions { display: flex; align-items: center; flex-shrink: 0; }
|
|
||||||
.single-session { max-width: 130px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: 12px; color: var(--rs-text-dim); margin-right: 6px; }
|
|
||||||
.body { display: flex; flex: 1; min-height: 0; }
|
|
||||||
.panes { flex: 1; position: relative; min-width: 0; min-height: 0; }
|
|
||||||
.pane { display: flex; flex-direction: column; position: absolute; top: 0; bottom: 0; visibility: hidden; min-width: 0; overflow: hidden; }
|
|
||||||
.pane.shown { visibility: visible; }
|
|
||||||
.pane :global(.term) { flex: 1; min-height: 0; height: auto; }
|
|
||||||
.pane-label { flex: 0 0 23px; padding: 3px 10px; font-size: 11px; color: var(--rs-text-dim); border-top: 1px solid transparent; }
|
|
||||||
.focused .pane-label { color: var(--rs-text-strong); border-top-color: var(--rs-accent); }
|
|
||||||
.split-gutter { position: absolute; top: 0; bottom: 0; left: 0; width: 4px; cursor: col-resize; background: var(--rs-border); }
|
|
||||||
.gutter { flex: 0 0 4px; cursor: col-resize; }
|
|
||||||
.gutter:hover, .split-gutter:hover { background: var(--rs-accent); }
|
|
||||||
.rail { flex: 0 0 var(--rail); width: var(--rail); overflow: auto; padding: 4px; border-left: 1px solid var(--rs-border); }
|
|
||||||
.item { display: flex; align-items: center; min-width: 0; border-left: 2px solid transparent; }
|
|
||||||
.item.grouped { border-left-color: var(--rs-border); }
|
|
||||||
.item.active { background: var(--rs-bg-active); border-left-color: var(--rs-accent); }
|
|
||||||
.pick { display: flex; align-items: center; gap: 7px; flex: 1; min-width: 0; border: 0; background: transparent; text-align: left; padding: 5px; }
|
|
||||||
.shell-icon { color: var(--rs-text-dim); }
|
|
||||||
.session-name { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
|
||||||
small { display: block; font-size: 10px; color: var(--rs-text-dim); }
|
|
||||||
.row-actions { visibility: hidden; }
|
|
||||||
.item:hover .row-actions, .item:focus-within .row-actions, .item.active .row-actions { visibility: visible; }
|
|
||||||
.error { padding: 7px 12px; display: flex; align-items: center; gap: 8px; color: var(--rs-error); font-size: 12px; border-bottom: 1px solid var(--rs-border); }
|
|
||||||
.error span { flex: 1; }
|
|
||||||
.error button, .empty button { background: var(--rs-bg-active); border: 1px solid var(--rs-border); padding: 4px 8px; }
|
|
||||||
.empty { padding: 20px; color: var(--rs-text-dim); }
|
|
||||||
@media (max-width: 700px) { .rail { flex-basis: 150px; width: 150px; } .row-actions { display: none; } .directory, .single-session { display: none; } .label { flex: 1; } }
|
|
||||||
</style>
|
|
||||||
@@ -1,218 +0,0 @@
|
|||||||
<script lang="ts">
|
|
||||||
import { listen } from "@tauri-apps/api/event";
|
|
||||||
import { FitAddon } from "@xterm/addon-fit";
|
|
||||||
import { Terminal } from "@xterm/xterm";
|
|
||||||
import { onMount } from "svelte";
|
|
||||||
import { ptyClose, ptyOpen, ptyResize, ptyWrite } from "./api";
|
|
||||||
import { terminalShortcut, type ShellProfile, type TerminalControl, type TerminalSettings } from "./model";
|
|
||||||
import "@xterm/xterm/css/xterm.css";
|
|
||||||
|
|
||||||
type Props = {
|
|
||||||
id: string;
|
|
||||||
cwd: string;
|
|
||||||
active: boolean;
|
|
||||||
focused: boolean;
|
|
||||||
profile: ShellProfile;
|
|
||||||
directory: string;
|
|
||||||
settings: TerminalSettings;
|
|
||||||
onFocus: () => void;
|
|
||||||
onControl: (control: TerminalControl | null) => void;
|
|
||||||
onCommand: (command: string) => void;
|
|
||||||
onDirectory: (directory: string) => void;
|
|
||||||
onState: (state: string) => void;
|
|
||||||
};
|
|
||||||
|
|
||||||
let { id, cwd, active, focused, profile, directory, settings, onFocus, onControl, onCommand, onDirectory, onState }: Props = $props();
|
|
||||||
let host: HTMLDivElement | undefined = $state();
|
|
||||||
let focusTerminal: (() => void) | undefined = $state();
|
|
||||||
let instance = $state.raw<Terminal>();
|
|
||||||
let resizeTerminal: (() => void) | undefined;
|
|
||||||
|
|
||||||
$effect(() => { if (active && focused && !document.activeElement?.closest(".rail")) focusTerminal?.(); });
|
|
||||||
$effect(() => {
|
|
||||||
if (instance) {
|
|
||||||
instance.options.fontSize = settings.fontSize;
|
|
||||||
instance.options.scrollback = settings.scrollback;
|
|
||||||
instance.options.cursorBlink = settings.cursorBlink;
|
|
||||||
requestAnimationFrame(() => resizeTerminal?.());
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
onMount(() => {
|
|
||||||
if (!host) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
const term = new Terminal({
|
|
||||||
scrollback: settings.scrollback,
|
|
||||||
fontFamily: "Cascadia Code, Cascadia Mono, Consolas, monospace",
|
|
||||||
fontSize: settings.fontSize,
|
|
||||||
cursorBlink: settings.cursorBlink,
|
|
||||||
allowProposedApi: true,
|
|
||||||
theme: {
|
|
||||||
background: "#141414",
|
|
||||||
foreground: "#e6e6e6",
|
|
||||||
cursor: "#82aaff",
|
|
||||||
selectionBackground: "#264f78",
|
|
||||||
black: "#3b4252",
|
|
||||||
red: "#bf616a",
|
|
||||||
green: "#a3be8c",
|
|
||||||
yellow: "#ebcb8b",
|
|
||||||
blue: "#81a1c1",
|
|
||||||
magenta: "#b48ead",
|
|
||||||
cyan: "#88c0d0",
|
|
||||||
white: "#e5e9f0",
|
|
||||||
},
|
|
||||||
});
|
|
||||||
const fit = new FitAddon();
|
|
||||||
term.loadAddon(fit);
|
|
||||||
term.open(host);
|
|
||||||
instance = term;
|
|
||||||
term.attachCustomKeyEventHandler(event => !terminalShortcut(event));
|
|
||||||
let disposed = false;
|
|
||||||
let opened = false;
|
|
||||||
let exited = false;
|
|
||||||
const pendingInput: string[] = [];
|
|
||||||
let writes = Promise.resolve();
|
|
||||||
const unlisteners: (() => void)[] = [];
|
|
||||||
const fail = (err: unknown) => {
|
|
||||||
if (!disposed) term.writeln(`\r\n${String(err)}`);
|
|
||||||
};
|
|
||||||
const resize = () => {
|
|
||||||
if (disposed || !host?.clientWidth || !host?.clientHeight) return;
|
|
||||||
fit.fit();
|
|
||||||
if (opened && !exited) void ptyResize(id, term.cols, term.rows).catch(fail);
|
|
||||||
};
|
|
||||||
resizeTerminal = resize;
|
|
||||||
focusTerminal = () => { resize(); term.focus(); };
|
|
||||||
const send = (data: string) => {
|
|
||||||
if (exited || disposed) return;
|
|
||||||
if (!opened) { pendingInput.push(data); return; }
|
|
||||||
writes = writes.then(() => ptyWrite(id, data)).catch(fail);
|
|
||||||
};
|
|
||||||
const onData = term.onData(send);
|
|
||||||
let markers: import("@xterm/xterm").IMarker[] = [];
|
|
||||||
let prompt: { marker: import("@xterm/xterm").IMarker; column: number } | undefined;
|
|
||||||
const promptParser = term.parser.registerOscHandler(133, data => {
|
|
||||||
if (data === "A") {
|
|
||||||
const marker = term.registerMarker(0);
|
|
||||||
if (marker) markers = [...markers.filter(item => !item.isDisposed), marker].slice(-1000);
|
|
||||||
}
|
|
||||||
if (data === "B") {
|
|
||||||
prompt?.marker.dispose();
|
|
||||||
const marker = term.registerMarker(0);
|
|
||||||
prompt = marker ? { marker, column: term.buffer.active.cursorX } : undefined;
|
|
||||||
}
|
|
||||||
return true;
|
|
||||||
});
|
|
||||||
const integration = term.parser.registerOscHandler(633, data => {
|
|
||||||
const separator = data.indexOf(";");
|
|
||||||
const type = data.slice(0, separator), value = data.slice(separator + 1);
|
|
||||||
try {
|
|
||||||
if (type === "Cwd") onDirectory(value);
|
|
||||||
if (type === "RSCwd" || type === "RSCommand") {
|
|
||||||
const decoded = new TextDecoder().decode(Uint8Array.from(atob(value), char => char.charCodeAt(0)));
|
|
||||||
if (type === "RSCwd") onDirectory(decoded); else onCommand(decoded);
|
|
||||||
}
|
|
||||||
} catch { /* Ignore malformed shell integration output. */ }
|
|
||||||
return true;
|
|
||||||
});
|
|
||||||
const keys = term.onKey(({ domEvent }) => {
|
|
||||||
if (profile.kind !== "cmd" || domEvent.key !== "Enter" || !prompt || prompt.marker.isDisposed) return;
|
|
||||||
const buffer = term.buffer.active;
|
|
||||||
let command = "";
|
|
||||||
for (let line = prompt.marker.line; line <= buffer.baseY + buffer.cursorY; line++) {
|
|
||||||
command += buffer.getLine(line)?.translateToString(true, line === prompt.marker.line ? prompt.column : 0) || "";
|
|
||||||
}
|
|
||||||
if (command.trim()) onCommand(command);
|
|
||||||
prompt.marker.dispose(); prompt = undefined;
|
|
||||||
});
|
|
||||||
onControl({
|
|
||||||
focus: () => { resize(); term.focus(); },
|
|
||||||
clear: () => { markers.forEach(marker => marker.dispose()); markers = []; term.clear(); term.focus(); },
|
|
||||||
scrollCommand: direction => {
|
|
||||||
const lines = markers.filter(marker => !marker.isDisposed).map(marker => marker.line);
|
|
||||||
const current = term.buffer.active.viewportY;
|
|
||||||
const target = direction < 0 ? lines.reverse().find(line => line < current) : lines.find(line => line > current);
|
|
||||||
if (target !== undefined) term.scrollToLine(target); else if (direction > 0) term.scrollToBottom();
|
|
||||||
},
|
|
||||||
send: (text, execute = true) => {
|
|
||||||
if (exited) return;
|
|
||||||
term.paste(text.replace(/\r?\n/g, "\r"));
|
|
||||||
if (execute) send("\r");
|
|
||||||
term.focus();
|
|
||||||
},
|
|
||||||
});
|
|
||||||
const start = async () => {
|
|
||||||
try {
|
|
||||||
// Subscribe before spawning: shells and agents can print immediately.
|
|
||||||
const offData = await listen<{ id: string; data: number[] }>("pty-data", (event) => {
|
|
||||||
if (!disposed && event.payload.id === id) term.write(new Uint8Array(event.payload.data));
|
|
||||||
});
|
|
||||||
unlisteners.push(offData);
|
|
||||||
if (disposed) return;
|
|
||||||
const offExit = await listen<{ id: string; code: number | null }>("pty-exit", (event) => {
|
|
||||||
if (!disposed && event.payload.id === id) {
|
|
||||||
exited = true;
|
|
||||||
onState(`Exited${event.payload.code === null ? "" : ` (${event.payload.code})`}`);
|
|
||||||
term.writeln(`\r\n[Process exited${event.payload.code === null ? "" : ` with code ${event.payload.code}`} ]`);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
unlisteners.push(offExit);
|
|
||||||
if (disposed) return;
|
|
||||||
resize();
|
|
||||||
await ptyOpen(id, term.cols, term.rows, cwd, profile.id, directory);
|
|
||||||
opened = true;
|
|
||||||
if (disposed) { await ptyClose(id); return; }
|
|
||||||
// Includes xterm's replies to startup cursor-position queries.
|
|
||||||
for (const data of pendingInput.splice(0)) {
|
|
||||||
writes = writes.then(() => ptyWrite(id, data)).catch(fail);
|
|
||||||
}
|
|
||||||
if (!exited) onState("Running");
|
|
||||||
resize();
|
|
||||||
if (active && focused) term.focus();
|
|
||||||
} catch (err) {
|
|
||||||
fail(err);
|
|
||||||
if (!disposed) onState("Failed");
|
|
||||||
} finally {
|
|
||||||
if (disposed) unlisteners.splice(0).forEach((off) => off());
|
|
||||||
}
|
|
||||||
};
|
|
||||||
void start();
|
|
||||||
const observer = new ResizeObserver(resize);
|
|
||||||
observer.observe(host);
|
|
||||||
return () => {
|
|
||||||
disposed = true;
|
|
||||||
focusTerminal = undefined;
|
|
||||||
instance = undefined;
|
|
||||||
resizeTerminal = undefined;
|
|
||||||
onControl(null);
|
|
||||||
observer.disconnect();
|
|
||||||
onData.dispose();
|
|
||||||
promptParser.dispose(); integration.dispose(); keys.dispose();
|
|
||||||
unlisteners.splice(0).forEach((off) => off());
|
|
||||||
if (opened) void ptyClose(id).catch(() => {});
|
|
||||||
term.dispose();
|
|
||||||
};
|
|
||||||
});
|
|
||||||
</script>
|
|
||||||
|
|
||||||
<div class="term" data-cwd={directory} bind:this={host} onfocusin={onFocus}></div>
|
|
||||||
|
|
||||||
<style>
|
|
||||||
.term {
|
|
||||||
height: 100%;
|
|
||||||
min-height: 0;
|
|
||||||
padding: 4px;
|
|
||||||
background: #141414;
|
|
||||||
}
|
|
||||||
|
|
||||||
.term :global(.xterm),
|
|
||||||
.term :global(.xterm-viewport) {
|
|
||||||
height: 100%;
|
|
||||||
}
|
|
||||||
|
|
||||||
.term :global(.xterm-viewport) {
|
|
||||||
/* Whole terminal rows can leave a gap above the bottom edge. */
|
|
||||||
background-color: transparent;
|
|
||||||
}
|
|
||||||
</style>
|
|
||||||
@@ -1,43 +0,0 @@
|
|||||||
<script lang="ts">
|
|
||||||
import { onMount, tick } from "svelte";
|
|
||||||
let { title, items, onPick, onClose, empty = "No entries yet." }: {
|
|
||||||
title: string; items: { label: string; detail?: string; value: string }[];
|
|
||||||
onPick: (value: string) => void; onClose: () => void; empty?: string;
|
|
||||||
} = $props();
|
|
||||||
let query = $state("");
|
|
||||||
let selected = $state(0);
|
|
||||||
let dialog: HTMLDialogElement;
|
|
||||||
let input: HTMLInputElement;
|
|
||||||
const matches = $derived(items.filter(item => `${item.label} ${item.detail || ""}`.toLowerCase().includes(query.toLowerCase())));
|
|
||||||
async function pick(value?: string) { if (value !== undefined) { const choose = onPick; onClose(); await tick(); choose(value); } }
|
|
||||||
onMount(() => { dialog.showModal(); input.focus(); });
|
|
||||||
</script>
|
|
||||||
<dialog bind:this={dialog} oncancel={onClose} aria-label={title}>
|
|
||||||
<header>{title}<button aria-label="Close picker" onclick={onClose}>×</button></header>
|
|
||||||
<input bind:this={input} bind:value={query} aria-label={title} placeholder="Type to filter…" oninput={() => selected = 0} onkeydown={event => {
|
|
||||||
if (event.key === "ArrowDown" || event.key === "ArrowUp") {
|
|
||||||
event.preventDefault(); selected = Math.max(0, Math.min(matches.length - 1, selected + (event.key === "ArrowDown" ? 1 : -1)));
|
|
||||||
dialog.querySelector(`[data-index="${selected}"]`)?.scrollIntoView({ block: "nearest" });
|
|
||||||
}
|
|
||||||
if (event.key === "Enter") { event.preventDefault(); pick(matches[selected]?.value); }
|
|
||||||
}} />
|
|
||||||
<div class="results">
|
|
||||||
{#each matches as item, index}
|
|
||||||
<button data-index={index} class:selected={index === selected} onclick={() => pick(item.value)}><span>{item.label}</span>{#if item.detail}<small>{item.detail}</small>{/if}</button>
|
|
||||||
{/each}
|
|
||||||
{#if !matches.length}<p>{query ? "No matching entries." : empty}</p>{/if}
|
|
||||||
</div>
|
|
||||||
<footer>↑ ↓ select · Enter choose · Esc close</footer>
|
|
||||||
</dialog>
|
|
||||||
<style>
|
|
||||||
dialog { margin-top: 12vh; padding: 0; width: min(640px, 85vw); background: var(--rs-bg-elevated); color: var(--rs-text); border: 1px solid var(--rs-border); border-radius: 8px; }
|
|
||||||
dialog::backdrop { background: #0008; }
|
|
||||||
header { display: flex; align-items: center; justify-content: space-between; padding: 8px 16px; }
|
|
||||||
input { width: 100%; padding: 14px; background: var(--rs-bg); color: var(--rs-text-strong); border: 0; }
|
|
||||||
.results { max-height: 50vh; overflow: auto; padding: 6px; }
|
|
||||||
button { background: transparent; border: 0; padding: 8px; }
|
|
||||||
.results button { display: flex; flex-direction: column; width: 100%; text-align: left; gap: 4px; overflow-wrap: anywhere; white-space: pre-wrap; }
|
|
||||||
button.selected, button:hover { background: var(--rs-bg-active); }
|
|
||||||
small, footer, p { color: var(--rs-text-dim); }
|
|
||||||
footer { padding: 10px 14px; border-top: 1px solid var(--rs-border); font-size: 12px; }
|
|
||||||
</style>
|
|
||||||
@@ -1,30 +0,0 @@
|
|||||||
<script lang="ts">
|
|
||||||
import { onMount, untrack } from "svelte";
|
|
||||||
import type { TerminalSettings, ShellProfile } from "./model";
|
|
||||||
let { settings, profiles, onSave, onClose }: { settings: TerminalSettings; profiles: ShellProfile[]; onSave: (settings: TerminalSettings) => void; onClose: () => void } = $props();
|
|
||||||
let value = $state(untrack(() => ({ ...settings })));
|
|
||||||
let dialog: HTMLDialogElement;
|
|
||||||
onMount(() => dialog.showModal());
|
|
||||||
</script>
|
|
||||||
<dialog bind:this={dialog} oncancel={onClose} aria-label="Terminal settings">
|
|
||||||
<form onsubmit={event => { event.preventDefault(); onSave(value); onClose(); }}>
|
|
||||||
<h2>Terminal settings</h2>
|
|
||||||
<label>Default profile<select aria-label="Default profile" bind:value={value.defaultProfile}>{#each profiles.filter(p => p.kind !== "node") as profile}<option value={profile.id}>{profile.title}</option>{/each}</select></label>
|
|
||||||
<label>Font size<input type="number" min="9" max="28" required bind:value={value.fontSize} /></label>
|
|
||||||
<label>Scrollback lines<input type="number" min="100" max="100000" step="100" required bind:value={value.scrollback} /></label>
|
|
||||||
<label class="check"><input type="checkbox" bind:checked={value.cursorBlink} />Blink cursor</label>
|
|
||||||
<p>Appearance applies to open sessions. The default profile applies to new terminals.</p>
|
|
||||||
<footer><button type="button" onclick={onClose}>Cancel</button><button type="submit">Save settings</button></footer>
|
|
||||||
</form>
|
|
||||||
</dialog>
|
|
||||||
<style>
|
|
||||||
dialog { width: min(450px, 90vw); background: var(--rs-bg-elevated); color: var(--rs-text); border: 1px solid var(--rs-border); border-radius: 8px; padding: 24px; }
|
|
||||||
dialog::backdrop { background: #0008; }
|
|
||||||
h2 { font-size: 18px; margin: 0 0 8px; }
|
|
||||||
form { display: flex; flex-direction: column; gap: 16px; }
|
|
||||||
label { display: flex; flex-direction: column; gap: 6px; }
|
|
||||||
label.check { flex-direction: row; }
|
|
||||||
input, select, button { background: var(--rs-bg); color: var(--rs-text); border: 1px solid var(--rs-border); padding: 7px; }
|
|
||||||
p { color: var(--rs-text-dim); font-size: 12px; margin: 0; }
|
|
||||||
footer { display: flex; justify-content: flex-end; gap: 8px; }
|
|
||||||
</style>
|
|
||||||
@@ -1,47 +0,0 @@
|
|||||||
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;
|
|
||||||
}
|
|
||||||
@@ -1,29 +0,0 @@
|
|||||||
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 };
|
|
||||||
},
|
|
||||||
});
|
|
||||||
}
|
|
||||||
@@ -1,70 +0,0 @@
|
|||||||
export type ShellProfile = { id: string; title: string; kind: "powershell" | "bash" | "cmd" | "node" };
|
|
||||||
export type TerminalSettings = { defaultProfile: string; fontSize: number; scrollback: number; cursorBlink: boolean };
|
|
||||||
export type TerminalControl = { focus(): void; clear(): void; scrollCommand(direction: -1 | 1): void; send(text: string, execute?: boolean): void };
|
|
||||||
export type TerminalTask = { label: string; command: string; profile?: string };
|
|
||||||
export const defaultSettings: TerminalSettings = { defaultProfile: "", fontSize: 13, scrollback: 10000, cursorBlink: true };
|
|
||||||
|
|
||||||
export function readSettings(): TerminalSettings {
|
|
||||||
try {
|
|
||||||
const value = JSON.parse(localStorage.getItem("runestone.terminal") || "{}");
|
|
||||||
return { defaultProfile: typeof value.defaultProfile === "string" ? value.defaultProfile : "",
|
|
||||||
fontSize: Number.isFinite(value.fontSize) ? Math.min(28, Math.max(9, value.fontSize)) : 13,
|
|
||||||
scrollback: Number.isFinite(value.scrollback) ? Math.min(100000, Math.max(100, value.scrollback)) : 10000,
|
|
||||||
cursorBlink: typeof value.cursorBlink === "boolean" ? value.cursorBlink : true };
|
|
||||||
} catch { return { ...defaultSettings }; }
|
|
||||||
}
|
|
||||||
|
|
||||||
export function quoteShell(value: string, kind: ShellProfile["kind"]): string {
|
|
||||||
if (/[\r\n\0]/.test(value)) throw new Error("Paths cannot contain line breaks or null characters.");
|
|
||||||
if (kind === "cmd") {
|
|
||||||
// Expansion happens even inside cmd quotes. Reject rather than execute a different path.
|
|
||||||
if (/["%!]/.test(value)) throw new Error("Use PowerShell for paths containing quotes, % or !.");
|
|
||||||
return `"${value}"`;
|
|
||||||
}
|
|
||||||
if (kind === "bash") return `'${value.replaceAll("'", "'\\''")}'`;
|
|
||||||
return `'${value.replaceAll("'", "''")}'`;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function directoryCommand(path: string, kind: ShellProfile["kind"]): string {
|
|
||||||
if (kind === "node") return `process.chdir(${JSON.stringify(path)})`;
|
|
||||||
const normalized = kind === "bash" ? path.replaceAll("\\", "/") : path;
|
|
||||||
return `${kind === "powershell" ? "Set-Location -LiteralPath" : kind === "cmd" ? "cd /d" : "cd --"} ${quoteShell(normalized, kind)}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function fileCommand(path: string, kind: ShellProfile["kind"]): string {
|
|
||||||
if (kind === "node") throw new Error("Choose a shell terminal to run files. The debug terminal is a Node.js REPL.");
|
|
||||||
const ext = path.split(".").pop()?.toLowerCase();
|
|
||||||
const quoted = quoteShell(kind === "bash" ? path.replaceAll("\\", "/") : path, kind);
|
|
||||||
const runner = ext === "py" ? "python" : ["js", "mjs", "cjs"].includes(ext || "") ? "node"
|
|
||||||
: ext === "ps1" ? "powershell -NoLogo -File" : ext === "sh" ? "bash" : ext === "rb" ? "ruby"
|
|
||||||
: ext === "bat" || ext === "cmd" ? "cmd /c" : ext === "exe" ? "" : null;
|
|
||||||
if (runner === null) throw new Error("No runner for this file type. Use Run Selected Text or configure a task.");
|
|
||||||
return `${runner || (kind === "powershell" ? "&" : "")}${runner || kind === "powershell" ? " " : ""}${quoted}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function parseTasks(text: string): TerminalTask[] {
|
|
||||||
const value = JSON.parse(text);
|
|
||||||
if (!Array.isArray(value.tasks)) throw new Error('Tasks must contain a "tasks" array.');
|
|
||||||
return value.tasks.map((task: unknown) => {
|
|
||||||
if (!task || typeof task !== "object" || !("label" in task) || typeof task.label !== "string" || !task.label.trim()
|
|
||||||
|| !("command" in task) || typeof task.command !== "string" || !task.command.trim()
|
|
||||||
|| ("profile" in task && typeof task.profile !== "string")) throw new Error("Each task needs a label, command, and optional profile ID.");
|
|
||||||
return task as TerminalTask;
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
export function remember(items: string[], value: string): string[] {
|
|
||||||
return value.trim() ? [value, ...items.filter(item => item !== value)].slice(0, 100) : items;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function terminalShortcut(event: Pick<KeyboardEvent, "ctrlKey" | "metaKey" | "altKey" | "shiftKey" | "code" | "key">): "toggle" | "new" | "window" | "split" | "previous" | "next" | "commands" | "directories" | null {
|
|
||||||
if (!event.ctrlKey && !event.metaKey) return null;
|
|
||||||
if (event.code === "Backquote" || event.key === "`") return event.shiftKey ? event.altKey ? "window" : "new" : "toggle";
|
|
||||||
if (event.shiftKey && event.code === "Digit5" && !event.altKey) return "split";
|
|
||||||
if (!event.shiftKey && !event.altKey && event.key.toLowerCase() === "j") return "toggle";
|
|
||||||
if (!event.shiftKey && !event.altKey && event.key === "ArrowUp") return "previous";
|
|
||||||
if (!event.shiftKey && !event.altKey && event.key === "ArrowDown") return "next";
|
|
||||||
if (!event.shiftKey && event.altKey && event.key.toLowerCase() === "r") return "commands";
|
|
||||||
if (!event.shiftKey && !event.altKey && event.key.toLowerCase() === "g") return "directories";
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
@@ -1,11 +0,0 @@
|
|||||||
{
|
|
||||||
"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"
|
|
||||||
}
|
|
||||||
Generated
-16
@@ -77,12 +77,6 @@ importers:
|
|||||||
'@tiptap/starter-kit':
|
'@tiptap/starter-kit':
|
||||||
specifier: ^3.31.3
|
specifier: ^3.31.3
|
||||||
version: 3.31.3
|
version: 3.31.3
|
||||||
'@xterm/addon-fit':
|
|
||||||
specifier: ^0.11.0
|
|
||||||
version: 0.11.0
|
|
||||||
'@xterm/xterm':
|
|
||||||
specifier: ^6.0.0
|
|
||||||
version: 6.0.0
|
|
||||||
markdown-it:
|
markdown-it:
|
||||||
specifier: ^15.0.2
|
specifier: ^15.0.2
|
||||||
version: 15.0.2
|
version: 15.0.2
|
||||||
@@ -742,12 +736,6 @@ packages:
|
|||||||
'@upsetjs/[email protected]':
|
'@upsetjs/[email protected]':
|
||||||
resolution: {integrity: sha512-WbBhLrooyePuQ1VZxrJjtLvTc4NVfpOyKx0sKqioq9bX1C1m7Jgykkn8gLrtwumBioXIqam8DLxp88Adbue6Hw==}
|
resolution: {integrity: sha512-WbBhLrooyePuQ1VZxrJjtLvTc4NVfpOyKx0sKqioq9bX1C1m7Jgykkn8gLrtwumBioXIqam8DLxp88Adbue6Hw==}
|
||||||
|
|
||||||
'@xterm/[email protected]':
|
|
||||||
resolution: {integrity: sha512-jYcgT6xtVYhnhgxh3QgYDnnNMYTcf8ElbxxFzX0IZo+vabQqSPAjC3c1wJrKB5E19VwQei89QCiZZP86DCPF7g==}
|
|
||||||
|
|
||||||
'@xterm/[email protected]':
|
|
||||||
resolution: {integrity: sha512-TQwDdQGtwwDt+2cgKDLn0IRaSxYu1tSUjgKarSDkUM0ZNiSRXFpjxEsvc/Zgc5kq5omJ+V0a8/kIM2WD3sMOYg==}
|
|
||||||
|
|
||||||
[email protected]:
|
[email protected]:
|
||||||
resolution: {integrity: sha512-lGq+9yr1/GuAWaVYIHRjvvySG5/4VfKIvC8EWxStPdcDh/Ka7FG3twP6v4d5BkravUilhIAsG4Qj83t02LWUPQ==}
|
resolution: {integrity: sha512-lGq+9yr1/GuAWaVYIHRjvvySG5/4VfKIvC8EWxStPdcDh/Ka7FG3twP6v4d5BkravUilhIAsG4Qj83t02LWUPQ==}
|
||||||
engines: {node: '>=0.4.0'}
|
engines: {node: '>=0.4.0'}
|
||||||
@@ -2037,10 +2025,6 @@ snapshots:
|
|||||||
d3-selection: 3.0.0
|
d3-selection: 3.0.0
|
||||||
d3-transition: 3.0.1([email protected])
|
d3-transition: 3.0.1([email protected])
|
||||||
|
|
||||||
'@xterm/[email protected]': {}
|
|
||||||
|
|
||||||
'@xterm/[email protected]': {}
|
|
||||||
|
|
||||||
[email protected]: {}
|
[email protected]: {}
|
||||||
|
|
||||||
[email protected]: {}
|
[email protected]: {}
|
||||||
|
|||||||
+15
-19
@@ -1,23 +1,19 @@
|
|||||||
import { build } from "vite";
|
import { mkdir, cp, access } from "node:fs/promises";
|
||||||
import { svelte } from "@sveltejs/vite-plugin-svelte";
|
import { execFileSync } from "node:child_process";
|
||||||
import { copyFile, mkdir } from "node:fs/promises";
|
import { resolve } from "node:path";
|
||||||
import { fileURLToPath } from "node:url";
|
import { fileURLToPath } from "node:url";
|
||||||
|
import { packagePlugin } from "./packagePlugin.mjs";
|
||||||
|
|
||||||
const root = fileURLToPath(new URL("../", import.meta.url));
|
const root = fileURLToPath(new URL("../", import.meta.url));
|
||||||
for (const name of ["terminal", "table-formulas"]) {
|
const formulasRoot = resolve(process.env.RUNESTONE_TABLE_FORMULAS_ROOT || resolve(root, "../RuneStone_TableFormulas"));
|
||||||
const source = new URL(`../plugins/${name}/`, import.meta.url);
|
const formulasBuild = resolve(formulasRoot, "scripts/build.mjs");
|
||||||
const output = new URL(`../plugin-packages/${name}/`, import.meta.url);
|
try {
|
||||||
await build({
|
await access(formulasBuild);
|
||||||
configFile: false,
|
} catch {
|
||||||
root,
|
throw new Error("Clone RuneStone_TableFormulas beside RuneStone, or set RUNESTONE_TABLE_FORMULAS_ROOT. Install its dependencies before building plugins.");
|
||||||
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));
|
|
||||||
}
|
}
|
||||||
|
execFileSync(process.execPath, [formulasBuild], { cwd: formulasRoot, stdio: "inherit" });
|
||||||
|
const formulasOutput = resolve(root, "plugin-packages/table-formulas");
|
||||||
|
await mkdir(formulasOutput, { recursive: true });
|
||||||
|
await cp(resolve(formulasRoot, "dist/plugin"), formulasOutput, { recursive: true });
|
||||||
|
console.log(await packagePlugin(formulasOutput, resolve(root, "plugin-packages")));
|
||||||
|
|||||||
@@ -75,9 +75,8 @@ 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.getByRole("tab", { selected: true }).click({ button: "right" });
|
||||||
await page.getByRole("button", { name: "Switch to IDE layout (Ctrl E)", exact: true }).click();
|
await page.getByRole("menuitem", { name: "Source mode", exact: true }).click();
|
||||||
}
|
|
||||||
await page.locator(".monaco-editor textarea").waitFor();
|
await page.locator(".monaco-editor textarea").waitFor();
|
||||||
}
|
}
|
||||||
async function contents() {
|
async function contents() {
|
||||||
@@ -112,7 +111,8 @@ try {
|
|||||||
await menu.getByRole("menuitem", { name: "Bold", exact: true }).click();
|
await menu.getByRole("menuitem", { name: "Bold", exact: true }).click();
|
||||||
await waitForText("**First** paragraph.\n\nSecond paragraph.\n");
|
await waitForText("**First** paragraph.\n\nSecond paragraph.\n");
|
||||||
await page.keyboard.press("Control+z"); await waitForText(source);
|
await page.keyboard.press("Control+z"); await waitForText(source);
|
||||||
await page.getByRole("button", { name: "Switch to writing layout (Ctrl E)", exact: true }).click();
|
await page.getByRole("tab", { selected: true }).click({ button: "right" });
|
||||||
|
await page.getByRole("menuitem", { name: "Writing mode", exact: true }).click();
|
||||||
const writer = page.getByRole("textbox", { name: "Writing editor", exact: true });
|
const writer = page.getByRole("textbox", { name: "Writing editor", exact: true });
|
||||||
await writer.click(); await page.keyboard.press("Control+Home");
|
await writer.click(); await page.keyboard.press("Control+Home");
|
||||||
await page.keyboard.press("Control+Shift+ArrowRight");
|
await page.keyboard.press("Control+Shift+ArrowRight");
|
||||||
|
|||||||
@@ -0,0 +1,140 @@
|
|||||||
|
import { createRequire } from "node:module";
|
||||||
|
import assert from "node:assert/strict";
|
||||||
|
import { mkdir } from "node:fs/promises";
|
||||||
|
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 page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
|
||||||
|
page.setDefaultTimeout(15000);
|
||||||
|
const errors = [];
|
||||||
|
page.on("pageerror", error => errors.push(error.message));
|
||||||
|
await mkdir(".audit", { recursive: true });
|
||||||
|
await page.addInitScript(() => {
|
||||||
|
window.isTauri = true;
|
||||||
|
const root = "C:\\tab-menu-workspace";
|
||||||
|
const files = new Map(["a.md", "b.md", "c.md", "d.md"].map(name => [name, `# ${name}\n\nOriginal text.\n\n| Name | Value |\n| --- | --- |\n| Alpha | One |\n`]));
|
||||||
|
window.tabMenuTest = { prompts: [], answer: "Cancel", revealed: null, clipboard: null };
|
||||||
|
Object.defineProperty(navigator, "clipboard", { value: { writeText: async text => { window.tabMenuTest.clipboard = text; } } });
|
||||||
|
let sequence = 0;
|
||||||
|
window.__TAURI_INTERNALS__ = {
|
||||||
|
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
|
||||||
|
transformCallback: () => ++sequence, unregisterCallback: () => {},
|
||||||
|
invoke: async (command, args = {}) => {
|
||||||
|
if (command === "plugin:event|listen") return ++sequence;
|
||||||
|
if (command === "plugin:event|unlisten") return;
|
||||||
|
if (command === "workspace_last_path") return root;
|
||||||
|
if (command === "workspace_open") return { root, name: "tab-menu-workspace", watch_mode: "native" };
|
||||||
|
if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("missing"); return files.get(args.rel); }
|
||||||
|
if (command === "workspace_list") return args.rel ? [] : [{ name: "notes", rel_path: "notes", kind: "folder" }, ...[...files.keys()].map(name => ({ name, rel_path: name, kind: "file" }))];
|
||||||
|
if (command === "workspace_search") return [];
|
||||||
|
if (command === "workspace_write") throw new Error("Keep unsaved edits for the close test");
|
||||||
|
if (command === "workspace_rename") { files.set(args.to, files.get(args.from)); files.delete(args.from); return; }
|
||||||
|
if (command === "workspace_abs_path") return `${root}\\${args.rel}`;
|
||||||
|
if (command === "workspace_reveal") { window.tabMenuTest.revealed = args.rel; return; }
|
||||||
|
if (command === "plugin:dialog|message") { window.tabMenuTest.prompts.push(args.message); return window.tabMenuTest.answer; }
|
||||||
|
throw new Error(`Unhandled IPC: ${command}`);
|
||||||
|
},
|
||||||
|
};
|
||||||
|
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} };
|
||||||
|
});
|
||||||
|
|
||||||
|
const menu = name => page.getByRole("menu", { name, exact: true });
|
||||||
|
const item = name => page.getByRole("menuitem", { name, exact: true });
|
||||||
|
async function metrics(panel) {
|
||||||
|
return panel.evaluate(node => {
|
||||||
|
const row = node.querySelector(":scope > button");
|
||||||
|
const icon = row.querySelector(".action-icon");
|
||||||
|
const label = row.querySelector(".action-label");
|
||||||
|
const css = getComputedStyle(node), button = getComputedStyle(row);
|
||||||
|
return {
|
||||||
|
panel: [css.padding, css.borderRadius, css.backgroundColor, css.color, css.boxShadow, css.font],
|
||||||
|
row: [button.padding, button.minHeight, button.borderRadius, button.gap, button.font],
|
||||||
|
iconWidth: icon.getBoundingClientRect().width,
|
||||||
|
inset: Math.round(row.getBoundingClientRect().left - node.getBoundingClientRect().left),
|
||||||
|
labelOffset: Math.round(label.getBoundingClientRect().left - row.getBoundingClientRect().left),
|
||||||
|
};
|
||||||
|
});
|
||||||
|
}
|
||||||
|
async function dismiss() { await page.keyboard.press("Escape"); await page.locator(".rs-menu").waitFor({ state: "detached" }); }
|
||||||
|
try {
|
||||||
|
await page.goto(process.env.SMOKE_URL || "http://127.0.0.1:1420");
|
||||||
|
const row = page.locator('[data-tree-rel="a.md"]');
|
||||||
|
await row.waitFor();
|
||||||
|
await row.click();
|
||||||
|
const tab = page.getByRole("tab", { name: "a.md", exact: true });
|
||||||
|
await tab.waitFor();
|
||||||
|
await page.locator(".cm-content").waitFor();
|
||||||
|
for (const theme of ["dark", "light"]) {
|
||||||
|
await page.evaluate(theme => document.documentElement.dataset.theme = theme, theme);
|
||||||
|
await row.focus();
|
||||||
|
await row.click({ button: "right" });
|
||||||
|
const file = menu("File actions");
|
||||||
|
await file.waitFor();
|
||||||
|
const reference = await metrics(file);
|
||||||
|
assert.ok(reference.inset >= 5, "Rows need an inset from the panel border");
|
||||||
|
assert.equal(await item("Pin").locator("svg.action-icon").count(), 1);
|
||||||
|
const offsets = await file.locator(":scope > button").evaluateAll(nodes => nodes.map(node => Math.round(node.querySelector(".action-label").getBoundingClientRect().left - node.getBoundingClientRect().left)));
|
||||||
|
assert.equal(new Set(offsets).size, 1, "All file labels align");
|
||||||
|
await page.screenshot({ path: ".audit/menu-file-" + theme + ".png" });
|
||||||
|
await dismiss();
|
||||||
|
assert.equal(await row.evaluate(node => node === document.activeElement), true);
|
||||||
|
await page.getByRole("navigation", { name: "Workspace files" }).click({ button: "right", position: { x: 100, y: 350 } });
|
||||||
|
await file.waitFor();
|
||||||
|
assert.deepEqual(await metrics(file), reference, "Pane and file menus share styles");
|
||||||
|
await dismiss();
|
||||||
|
await page.locator('[data-tree-rel="notes"]').click({ button: "right" });
|
||||||
|
assert.deepEqual(await metrics(file), reference, "Folder and file menus share styles");
|
||||||
|
await dismiss();
|
||||||
|
await tab.click({ button: "right" });
|
||||||
|
const tabs = menu("Tab actions");
|
||||||
|
assert.deepEqual(await metrics(tabs), reference, "Tab and file menus share styles");
|
||||||
|
await item("Close tabs after").hover();
|
||||||
|
assert.equal(await item("Close tabs after").evaluate(node => getComputedStyle(node).backgroundColor), "rgba(0, 0, 0, 0)");
|
||||||
|
await item("Move tab").focus();
|
||||||
|
await page.keyboard.press("ArrowRight");
|
||||||
|
assert.deepEqual(await metrics(menu("Move tab")), reference, "Submenus share styles");
|
||||||
|
await page.screenshot({ path: ".audit/menu-tab-" + theme + ".png" });
|
||||||
|
await page.keyboard.press("ArrowLeft");
|
||||||
|
assert.equal(await item("Move tab").evaluate(node => node === document.activeElement), true);
|
||||||
|
await dismiss();
|
||||||
|
await page.getByText("Original text.", { exact: true }).click({ button: "right" });
|
||||||
|
const editor = menu("Markdown text actions");
|
||||||
|
assert.deepEqual(await metrics(editor), reference, "Editor and file menus share styles");
|
||||||
|
await item("Paragraph").focus();
|
||||||
|
await page.keyboard.press("ArrowRight");
|
||||||
|
assert.deepEqual(await metrics(menu("Paragraph")), reference);
|
||||||
|
await page.screenshot({ path: ".audit/menu-editor-" + theme + ".png" });
|
||||||
|
await dismiss();
|
||||||
|
await page.locator(".live-writer td").first().click({ button: "right" });
|
||||||
|
assert.deepEqual(await metrics(menu("Table actions")), reference, "Table and file menus share styles");
|
||||||
|
await dismiss();
|
||||||
|
}
|
||||||
|
await page.setViewportSize({ width: 420, height: 320 });
|
||||||
|
await page.evaluate(async () => {
|
||||||
|
const { actionMenu } = await import("/src/lib/ui/actionMenu.ts");
|
||||||
|
const root = actionMenu(418, 318, [
|
||||||
|
{ label: "Without icon", run: () => {} },
|
||||||
|
{ label: "With icon", icon: "copy", run: () => {} },
|
||||||
|
{ label: "Unavailable", icon: "trash", disabled: true },
|
||||||
|
{ label: "More", icon: "plus", children: Array.from({ length: 30 }, (_, i) => ({ label: "Action " + i, icon: "copy" })) },
|
||||||
|
], () => root.remove(), "Edge test");
|
||||||
|
});
|
||||||
|
const edge = menu("Edge test");
|
||||||
|
const offsets = await edge.locator(":scope > button").evaluateAll(nodes => nodes.map(node => node.querySelector(".action-label").getBoundingClientRect().left));
|
||||||
|
assert.equal(new Set(offsets).size, 1, "Iconless labels keep the icon column");
|
||||||
|
await page.keyboard.press("ArrowDown");
|
||||||
|
await page.keyboard.press("ArrowDown");
|
||||||
|
assert.equal(await item("More").evaluate(node => node === document.activeElement), true, "Keyboard skips disabled rows");
|
||||||
|
await page.keyboard.press("ArrowRight");
|
||||||
|
const sub = menu("More");
|
||||||
|
for (const panel of [edge, sub]) {
|
||||||
|
const bounds = await panel.boundingBox();
|
||||||
|
assert.ok(bounds.x >= 8 && bounds.y >= 8 && bounds.x + bounds.width <= 412 && bounds.y + bounds.height <= 312);
|
||||||
|
}
|
||||||
|
await page.keyboard.press("End");
|
||||||
|
assert.equal(await item("Action 29").evaluate(node => node === document.activeElement), true);
|
||||||
|
await page.screenshot({ path: ".audit/menu-edge.png" });
|
||||||
|
await dismiss();
|
||||||
|
assert.deepEqual(errors, []);
|
||||||
|
console.log("PASS: menu styles, dark/light themes, icons, disabled rows, focus return, submenus, scrolling, and viewport edges");
|
||||||
|
} finally { await browser.close(); }
|
||||||
@@ -0,0 +1,120 @@
|
|||||||
|
import { lstat, readdir, readFile, mkdir, writeFile, realpath, rename, unlink } from "node:fs/promises";
|
||||||
|
import { randomUUID } from "node:crypto";
|
||||||
|
import { resolve, relative, isAbsolute, join } from "node:path";
|
||||||
|
import { pathToFileURL } from "node:url";
|
||||||
|
import { crc32, deflateRawSync } from "node:zlib";
|
||||||
|
|
||||||
|
const MiB = 1024 * 1024;
|
||||||
|
const device = /^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])$/i;
|
||||||
|
function validPath(name) {
|
||||||
|
return name.length <= 180 && name.split("/").every(part =>
|
||||||
|
part.length > 0 && part.length <= 120 && /^[a-zA-Z0-9._-]+$/.test(part)
|
||||||
|
&& !part.endsWith(".") && !device.test(part.split(".")[0]));
|
||||||
|
}
|
||||||
|
function requireValue(condition, message) {
|
||||||
|
if (!condition) throw new Error(message);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ZIP32 with DEFLATE, fixed timestamps, and sorted paths gives repeatable release files.
|
||||||
|
function zip(files) {
|
||||||
|
const local = [], central = [];
|
||||||
|
let offset = 0, centralSize = 0;
|
||||||
|
for (const [path, bytes] of files) {
|
||||||
|
const name = Buffer.from(path);
|
||||||
|
const compressed = deflateRawSync(bytes, { level: 9 });
|
||||||
|
const header = Buffer.alloc(30);
|
||||||
|
header.writeUInt32LE(0x04034b50, 0);
|
||||||
|
header.writeUInt16LE(20, 4);
|
||||||
|
header.writeUInt16LE(8, 8);
|
||||||
|
header.writeUInt16LE(33, 12); // January 1, 1980.
|
||||||
|
header.writeUInt32LE(crc32(bytes), 14);
|
||||||
|
header.writeUInt32LE(compressed.length, 18);
|
||||||
|
header.writeUInt32LE(bytes.length, 22);
|
||||||
|
header.writeUInt16LE(name.length, 26);
|
||||||
|
local.push(header, name, compressed);
|
||||||
|
const record = Buffer.alloc(46);
|
||||||
|
record.writeUInt32LE(0x02014b50, 0);
|
||||||
|
record.writeUInt16LE(20, 4);
|
||||||
|
header.copy(record, 6, 4, 30);
|
||||||
|
record.writeUInt32LE(offset, 42);
|
||||||
|
central.push(record, name);
|
||||||
|
offset += header.length + name.length + compressed.length;
|
||||||
|
centralSize += record.length + name.length;
|
||||||
|
}
|
||||||
|
const end = Buffer.alloc(22);
|
||||||
|
end.writeUInt32LE(0x06054b50, 0);
|
||||||
|
end.writeUInt16LE(files.length, 8);
|
||||||
|
end.writeUInt16LE(files.length, 10);
|
||||||
|
end.writeUInt32LE(centralSize, 12);
|
||||||
|
end.writeUInt32LE(offset, 16);
|
||||||
|
return Buffer.concat([...local, ...central, end]);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function packagePlugin(source, destination = "plugin-packages") {
|
||||||
|
const input = resolve(source);
|
||||||
|
const output = resolve(destination);
|
||||||
|
const inputMeta = await lstat(input);
|
||||||
|
requireValue(inputMeta.isDirectory() && !inputMeta.isSymbolicLink(), "Select a compiled plugin folder.");
|
||||||
|
const files = [], names = new Set();
|
||||||
|
let total = 0, count = 0;
|
||||||
|
async function walk(directory, prefix = "") {
|
||||||
|
for (const entry of (await readdir(directory)).sort()) {
|
||||||
|
const name = prefix + entry;
|
||||||
|
requireValue(validPath(name), `Invalid package path: ${name}`);
|
||||||
|
requireValue(!names.has(name.toLowerCase()), `Duplicate package path: ${name}`);
|
||||||
|
names.add(name.toLowerCase());
|
||||||
|
requireValue(++count <= 5000, "The package exceeds 5,000 entries.");
|
||||||
|
const path = join(directory, entry), meta = await lstat(path);
|
||||||
|
requireValue(!meta.isSymbolicLink(), `Remove the link from the package: ${name}`);
|
||||||
|
if (meta.isDirectory()) await walk(path, name + "/");
|
||||||
|
else {
|
||||||
|
requireValue(meta.isFile() && meta.size <= 25 * MiB, `Invalid or oversized package file: ${name}`);
|
||||||
|
const bytes = await readFile(path);
|
||||||
|
requireValue(bytes.length <= 25 * MiB, `The file exceeds 25 MiB: ${name}`);
|
||||||
|
total += bytes.length;
|
||||||
|
requireValue(total <= 100 * MiB, "The package exceeds 100 MiB of expanded data.");
|
||||||
|
files.push([name, bytes]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
await walk(input);
|
||||||
|
const manifestBytes = files.find(([name]) => name === "plugin.json")?.[1];
|
||||||
|
requireValue(manifestBytes && manifestBytes.length <= 64 * 1024, "The package needs plugin.json at its root, within 64 KiB.");
|
||||||
|
const manifest = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(manifestBytes));
|
||||||
|
requireValue(typeof manifest.id === "string" && validPath(manifest.id) && /^[a-z][a-z0-9.-]*$/.test(manifest.id), "The plugin ID is invalid.");
|
||||||
|
requireValue(manifest.schemaVersion === 1 && manifest.apiVersion === 1 && manifest.access === "full-app", "Unsupported schema, API version, or access mode.");
|
||||||
|
for (const key of ["name", "author", "description", "version"]) {
|
||||||
|
requireValue(typeof manifest[key] === "string" && manifest[key].trim() && Buffer.byteLength(manifest[key]) <= 1000, `The manifest needs a valid ${key}.`);
|
||||||
|
}
|
||||||
|
requireValue(/^\d+\.\d+\.\d+$/.test(manifest.version), "Use a plugin version such as 1.0.0.");
|
||||||
|
requireValue(typeof manifest.entry === "string" && validPath(manifest.entry) && /\.m?js$/.test(manifest.entry), "The entry must be a compiled JavaScript module.");
|
||||||
|
const entry = files.find(([name]) => name === manifest.entry)?.[1];
|
||||||
|
requireValue(entry, "The entry module is missing.");
|
||||||
|
new TextDecoder("utf-8", { fatal: true }).decode(entry);
|
||||||
|
const filename = `${manifest.id}-${manifest.version}.zip`;
|
||||||
|
requireValue(filename.length <= 240, "The release filename is too long.");
|
||||||
|
await mkdir(output, { recursive: true });
|
||||||
|
const target = join(await realpath(output), filename);
|
||||||
|
const within = relative(await realpath(input), target);
|
||||||
|
requireValue(isAbsolute(within) || within === ".." || within.startsWith("../") || within.startsWith("..\\"), "Choose an output folder outside the plugin folder.");
|
||||||
|
const archive = zip(files.sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0));
|
||||||
|
requireValue(archive.length <= 100 * MiB, "The archive exceeds 100 MiB.");
|
||||||
|
const temporary = `${target}.${randomUUID()}.tmp`;
|
||||||
|
try {
|
||||||
|
await writeFile(temporary, archive, { flag: "wx" });
|
||||||
|
await rename(temporary, target);
|
||||||
|
} finally {
|
||||||
|
await unlink(temporary).catch(error => { if (error.code !== "ENOENT") throw error; });
|
||||||
|
}
|
||||||
|
return target;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) {
|
||||||
|
try {
|
||||||
|
requireValue(process.argv[2] && process.argv.length <= 4, "Usage: node scripts/packagePlugin.mjs <compiled-folder> [output-folder]");
|
||||||
|
console.log(await packagePlugin(process.argv[2], process.argv[3]));
|
||||||
|
} catch (error) {
|
||||||
|
console.error(error.message);
|
||||||
|
process.exitCode = 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,96 @@
|
|||||||
|
import test from "node:test";
|
||||||
|
import assert from "node:assert/strict";
|
||||||
|
import { ExternalSession } from "../src/lib/plugins/externalSession.ts";
|
||||||
|
import type { PluginApi, PluginDocumentType } 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() },
|
||||||
|
};
|
||||||
|
const type: PluginDocumentType = {
|
||||||
|
id: "board", title: "Board", icon: "kanban", extensions: ["md"],
|
||||||
|
identify: (_path, source) => source === "board" ? { id: "stable" } : null,
|
||||||
|
create: { label: "New board", defaultName: "Untitled board", extension: "md", contents: () => "board" },
|
||||||
|
mount: () => {},
|
||||||
|
};
|
||||||
|
|
||||||
|
test("document renames pass the stable identity and stop after shutdown", async () => {
|
||||||
|
let api!: PluginApi;
|
||||||
|
const calls: unknown[] = [];
|
||||||
|
const session = new ExternalSession("fixture", services, () => {}, () => {}, undefined, undefined,
|
||||||
|
async (document, name) => { calls.push({ document, name }); return "Renamed.md"; });
|
||||||
|
await session.start({ activate(value) { api = value; } });
|
||||||
|
assert.equal(await api.renameDocument!({ id: "stable", path: "Board.md" }, "Renamed"), "Renamed.md");
|
||||||
|
assert.deepEqual(calls, [{ document: { id: "stable", path: "Board.md" }, name: "Renamed" }]);
|
||||||
|
await session.stop();
|
||||||
|
assert.throws(() => api.renameDocument!({ id: "stable", path: "Board.md" }, "Other"), /disabled/);
|
||||||
|
assert.equal(calls.length, 1);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("binary document registration preserves bytes and revokes reads on shutdown", async () => {
|
||||||
|
let api!: PluginApi;
|
||||||
|
const bytes = new Uint8Array([0x25, 0x50, 0x44, 0x46, 0xff, 0x00]);
|
||||||
|
const paths: string[] = [];
|
||||||
|
const session = new ExternalSession("fixture", {
|
||||||
|
...services, workspace: { ...services.workspace, readBytes: async path => { paths.push(path); return bytes; } },
|
||||||
|
}, () => {}, () => {});
|
||||||
|
await session.start({ activate(value) {
|
||||||
|
api = value;
|
||||||
|
api.registerDocumentType({ ...type, id: "pdf", extensions: ["pdf"], content: "binary", create: undefined });
|
||||||
|
} });
|
||||||
|
assert.equal(session.documentTypes.get("pdf")?.content, "binary");
|
||||||
|
assert.deepEqual(await api.workspace.readBytes!("report.pdf"), bytes);
|
||||||
|
assert.deepEqual(paths, ["report.pdf"]);
|
||||||
|
assert.throws(() => api.registerDocumentType({ ...type, content: "invalid" as "binary" }), /content type/);
|
||||||
|
await session.stop();
|
||||||
|
assert.throws(() => api.workspace.readBytes!("report.pdf"), /disabled/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("document types have independent registrations and reject invalid creation actions", async () => {
|
||||||
|
let api!: PluginApi;
|
||||||
|
const session = new ExternalSession("fixture", services, () => {}, () => {});
|
||||||
|
await session.start({ activate(value) { api = value; api.registerDocumentType(type); } });
|
||||||
|
assert.equal(session.documentTypes.get("board")?.identify("Board.md", "board")?.id, "stable");
|
||||||
|
assert.equal(session.documentTypes.get("board")?.identify("Note.md", "plain"), null);
|
||||||
|
assert.throws(() => api.registerDocumentType(type), /duplicate/);
|
||||||
|
assert.throws(() => api.registerDocumentType({ ...type, id: "other", create: { ...type.create!, extension: "exe" } }), /Invalid document creation/);
|
||||||
|
await session.stop();
|
||||||
|
assert.equal(session.documentTypes.size, 0);
|
||||||
|
assert.throws(() => api.registerDocumentType(type), /disabled/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("two document mounts retain independent context and clean up once", async () => {
|
||||||
|
const mounted: string[] = [], cleaned: string[] = [];
|
||||||
|
const session = new ExternalSession("fixture", services, () => {}, () => {});
|
||||||
|
await session.start({ activate(api) {
|
||||||
|
api.registerDocumentType({ ...type, mount(_node, context) { mounted.push(context.path); return () => { cleaned.push(context.id); }; } });
|
||||||
|
} });
|
||||||
|
const element = () => ({ replaceChildren() {} }) as unknown as HTMLElement;
|
||||||
|
const first = await session.mount("board", element(), { id: "first", path: "One.md" });
|
||||||
|
await session.mount("board", element(), { id: "second", path: "Two.md" });
|
||||||
|
assert.deepEqual(mounted, ["One.md", "Two.md"]);
|
||||||
|
await first(); await first();
|
||||||
|
assert.deepEqual(cleaned, ["first"]);
|
||||||
|
await session.stop();
|
||||||
|
assert.deepEqual(cleaned, ["first", "second"]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("document opening and workspace subscriptions stop with their plugin", async () => {
|
||||||
|
let api!: PluginApi;
|
||||||
|
let listener: (() => void) | undefined;
|
||||||
|
let notifications = 0, removed = 0;
|
||||||
|
const opened: string[] = [];
|
||||||
|
const session = new ExternalSession("fixture", {
|
||||||
|
...services,
|
||||||
|
workspace: { ...services.workspace, subscribe(callback) { listener = callback; return () => { removed++; }; } },
|
||||||
|
}, () => {}, () => {}, undefined, async path => { opened.push(path); });
|
||||||
|
await session.start({ activate(value) { api = value; api.workspace.subscribe!(() => { notifications++; }); } });
|
||||||
|
await api.openDocument("Board.md"); listener!();
|
||||||
|
assert.deepEqual(opened, ["Board.md"]);
|
||||||
|
assert.equal(notifications, 1);
|
||||||
|
await session.stop(); listener!();
|
||||||
|
assert.equal(notifications, 1);
|
||||||
|
assert.equal(removed, 1);
|
||||||
|
assert.throws(() => api.openDocument("Board.md"), /disabled/);
|
||||||
|
});
|
||||||
@@ -5,7 +5,7 @@ import { readFileSync } from "node:fs";
|
|||||||
const require = createRequire(import.meta.url);
|
const require = createRequire(import.meta.url);
|
||||||
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright");
|
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 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 context = await browser.newContext({ viewport: { width: 1440, height: 1000 }, locale: 'en-US', timezoneId: 'America/Vancouver' });
|
||||||
const page = await context.newPage();
|
const page = await context.newPage();
|
||||||
page.setDefaultTimeout(10000);
|
page.setDefaultTimeout(10000);
|
||||||
const errors = [];
|
const errors = [];
|
||||||
@@ -42,10 +42,14 @@ await page.context().addInitScript(({ manifest, pluginCode }) => {
|
|||||||
if (command === "plugin:window|is_maximized") return false;
|
if (command === "plugin:window|is_maximized") return false;
|
||||||
if (command.startsWith("plugin:window|")) return null;
|
if (command.startsWith("plugin:window|")) return null;
|
||||||
if (command === "plugins_snapshot") return snapshot();
|
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_choose") return [{ token: 'candidate', source: 'C:/Downloads/overview.zip', manifest, error: null }];
|
||||||
|
if (command === "plugins_from_git") {
|
||||||
|
if (args.tag === 'missing') throw new Error('Release not found. Publish a release with one plugin ZIP.');
|
||||||
|
return [{ token: 'git-candidate', source: args.url + ' @ ' + (args.tag || 'v1.0.0'), manifest, error: null }];
|
||||||
|
}
|
||||||
if (command === "plugins_cancel") { removalPrepared = false; return; }
|
if (command === "plugins_cancel") { removalPrepared = false; return; }
|
||||||
if (command === "plugins_install") {
|
if (command === "plugins_install") {
|
||||||
installed = [{ manifest, hash: 'reviewed-hash', enabled: args.enabled, path, error: null, removal: false }];
|
installed = [{ manifest, hash: 'reviewed-hash', enabled: args.enabled, installedAt: Date.parse('2026-10-05T18:24:36Z'), path, error: null, removal: false }];
|
||||||
emit('plugins-changed', null); return [{ name: manifest.name, error: null }];
|
emit('plugins-changed', null); return [{ name: manifest.name, error: null }];
|
||||||
}
|
}
|
||||||
if (command === "plugins_set_enabled") {
|
if (command === "plugins_set_enabled") {
|
||||||
@@ -119,19 +123,39 @@ async function settings() {
|
|||||||
await page.getByRole('button', { name: 'Settings (Ctrl+,)', exact: true }).click();
|
await page.getByRole('button', { name: 'Settings (Ctrl+,)', exact: true }).click();
|
||||||
await settingsDialog.getByRole('button', { name: 'Plug-ins', 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(); }
|
async function uninstall() { await settingsDialog.locator('.card').filter({ hasText: 'Workspace overview' }).getByRole('button', { name: 'Uninstall', exact: true }).click(); }
|
||||||
try {
|
try {
|
||||||
await page.goto(process.env.SMOKE_URL || 'http://127.0.0.1:1420');
|
await page.goto(process.env.SMOKE_URL || 'http://127.0.0.1:1420');
|
||||||
await page.getByText('smoke-workspace', { exact: true }).waitFor();
|
await page.getByText('smoke-workspace', { exact: true }).waitFor();
|
||||||
await settings();
|
await settings();
|
||||||
await settingsDialog.getByRole('button', { name: 'Install from file', exact: true }).click();
|
assert.equal(await settingsDialog.getByRole('button', { name: 'Install from folder', exact: true }).count(), 0);
|
||||||
|
assert.equal(await settingsDialog.getByRole('button', { name: 'Install from file', exact: true }).count(), 0);
|
||||||
|
await settingsDialog.getByRole('button', { name: 'Install plugin ZIP', exact: true }).click();
|
||||||
let review = page.getByRole('dialog', { name: 'Review plugin installation', exact: true });
|
let review = page.getByRole('dialog', { name: 'Review plugin installation', exact: true });
|
||||||
|
await review.getByText('Source: C:/Downloads/overview.zip', { exact: true }).waitFor();
|
||||||
await review.getByRole('button', { name: 'Cancel', exact: true }).click();
|
await review.getByRole('button', { name: 'Cancel', exact: true }).click();
|
||||||
assert.equal(await count('plugins_install'), 0);
|
assert.equal(await count('plugins_install'), 0);
|
||||||
await settingsDialog.getByRole('button', { name: 'Install from folder', exact: true }).click();
|
const gitButton = settingsDialog.getByRole('button', { name: 'Install from Git link', exact: true });
|
||||||
|
await gitButton.click();
|
||||||
|
const gitDialog = page.getByRole('dialog', { name: 'Install from Git link', exact: true });
|
||||||
|
await gitDialog.getByLabel('Repository link', { exact: true }).fill('https://git.example/owner/plugin.git');
|
||||||
|
await gitDialog.getByLabel('Release tag (optional)', { exact: true }).fill('missing');
|
||||||
|
await gitDialog.getByLabel('Access token (optional)', { exact: true }).fill('test-token');
|
||||||
|
await gitDialog.getByRole('button', { name: 'Review release', exact: true }).click();
|
||||||
|
await gitDialog.getByRole('alert').getByText(/Release not found/).waitFor();
|
||||||
|
assert.equal(await gitDialog.getByLabel('Access token (optional)', { exact: true }).inputValue(), '');
|
||||||
|
await gitDialog.getByLabel('Release tag (optional)', { exact: true }).fill('v1.0.0');
|
||||||
|
await gitDialog.getByRole('button', { name: 'Review release', exact: true }).click();
|
||||||
|
await review.getByText('Source: https://git.example/owner/plugin.git @ v1.0.0', { exact: true }).waitFor();
|
||||||
|
await review.getByRole('button', { name: 'Cancel', exact: true }).click();
|
||||||
|
assert.equal(await count('plugins_install'), 0);
|
||||||
|
assert(await gitButton.evaluate(element => element === document.activeElement));
|
||||||
|
await settingsDialog.getByRole('button', { name: 'Install plugin ZIP', exact: true }).click();
|
||||||
await review.getByRole('button', { name: 'Install and enable', exact: true }).click();
|
await review.getByRole('button', { name: 'Install and enable', exact: true }).click();
|
||||||
await settingsDialog.getByRole('switch', { name: 'Workspace overview', exact: true }).waitFor();
|
await settingsDialog.getByRole('switch', { name: 'Workspace overview', exact: true }).waitFor();
|
||||||
assert(await settingsDialog.getByRole('switch', { name: 'Workspace overview', exact: true }).isChecked());
|
assert(await settingsDialog.getByRole('switch', { name: 'Workspace overview', exact: true }).isChecked());
|
||||||
|
assert.equal(await settingsDialog.locator('time').getAttribute('datetime'), '2026-10-05T18:24:36.000Z');
|
||||||
|
assert.match(await settingsDialog.locator('time').innerText(), /Oct 5, 2026.*11:24:36 AM PDT/);
|
||||||
await page.screenshot({ path: '.audit/plugin-manager-installed.png' });
|
await page.screenshot({ path: '.audit/plugin-manager-installed.png' });
|
||||||
await page.keyboard.press('Escape');
|
await page.keyboard.press('Escape');
|
||||||
await page.getByRole('button', { name: 'Plugin commands and views', exact: true }).click();
|
await page.getByRole('button', { name: 'Plugin commands and views', exact: true }).click();
|
||||||
@@ -167,6 +191,15 @@ try {
|
|||||||
await settings();
|
await settings();
|
||||||
await page.screenshot({ path: '.audit/plugin-manager-narrow.png' });
|
await page.screenshot({ path: '.audit/plugin-manager-narrow.png' });
|
||||||
assert.equal(await settingsDialog.evaluate(element => element.scrollWidth > element.clientWidth), false);
|
assert.equal(await settingsDialog.evaluate(element => element.scrollWidth > element.clientWidth), false);
|
||||||
|
await gitButton.click();
|
||||||
|
await gitDialog.getByLabel('Repository link', { exact: true }).fill('https://git.example/owner/plugin.git');
|
||||||
|
await page.screenshot({ path: '.audit/plugin-git-narrow.png' });
|
||||||
|
assert.equal(await gitDialog.evaluate(element => element.scrollWidth > element.clientWidth), false);
|
||||||
|
await gitDialog.getByRole('button', { name: 'Review release', exact: true }).click();
|
||||||
|
await review.getByRole('button', { name: 'Install', exact: true }).click();
|
||||||
|
await settingsDialog.getByRole('switch', { name: 'Workspace overview', exact: true }).waitFor();
|
||||||
|
assert.equal(await settingsDialog.getByRole('switch', { name: 'Workspace overview', exact: true }).isChecked(), false);
|
||||||
|
assert.equal(await count('plugins_from_git'), 3);
|
||||||
assert.deepEqual(errors, []);
|
assert.deepEqual(errors, []);
|
||||||
console.log('External plugin smoke passed: file/folder review, code loading, command/view, one confirmation, cancellation, focus, cleanup, and uninstall.');
|
console.log('External plugin smoke passed: ZIP and Git-link review, download errors, token clearing, disabled installation, code loading, cancellation, focus, cleanup, and uninstall.');
|
||||||
} finally { await browser.close(); }
|
} finally { await browser.close(); }
|
||||||
|
|||||||
@@ -1,9 +1,13 @@
|
|||||||
import { readFile } from "node:fs/promises";
|
import { readFile } from "node:fs/promises";
|
||||||
|
import { resolve } from "node:path";
|
||||||
|
import { pathToFileURL } from "node:url";
|
||||||
|
|
||||||
/** Load the actual compiled packages through the production Blob module loader. */
|
/** Load the actual compiled packages through the production Blob module loader. */
|
||||||
export async function mockFeaturePlugins(surface) {
|
export async function mockFeaturePlugins(surface) {
|
||||||
const packages = await Promise.all(["terminal", "table-formulas"].map(async name => {
|
const packages = await Promise.all(["terminal", "table-formulas"].map(async name => {
|
||||||
const root = new URL(`../plugin-packages/${name}/`, import.meta.url);
|
const root = name === "terminal"
|
||||||
|
? (process.env.RUNESTONE_TERMINAL_DIST ? pathToFileURL(resolve(process.env.RUNESTONE_TERMINAL_DIST) + "/") : new URL("../../RuneStone_Terminal/dist/", import.meta.url))
|
||||||
|
: new URL(`../plugin-packages/${name}/`, import.meta.url);
|
||||||
return {
|
return {
|
||||||
manifest: JSON.parse(await readFile(new URL("plugin.json", root), "utf8")),
|
manifest: JSON.parse(await readFile(new URL("plugin.json", root), "utf8")),
|
||||||
code: await readFile(new URL("main.js", root), "utf8"),
|
code: await readFile(new URL("main.js", root), "utf8"),
|
||||||
|
|||||||
@@ -0,0 +1,48 @@
|
|||||||
|
import { test } from "node:test";
|
||||||
|
import assert from "node:assert/strict";
|
||||||
|
import { mkdtemp, mkdir, readFile, writeFile, rm, realpath } from "node:fs/promises";
|
||||||
|
import { tmpdir } from "node:os";
|
||||||
|
import { join } from "node:path";
|
||||||
|
// @ts-ignore The build tool is a JavaScript module.
|
||||||
|
import { packagePlugin } from "./packagePlugin.mjs";
|
||||||
|
|
||||||
|
test("plugin packaging rejects invalid release inputs before writing an archive", async () => {
|
||||||
|
const root = await mkdtemp(join(tmpdir(), "runestone-packaging-"));
|
||||||
|
const source = join(root, "plugin"), output = join(root, "releases");
|
||||||
|
await mkdir(source);
|
||||||
|
const manifest = {
|
||||||
|
schemaVersion: 1, apiVersion: 1, id: "org.test.demo", name: "Demo", author: "Test",
|
||||||
|
description: "Test plugin", version: "1.0.0", entry: "main.js", access: "full-app",
|
||||||
|
};
|
||||||
|
const save = async (changes = {}) => writeFile(join(source, "plugin.json"), JSON.stringify({ ...manifest, ...changes }));
|
||||||
|
try {
|
||||||
|
await assert.rejects(packagePlugin(source, output), /plugin.json at its root/);
|
||||||
|
await save();
|
||||||
|
await assert.rejects(packagePlugin(source, output), /entry module is missing/);
|
||||||
|
await writeFile(join(source, "main.js"), "export function activate() {}");
|
||||||
|
for (const [changes, message] of [
|
||||||
|
[{ id: "../escape" }, /ID is invalid/],
|
||||||
|
[{ version: "1.0" }, /version such as/],
|
||||||
|
[{ entry: "../main.js" }, /compiled JavaScript/],
|
||||||
|
[{ apiVersion: 99 }, /Unsupported/],
|
||||||
|
[{ author: "" }, /valid author/],
|
||||||
|
] as const) {
|
||||||
|
await save(changes);
|
||||||
|
await assert.rejects(packagePlugin(source, output), message);
|
||||||
|
}
|
||||||
|
await save();
|
||||||
|
await assert.rejects(packagePlugin(source, source), /outside the plugin folder/);
|
||||||
|
await writeFile(join(source, "invalid file.txt"), "test");
|
||||||
|
await assert.rejects(packagePlugin(source, output), /Invalid package path/);
|
||||||
|
await rm(join(source, "invalid file.txt"));
|
||||||
|
const path = await packagePlugin(source, output);
|
||||||
|
assert.equal(path, join(await realpath(output), "org.test.demo-1.0.0.zip"));
|
||||||
|
const first = await readFile(path);
|
||||||
|
await packagePlugin(source, output);
|
||||||
|
assert.deepEqual(await readFile(path), first);
|
||||||
|
} finally {
|
||||||
|
// mkdtemp returns this test's unique directory under the operating system temp folder.
|
||||||
|
assert.equal(root.startsWith(join(tmpdir(), "runestone-packaging-")), true);
|
||||||
|
await rm(root, { recursive: true, force: true });
|
||||||
|
}
|
||||||
|
});
|
||||||
@@ -170,7 +170,7 @@ try {
|
|||||||
assert.equal(await dialog.getByRole('heading', { name: 'Bundled plugins' }).count(), 0);
|
assert.equal(await dialog.getByRole('heading', { name: 'Bundled plugins' }).count(), 0);
|
||||||
for (const name of ['Terminal', 'Table formulas']) {
|
for (const name of ['Terminal', 'Table formulas']) {
|
||||||
await page.waitForFunction(() => [...document.querySelectorAll('input[role="switch"]')].every(input => !input.disabled));
|
await page.waitForFunction(() => [...document.querySelectorAll('input[role="switch"]')].every(input => !input.disabled));
|
||||||
await dialog.getByRole('button', { name: `Uninstall ${name}`, exact: true }).click();
|
await dialog.locator('.card').filter({ has: page.getByRole('switch', { name, exact: true }) }).getByRole('button', { name: 'Uninstall', exact: true }).click();
|
||||||
const confirmation = page.getByRole('dialog', { name: `Uninstall ${name}?`, exact: true });
|
const confirmation = page.getByRole('dialog', { name: `Uninstall ${name}?`, exact: true });
|
||||||
await confirmation.getByRole('button', { name: 'Uninstall and delete files', exact: true }).click();
|
await confirmation.getByRole('button', { name: 'Uninstall and delete files', exact: true }).click();
|
||||||
await confirmation.waitFor({ state: 'hidden' });
|
await confirmation.waitFor({ state: 'hidden' });
|
||||||
|
|||||||
+24
-1
@@ -2,7 +2,8 @@ import test from "node:test";
|
|||||||
import assert from "node:assert/strict";
|
import assert from "node:assert/strict";
|
||||||
import { ContributionRegistry, pluginHost } from "../src/lib/plugins/registry.ts";
|
import { ContributionRegistry, pluginHost } from "../src/lib/plugins/registry.ts";
|
||||||
import { ExternalSession } from "../src/lib/plugins/externalSession.ts";
|
import { ExternalSession } from "../src/lib/plugins/externalSession.ts";
|
||||||
import { activate } from "../plugins/table-formulas/index.ts";
|
// @ts-ignore The compiled package is generated by pnpm build:plugins.
|
||||||
|
import { activate } from "../plugin-packages/table-formulas/main.js";
|
||||||
import { renderMarkdownHtml, renderMarkdownSections } from "../src/lib/workspace/noteHtml.ts";
|
import { renderMarkdownHtml, renderMarkdownSections } from "../src/lib/workspace/noteHtml.ts";
|
||||||
import type { PluginApi } from "../src/lib/plugins/sdk.ts";
|
import type { PluginApi } from "../src/lib/plugins/sdk.ts";
|
||||||
|
|
||||||
@@ -11,6 +12,28 @@ const services = {
|
|||||||
settings: { read: async () => null, write: async () => {} },
|
settings: { read: async () => null, write: async () => {} },
|
||||||
assets: { read: async () => new Uint8Array() },
|
assets: { read: async () => new Uint8Array() },
|
||||||
};
|
};
|
||||||
|
|
||||||
|
test("optional workspace creation and reads stop when the plugin is disabled", async () => {
|
||||||
|
const files = new Map<string, string>();
|
||||||
|
let api!: PluginApi;
|
||||||
|
const session = new ExternalSession("workspace-test", {
|
||||||
|
...services,
|
||||||
|
workspace: {
|
||||||
|
...services.workspace,
|
||||||
|
readOptional: async path => files.get(path) ?? null,
|
||||||
|
create: async (path, contents) => { if (files.has(path)) throw new Error("exists"); files.set(path, contents); },
|
||||||
|
},
|
||||||
|
}, () => {}, () => {});
|
||||||
|
await session.start({ activate(value) { api = value; } });
|
||||||
|
assert.equal(await api.workspace.readOptional!("board.json"), null);
|
||||||
|
await api.workspace.create!("board.json", "{}");
|
||||||
|
assert.equal(await api.workspace.readOptional!("board.json"), "{}");
|
||||||
|
await assert.rejects(api.workspace.create!("board.json", "replacement"), /exists/);
|
||||||
|
await session.stop();
|
||||||
|
assert.throws(() => api.workspace.create!("other.json", "{}"), /disabled/);
|
||||||
|
assert.throws(() => api.workspace.readOptional!("board.json"), /disabled/);
|
||||||
|
assert.equal(files.size, 1);
|
||||||
|
});
|
||||||
test("core starts without optional features and formula packages preserve source when stopped", async () => {
|
test("core starts without optional features and formula packages preserve source when stopped", async () => {
|
||||||
assert.equal(pluginHost.get("terminal"), undefined);
|
assert.equal(pluginHost.get("terminal"), undefined);
|
||||||
assert.equal(pluginHost.get("tableFormulas"), undefined);
|
assert.equal(pluginHost.get("tableFormulas"), undefined);
|
||||||
|
|||||||
@@ -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 { planRename, planTitleRename, planMarkdownTitleRename } from "../src/lib/workspace/renamePath.ts";
|
import { planRename, planTitleRename, planMarkdownTitleRename, planDocumentTitleRename } from "../src/lib/workspace/renamePath.ts";
|
||||||
|
|
||||||
test("rename in a folder keeps the parent", () => {
|
test("rename in a folder keeps the parent", () => {
|
||||||
assert.deepEqual(planRename("notes/a.md", "b.md"), {
|
assert.deepEqual(planRename("notes/a.md", "b.md"), {
|
||||||
@@ -64,3 +64,13 @@ test("writing titles preserve Markdown extensions and allow dots in names", () =
|
|||||||
assert.equal(planMarkdownTitleRename("notes/inbox.md", name).action, "error", name);
|
assert.equal(planMarkdownTitleRename("notes/inbox.md", name).action, "error", name);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test("document names retain their format and cannot hide or move the file", () => {
|
||||||
|
assert.deepEqual(planDocumentTitleRename("Projects/Board.md", "Renamed"), { action: "rename", to: "Projects/Renamed.md" });
|
||||||
|
assert.deepEqual(planDocumentTitleRename("Projects/Board.md", "Release 1.2"), { action: "rename", to: "Projects/Release 1.2.md" });
|
||||||
|
assert.deepEqual(planDocumentTitleRename("Projects/Board.MD", "Renamed.md"), { action: "rename", to: "Projects/Renamed.MD" });
|
||||||
|
assert.deepEqual(planDocumentTitleRename("Report.pdf", "Next.pdf"), { action: "rename", to: "Next.pdf" });
|
||||||
|
assert.deepEqual(planDocumentTitleRename("Board.md", "Board"), { action: "noop" });
|
||||||
|
for (const name of ["", " ", ".md", ".hidden", "../escape", "folder/name", "folder\\name", "a:b", "a?b"])
|
||||||
|
assert.equal(planDocumentTitleRename("Board.md", name).action, "error", name);
|
||||||
|
});
|
||||||
|
|||||||
@@ -67,7 +67,7 @@ try {
|
|||||||
await changeSeconds(2);
|
await changeSeconds(2);
|
||||||
await settings.getByRole("textbox", { name: "Search settings" }).fill("plugins");
|
await settings.getByRole("textbox", { name: "Search settings" }).fill("plugins");
|
||||||
await settings.getByText("No plugins installed.", { exact: true }).waitFor();
|
await settings.getByText("No plugins installed.", { exact: true }).waitFor();
|
||||||
assert(await settings.getByRole("button", { name: "Install from folder", exact: true }).isEnabled());
|
assert(await settings.getByRole("button", { name: "Install plugin ZIP", exact: true }).isEnabled());
|
||||||
await settings.getByRole("textbox", { name: "Search settings" }).fill("no such setting");
|
await settings.getByRole("textbox", { name: "Search settings" }).fill("no such setting");
|
||||||
await settings.getByText("No settings found", { exact: true }).waitFor();
|
await settings.getByText("No settings found", { exact: true }).waitFor();
|
||||||
await settings.getByRole("button", { name: "Clear search" }).click();
|
await settings.getByRole("button", { name: "Clear search" }).click();
|
||||||
@@ -78,7 +78,7 @@ try {
|
|||||||
await page.getByRole("textbox", { name: "Find a file" }).fill("note.txt");
|
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.getByRole("dialog").getByRole("button").filter({ hasText: "note.txt" }).first().click();
|
||||||
await page.locator(".monaco-editor textarea").waitFor();
|
await page.locator(".monaco-editor textarea").waitFor();
|
||||||
await page.clock.pauseAt(new Date());
|
await page.clock.pauseAt(new Date(await page.evaluate(() => Date.now()) + 1000));
|
||||||
await trigger.click();
|
await trigger.click();
|
||||||
await changeSeconds(3);
|
await changeSeconds(3);
|
||||||
await page.keyboard.press("Escape");
|
await page.keyboard.press("Escape");
|
||||||
|
|||||||
@@ -1,7 +1,8 @@
|
|||||||
import assert from "node:assert/strict";
|
import assert from "node:assert/strict";
|
||||||
import test, { before, after } from "node:test";
|
import test, { before, after } from "node:test";
|
||||||
import { ExternalSession } from "../src/lib/plugins/externalSession.ts";
|
import { ExternalSession } from "../src/lib/plugins/externalSession.ts";
|
||||||
import { activate } from "../plugins/table-formulas/index.ts";
|
// @ts-ignore The compiled package is generated by pnpm build:plugins.
|
||||||
|
import { activate } from "../plugin-packages/table-formulas/main.js";
|
||||||
const session = new ExternalSession("runestone.table-formulas", {
|
const session = new ExternalSession("runestone.table-formulas", {
|
||||||
workspace: { list: async () => [], read: async () => "", write: async () => {} },
|
workspace: { list: async () => [], read: async () => "", write: async () => {} },
|
||||||
settings: { read: async () => null, write: async () => {} },
|
settings: { read: async () => null, write: async () => {} },
|
||||||
@@ -9,74 +10,10 @@ const session = new ExternalSession("runestone.table-formulas", {
|
|||||||
}, () => {}, () => {});
|
}, () => {}, () => {});
|
||||||
before(() => session.start({ activate }));
|
before(() => session.start({ activate }));
|
||||||
after(() => session.stop());
|
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";
|
||||||
|
|
||||||
const calculate = (formula: string) => evaluateTableFormulas([[formula]])[0][0]!.text;
|
|
||||||
test("aggregates distinguish separate cells and ranges from an arithmetic argument", () => {
|
|
||||||
const evaluate = (formula: string) => evaluateTableFormulas([["Name", "B", "C", "Result"], ["First", "9", "10", formula]])[1][3]!;
|
|
||||||
for (const [name, separate, combined] of [["SUM", "19", "19"], ["AVERAGE", "9.5", "19"], ["MIN", "9", "19"], ["MAX", "10", "19"], ["COUNT", "2", "1"]]) {
|
|
||||||
for (const separator of [",", ":"]) {
|
|
||||||
const result = evaluate(`=${name}(B2${separator}C2)`);
|
|
||||||
assert.equal(result.text, separate);
|
|
||||||
}
|
|
||||||
const result = evaluate(`=${name}(B2+C2)`);
|
|
||||||
assert.equal(result.text, combined);
|
|
||||||
}
|
|
||||||
assert.equal(evaluate("=(B2+C2)/2").text, "9.5");
|
|
||||||
assert.equal(evaluate("=ROUND(AVERAGE(B2,C2),0)").text, "10");
|
|
||||||
assert.equal(evaluate("=ABS(B2-C2)").text, "1");
|
|
||||||
assert.equal(evaluate("=AVERAGE((B2+C2))").text, "19");
|
|
||||||
});
|
|
||||||
|
|
||||||
test("arithmetic, precedence, parentheses, percentages and rounding", () => {
|
|
||||||
for (const [formula, result] of [
|
|
||||||
["=SUM(2+3)", "5"], ["=2+3*4", "14"], ["=(2+3)*4", "20"],
|
|
||||||
["=2^3^2", "512"], ["=-2^2", "-4"], ["=2^-2", "0.25"],
|
|
||||||
["=200*10%", "20"], ["=0.1+0.2", "0.3"], ["=1e2 + .5", "100.5"],
|
|
||||||
["=ROUND(-1.25,1)", "-1.3"], ["=ROUND(1.005,2)", "1.01"],
|
|
||||||
["=ROUND(125,-1)", "130"], ["=ABS(-4)", "4"], ["=sum(1,2,3)", "6"],
|
|
||||||
]) assert.equal(calculate(formula), result, formula);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("same-table references, ranges, chained dependencies, and empty/text cells", () => {
|
|
||||||
const results = evaluateTableFormulas([
|
|
||||||
["Name", "Appearance", "Cha", "Combined"],
|
|
||||||
["First", "9", "10", "=AVERAGE(B2:C2)"],
|
|
||||||
["Second", "7", "9", "=SUM(B3,C3)/2"],
|
|
||||||
["Total", "", "=B4+1", "=SUM(D2:D3)"],
|
|
||||||
["Count", "=COUNT(A1:C4)", "=MAX(B2:C3)-MIN(B2:C3)", "=ROUND(D4/3,2)"],
|
|
||||||
["", "=SUM($B$2:$C$3)", "=AVERAGE(B1:B4)", "=SUM(C3:B2)"],
|
|
||||||
]);
|
|
||||||
assert.equal(results[1][3]?.text, "9.5");
|
|
||||||
assert.equal(results[2][3]?.text, "8");
|
|
||||||
assert.equal(results[3][3]?.text, "17.5");
|
|
||||||
assert.equal(results[3][2]?.text, "1");
|
|
||||||
assert.equal(results[4][1]?.text, "5");
|
|
||||||
assert.equal(results[4][2]?.text, "3");
|
|
||||||
assert.equal(results[4][3]?.text, "5.83");
|
|
||||||
assert.equal(results[5][1]?.text, "35");
|
|
||||||
assert.equal(results[5][2]?.text, "8");
|
|
||||||
assert.equal(results[5][3]?.text, "35");
|
|
||||||
assert.equal(results[0][0], null);
|
|
||||||
assert.equal(cellAddress(1, 26), "AA2");
|
|
||||||
assert.equal(evaluateTableFormulas([Array.from({ length: 27 }, (_, c) => c === 0 ? "=AA1" : "3")])[0][0]?.text, "3");
|
|
||||||
});
|
|
||||||
|
|
||||||
test("errors are visible, propagated, bounded, and never executed", () => {
|
|
||||||
for (const [formula, result] of [
|
|
||||||
["=1/0", "#DIV/0!"], ["=AVERAGE()", "#DIV/0!"], ["=A2", "#REF!"],
|
|
||||||
["=B1:B999999999", "#REF!"], ["=A0", "#REF!"], ["=1+", "#ERROR!"],
|
|
||||||
["=1 2", "#ERROR!"], ["=ROUND(1,2,3)", "#ERROR!"], ["=BOGUS(1)", "#NAME?"],
|
|
||||||
["=A1", "#CYCLE!"], ["=1e999", "#NUM!"], ["=9^9999", "#NUM!"],
|
|
||||||
["=globalThis.alert(1)", "#ERROR!"], ["=" + "(".repeat(100) + "1" + ")".repeat(100), "#LIMIT!"],
|
|
||||||
]) assert.equal(calculate(formula), result, formula);
|
|
||||||
const cycle = evaluateTableFormulas([["=B1", "=A1", "=SUM(A1:B1)", "=2+3"]]);
|
|
||||||
assert.deepEqual(cycle[0].map(cell => cell?.text), ["#CYCLE!", "#CYCLE!", "#CYCLE!", "5"]);
|
|
||||||
assert.equal(evaluateTableFormulas([["text", "=A1+1"]])[0][1]?.text, "#VALUE!");
|
|
||||||
});
|
|
||||||
|
|
||||||
test("Markdown rendering isolates tables and preserves literal, formatted, and non-table text", () => {
|
test("Markdown rendering isolates tables and preserves literal, formatted, and non-table text", () => {
|
||||||
const source = "| X | Y | Result |\r\n| --- | --- | --- |\r\n| 9 | 10 | =AVERAGE(A2:B2) |\r\n\r\n| X | Y | Result |\r\n| --- | --- | --- |\r\n| 1 | 3 | =A2*B2 |\r\n";
|
const source = "| X | Y | Result |\r\n| --- | --- | --- |\r\n| 9 | 10 | =AVERAGE(A2:B2) |\r\n\r\n| X | Y | Result |\r\n| --- | --- | --- |\r\n| 1 | 3 | =A2*B2 |\r\n";
|
||||||
const html = renderMarkdownHtml(source, new Map());
|
const html = renderMarkdownHtml(source, new Map());
|
||||||
|
|||||||
@@ -1,198 +0,0 @@
|
|||||||
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";
|
|
||||||
import { readFile } from "node:fs/promises";
|
|
||||||
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 page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
|
|
||||||
page.setDefaultTimeout(10000);
|
|
||||||
const errors = [];
|
|
||||||
const showcase = await readFile(new URL("../fixtures/reader-showcase.md", import.meta.url), "utf8");
|
|
||||||
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.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 === "workspace_abs_path") return root + "\\" + args.rel.replaceAll("/", "\\");
|
|
||||||
if (command === "pty_profiles") return [{ id: "powershell", title: "PowerShell", kind: "powershell" }, { id: "cmd", title: "Command Prompt", kind: "cmd" }, { id: "git-bash", title: "Git Bash", kind: "bash" }, { id: "node", title: "JavaScript Debug Terminal", kind: "node" }];
|
|
||||||
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);
|
|
||||||
|
|
||||||
|
|
||||||
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 click = name => page.getByRole("button", { 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(""));
|
|
||||||
try {
|
|
||||||
await page.goto(process.env.SMOKE_URL || "http://127.0.0.1:1420");
|
|
||||||
await page.getByText("smoke-workspace", { exact: true }).waitFor();
|
|
||||||
await click("Terminal");
|
|
||||||
await waitCount("pty_open", 1);
|
|
||||||
assert.equal(await page.getByRole("navigation", { name: "Terminal list" }).count(), 0);
|
|
||||||
const adjacent = await page.getByRole("button", { name: "New terminal", exact: true }).evaluate(button => { const buttons = [...button.closest(".actions").querySelectorAll("button")]; return buttons[buttons.indexOf(button) + 1]?.getAttribute("aria-label"); });
|
|
||||||
assert.equal(adjacent, "Terminal profiles and tasks");
|
|
||||||
await click("Split terminal (Ctrl+Shift+5)");
|
|
||||||
await waitCount("pty_open", 2);
|
|
||||||
assert.equal(await page.getByRole("navigation", { name: "Terminal list" }).count(), 1);
|
|
||||||
assert.equal(await page.locator(".pane.shown").count(), 2);
|
|
||||||
const original = await page.locator(".pane.shown").first().boundingBox();
|
|
||||||
await click("Maximize panel");
|
|
||||||
const enlarged = await page.locator(".pane.shown").first().boundingBox();
|
|
||||||
assert.ok(enlarged.height > original.height + 100);
|
|
||||||
assert.equal(await count("pty_close"), 0);
|
|
||||||
await page.screenshot({ path: ".audit/terminal-splits.png" });
|
|
||||||
await click("Restore panel");
|
|
||||||
await click("Hide terminal (sessions keep running)");
|
|
||||||
assert.equal(await count("pty_close"), 0);
|
|
||||||
await page.keyboard.press("Control+j");
|
|
||||||
assert.equal(await count("pty_open"), 2);
|
|
||||||
await click("Terminal profiles and tasks");
|
|
||||||
await page.screenshot({ path: ".audit/terminal-profiles.png" });
|
|
||||||
await menu("Command Prompt");
|
|
||||||
await waitCount("pty_open", 3);
|
|
||||||
assert.equal(await page.locator(".pane.shown").count(), 1);
|
|
||||||
assert.equal(await page.evaluate(() => window.__TEST__.calls.filter(c => c.command === "pty_open").at(-1).args.profile), "cmd");
|
|
||||||
await page.keyboard.press("Control+Shift+5");
|
|
||||||
await waitCount("pty_open", 4);
|
|
||||||
assert.equal(await page.locator(".pane.shown").count(), 2);
|
|
||||||
await click("Kill terminal");
|
|
||||||
await waitCount("pty_close", 1);
|
|
||||||
assert.equal(await page.locator(".pane.shown").count(), 1);
|
|
||||||
// OSC prompt integration reaches the history pickers.
|
|
||||||
await page.evaluate(() => {
|
|
||||||
const id = window.__TEST__.calls.filter(c => c.command === "pty_open")[2].args.id;
|
|
||||||
const data = `\x1b]633;RSCommand;${btoa("echo history-check")}\x07\x1b]633;RSCwd;${btoa("C:\\two words")}\x07\x1b]133;A\x07C:\\two words>\x1b]133;B\x07`;
|
|
||||||
window.__TEST__.emit("pty-data", { id, data: [...new TextEncoder().encode(data)] });
|
|
||||||
});
|
|
||||||
await click("More terminal actions");
|
|
||||||
await page.screenshot({ path: ".audit/terminal-actions.png" });
|
|
||||||
await menu("Run Recent Command… Ctrl+Alt+R");
|
|
||||||
await page.getByRole("dialog").getByRole("button", { name: "echo history-check" }).click();
|
|
||||||
await page.waitForFunction(() => window.__TEST__.calls.some(c => c.command === "pty_write" && c.args.data.includes("echo history-check")));
|
|
||||||
await page.keyboard.press("Control+g");
|
|
||||||
await page.getByRole("dialog").getByRole("button", { name: "C:\\two words" }).click();
|
|
||||||
assert.ok((await writes()).includes('cd /d "C:\\two words"'));
|
|
||||||
await click("Terminal profiles and tasks");
|
|
||||||
await menu("Configure Terminal Settings");
|
|
||||||
await page.getByLabel("Font size", { exact: true }).fill("16");
|
|
||||||
await page.getByLabel("Default profile", { exact: true }).selectOption("git-bash");
|
|
||||||
await click("Save settings");
|
|
||||||
await click("New terminal");
|
|
||||||
await waitCount("pty_open", 5);
|
|
||||||
assert.equal(await page.evaluate(() => window.__TEST__.calls.filter(c => c.command === "pty_open").at(-1).args.profile), "git-bash");
|
|
||||||
assert.equal(await page.evaluate(() => JSON.parse(localStorage.getItem("runestone.terminal")).fontSize), 16);
|
|
||||||
await page.evaluate(() => window.__TEST__.files.set(".runestone/tasks.json", JSON.stringify({ tasks: [{ label: "Smoke task", command: "echo task-ok", profile: "powershell" }] })));
|
|
||||||
await click("Terminal profiles and tasks");
|
|
||||||
await menu("Run Task…");
|
|
||||||
await page.getByRole("dialog").getByRole("button", { name: "Smoke task echo task-ok" }).click();
|
|
||||||
await waitCount("pty_open", 6);
|
|
||||||
await page.waitForFunction(() => window.__TEST__.calls.some(c => c.command === "pty_write" && c.args.data.includes("echo task-ok")));
|
|
||||||
// Capture selected source while the terminal menu takes focus.
|
|
||||||
await page.getByRole("button", { name: /Find a file/ }).click();
|
|
||||||
await page.getByRole("textbox", { name: "Find a file" }).fill("hello.py");
|
|
||||||
await page.getByRole("dialog").getByRole("button").filter({ hasText: "hello.py" }).click();
|
|
||||||
await page.locator(".monaco-editor textarea").waitFor();
|
|
||||||
await page.evaluate(async () => {
|
|
||||||
const { monaco } = await import("/src/lib/editor/monacoEnv.ts");
|
|
||||||
const editor = monaco.editor.getEditors().find(e => e.getDomNode()?.isConnected);
|
|
||||||
editor.setSelection({ startLineNumber: 1, startColumn: 1, endLineNumber: 1, endColumn: 15 });
|
|
||||||
});
|
|
||||||
await click("More terminal actions");
|
|
||||||
await menu("Run Selected Text");
|
|
||||||
await page.waitForFunction(() => window.__TEST__.calls.some(c => c.command === "pty_write" && c.args.data.includes("print('hello')")));
|
|
||||||
await click("More terminal actions");
|
|
||||||
await menu("Run Active File");
|
|
||||||
await page.waitForFunction(() => window.__TEST__.calls.some(c => c.command === "pty_write" && c.args.data.includes("python 'C:\\smoke-workspace\\src\\hello.py'")));
|
|
||||||
await click("Terminal profiles and tasks");
|
|
||||||
await menu("New Terminal Window Ctrl+Shift+Alt+`");
|
|
||||||
await waitCount("pty_new_window", 1);
|
|
||||||
await click("More terminal actions");
|
|
||||||
await menu("Start Dictation");
|
|
||||||
await waitCount("pty_dictation", 1);
|
|
||||||
await click("More terminal actions");
|
|
||||||
await menu("Clear Terminal");
|
|
||||||
assert.equal(await count("pty_close"), 1);
|
|
||||||
await page.setViewportSize({ width: 880, height: 600 });
|
|
||||||
await page.screenshot({ path: ".audit/terminal-narrow.png" });
|
|
||||||
for (let remaining = 5; remaining > 1; remaining--) await click("Kill terminal");
|
|
||||||
await waitCount("pty_close", 5);
|
|
||||||
assert.equal(await page.getByRole("navigation", { name: "Terminal list" }).count(), 0);
|
|
||||||
await page.screenshot({ path: ".audit/terminal-single.png" });
|
|
||||||
await click("Kill terminal");
|
|
||||||
await waitCount("pty_close", 6);
|
|
||||||
await click("Start a terminal");
|
|
||||||
await waitCount("pty_open", 7);
|
|
||||||
await page.locator(".pane.shown .xterm-helper-textarea").focus();
|
|
||||||
await page.keyboard.press("Control+Shift+Backquote");
|
|
||||||
await waitCount("pty_open", 8);
|
|
||||||
await page.keyboard.press("Control+Shift+Alt+Backquote");
|
|
||||||
await waitCount("pty_new_window", 2);
|
|
||||||
await page.goto((process.env.SMOKE_URL || "http://127.0.0.1:1420") + "/?terminalWindow=C%3A%5Csmoke-workspace");
|
|
||||||
await waitCount("pty_open", 1);
|
|
||||||
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("navigation", { name: "Terminal list" }).count(), 0);
|
|
||||||
await page.screenshot({ path: ".audit/terminal-window.png" });
|
|
||||||
assert.deepEqual(errors, []);
|
|
||||||
console.log("PASS: split groups, profile selection, maximize/restore/hide, shell history, directory quoting, settings persistence, tasks, editor selection/file execution, window/dictation IPC, and narrow layout.");
|
|
||||||
} catch (error) { console.log("errors", errors, "writes", await writes());
|
|
||||||
await page.screenshot({ path: ".audit/terminal-failure.png" });
|
|
||||||
throw error;
|
|
||||||
} finally { await browser.close(); }
|
|
||||||
@@ -1,39 +0,0 @@
|
|||||||
import assert from "node:assert/strict";
|
|
||||||
import test from "node:test";
|
|
||||||
import { directoryCommand, fileCommand, parseTasks, quoteShell, remember, terminalShortcut } from "../plugins/terminal/model.ts";
|
|
||||||
|
|
||||||
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(quoteShell("/tmp/it's $(bad)", "bash"), "'/tmp/it'\\''s $(bad)'");
|
|
||||||
assert.equal(directoryCommand("C:\\two words", "cmd"), 'cd /d "C:\\two words"');
|
|
||||||
assert.equal(directoryCommand("C:\\two words", "node"), 'process.chdir("C:\\\\two words")');
|
|
||||||
assert.throws(() => quoteShell("C:\\%PATH%", "cmd"));
|
|
||||||
assert.throws(() => fileCommand("a\nwhoami.py", "powershell"));
|
|
||||||
});
|
|
||||||
|
|
||||||
test("run file selects a runner and rejects non-executable documents", () => {
|
|
||||||
assert.equal(fileCommand("D:\\project\\hello world.py", "powershell"), "python 'D:\\project\\hello world.py'");
|
|
||||||
assert.equal(fileCommand("/project/app.mjs", "bash"), "node '/project/app.mjs'");
|
|
||||||
assert.throws(() => fileCommand("notes.md", "powershell"));
|
|
||||||
assert.throws(() => fileCommand("app.js", "node"));
|
|
||||||
});
|
|
||||||
|
|
||||||
test("task config validates every entry before offering execution", () => {
|
|
||||||
assert.deepEqual(parseTasks('{"tasks":[{"label":"Test","command":"npm test","profile":"pwsh"}]}'), [{ label: "Test", command: "npm test", profile: "pwsh" }]);
|
|
||||||
for (const text of ['{}', '{"tasks":[null]}', '{"tasks":[{"label":"x","command":" "}]}', '{"tasks":[{"label":"x","command":"echo hi","profile":4}]}']) assert.throws(() => parseTasks(text));
|
|
||||||
});
|
|
||||||
|
|
||||||
test("history deduplicates most recent entries and is bounded", () => {
|
|
||||||
assert.deepEqual(remember(["one", "two"], "two"), ["two", "one"]);
|
|
||||||
assert.equal(remember(Array.from({ length: 100 }, (_, i) => String(i)), "new").length, 100);
|
|
||||||
assert.deepEqual(remember(["one"], " "), ["one"]);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("physical key shortcuts distinguish new, split, window, and hide", () => {
|
|
||||||
const key = { ctrlKey: true, metaKey: false, altKey: false, shiftKey: true, code: "Backquote", key: "~" };
|
|
||||||
assert.equal(terminalShortcut(key), "new");
|
|
||||||
assert.equal(terminalShortcut({ ...key, altKey: true }), "window");
|
|
||||||
assert.equal(terminalShortcut({ ...key, code: "Digit5", key: "%" }), "split");
|
|
||||||
assert.equal(terminalShortcut({ ...key, shiftKey: false, code: "KeyJ", key: "j" }), "toggle");
|
|
||||||
assert.equal(terminalShortcut({ ...key, shiftKey: false, code: "KeyC", key: "c" }), null);
|
|
||||||
});
|
|
||||||
Generated
+165
-3
@@ -541,7 +541,7 @@ dependencies = [
|
|||||||
"bitflags 2.13.2",
|
"bitflags 2.13.2",
|
||||||
"core-foundation",
|
"core-foundation",
|
||||||
"core-graphics-types",
|
"core-graphics-types",
|
||||||
"foreign-types",
|
"foreign-types 0.5.0",
|
||||||
"libc",
|
"libc",
|
||||||
]
|
]
|
||||||
|
|
||||||
@@ -1071,6 +1071,15 @@ version = "0.2.0"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb"
|
checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "foreign-types"
|
||||||
|
version = "0.3.2"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "f6f339eb8adc052cd2ca78910fda869aefa38d22d5cb648e6485e4d3fc06f3b1"
|
||||||
|
dependencies = [
|
||||||
|
"foreign-types-shared 0.1.1",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "foreign-types"
|
name = "foreign-types"
|
||||||
version = "0.5.0"
|
version = "0.5.0"
|
||||||
@@ -1078,7 +1087,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
|||||||
checksum = "d737d9aa519fb7b749cbc3b962edcf310a8dd1f4b67c91c4f83975dbdd17d965"
|
checksum = "d737d9aa519fb7b749cbc3b962edcf310a8dd1f4b67c91c4f83975dbdd17d965"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"foreign-types-macros",
|
"foreign-types-macros",
|
||||||
"foreign-types-shared",
|
"foreign-types-shared 0.3.1",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -1092,6 +1101,12 @@ dependencies = [
|
|||||||
"syn 3.0.6",
|
"syn 3.0.6",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "foreign-types-shared"
|
||||||
|
version = "0.1.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "00b0228411908ca8685dba7fc2cdd70ec9990a6e753e89b6ac91a84c40fbaf4b"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "foreign-types-shared"
|
name = "foreign-types-shared"
|
||||||
version = "0.3.1"
|
version = "0.3.1"
|
||||||
@@ -1123,6 +1138,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
|||||||
checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4"
|
checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"futures-core",
|
"futures-core",
|
||||||
|
"futures-sink",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -1598,6 +1614,22 @@ dependencies = [
|
|||||||
"want",
|
"want",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "hyper-tls"
|
||||||
|
version = "0.6.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "70206fc6890eaca9fde8a0bf71caa2ddfc9fe045ac9e5c70df101a7dbde866e0"
|
||||||
|
dependencies = [
|
||||||
|
"bytes",
|
||||||
|
"http-body-util",
|
||||||
|
"hyper",
|
||||||
|
"hyper-util",
|
||||||
|
"native-tls",
|
||||||
|
"tokio",
|
||||||
|
"tokio-native-tls",
|
||||||
|
"tower-service",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "hyper-util"
|
name = "hyper-util"
|
||||||
version = "0.1.20"
|
version = "0.1.20"
|
||||||
@@ -2225,6 +2257,23 @@ dependencies = [
|
|||||||
"windows-sys 0.61.2",
|
"windows-sys 0.61.2",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "native-tls"
|
||||||
|
version = "0.2.18"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "465500e14ea162429d264d44189adc38b199b62b1c21eea9f69e4b73cb03bbf2"
|
||||||
|
dependencies = [
|
||||||
|
"libc",
|
||||||
|
"log",
|
||||||
|
"openssl",
|
||||||
|
"openssl-probe",
|
||||||
|
"openssl-sys",
|
||||||
|
"schannel",
|
||||||
|
"security-framework",
|
||||||
|
"security-framework-sys",
|
||||||
|
"tempfile",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "ndk"
|
name = "ndk"
|
||||||
version = "0.9.0"
|
version = "0.9.0"
|
||||||
@@ -2544,6 +2593,50 @@ dependencies = [
|
|||||||
"libc",
|
"libc",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "openssl"
|
||||||
|
version = "0.10.76"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "951c002c75e16ea2c65b8c7e4d3d51d5530d8dfa7d060b4776828c88cfb18ecf"
|
||||||
|
dependencies = [
|
||||||
|
"bitflags 2.13.2",
|
||||||
|
"cfg-if",
|
||||||
|
"foreign-types 0.3.2",
|
||||||
|
"libc",
|
||||||
|
"once_cell",
|
||||||
|
"openssl-macros",
|
||||||
|
"openssl-sys",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "openssl-macros"
|
||||||
|
version = "0.1.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c"
|
||||||
|
dependencies = [
|
||||||
|
"proc-macro2",
|
||||||
|
"quote",
|
||||||
|
"syn 2.0.119",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "openssl-probe"
|
||||||
|
version = "0.2.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "openssl-sys"
|
||||||
|
version = "0.9.112"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "57d55af3b3e226502be1526dfdba67ab0e9c96fc293004e79576b2b9edb0dbdb"
|
||||||
|
dependencies = [
|
||||||
|
"cc",
|
||||||
|
"libc",
|
||||||
|
"pkg-config",
|
||||||
|
"vcpkg",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "option-ext"
|
name = "option-ext"
|
||||||
version = "0.2.0"
|
version = "0.2.0"
|
||||||
@@ -2980,21 +3073,26 @@ checksum = "16a1cfa75cc186dd73d5818e510e042e40927bccc9c236b061cea97e1eb08029"
|
|||||||
dependencies = [
|
dependencies = [
|
||||||
"base64 0.23.1",
|
"base64 0.23.1",
|
||||||
"bytes",
|
"bytes",
|
||||||
|
"futures-channel",
|
||||||
"futures-core",
|
"futures-core",
|
||||||
"futures-util",
|
"futures-util",
|
||||||
"http",
|
"http",
|
||||||
"http-body",
|
"http-body",
|
||||||
"http-body-util",
|
"http-body-util",
|
||||||
"hyper",
|
"hyper",
|
||||||
|
"hyper-tls",
|
||||||
"hyper-util",
|
"hyper-util",
|
||||||
"js-sys",
|
"js-sys",
|
||||||
"log",
|
"log",
|
||||||
|
"native-tls",
|
||||||
"percent-encoding",
|
"percent-encoding",
|
||||||
"pin-project-lite",
|
"pin-project-lite",
|
||||||
|
"rustls-pki-types",
|
||||||
"serde",
|
"serde",
|
||||||
"serde_json",
|
"serde_json",
|
||||||
"sync_wrapper",
|
"sync_wrapper",
|
||||||
"tokio",
|
"tokio",
|
||||||
|
"tokio-native-tls",
|
||||||
"tokio-util",
|
"tokio-util",
|
||||||
"tower",
|
"tower",
|
||||||
"tower-http",
|
"tower-http",
|
||||||
@@ -3032,13 +3130,14 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "runestone"
|
name = "runestone"
|
||||||
version = "0.1.4"
|
version = "0.1.7"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"base64 0.23.1",
|
"base64 0.23.1",
|
||||||
"dunce",
|
"dunce",
|
||||||
"ignore",
|
"ignore",
|
||||||
"notify",
|
"notify",
|
||||||
"portable-pty",
|
"portable-pty",
|
||||||
|
"reqwest",
|
||||||
"serde",
|
"serde",
|
||||||
"serde_json",
|
"serde_json",
|
||||||
"sha2",
|
"sha2",
|
||||||
@@ -3080,6 +3179,15 @@ dependencies = [
|
|||||||
"windows-sys 0.61.2",
|
"windows-sys 0.61.2",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "rustls-pki-types"
|
||||||
|
version = "1.14.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "be040f8b0a225e40375822a563fa9524378b9d63112f53e19ffff34df5d33fdd"
|
||||||
|
dependencies = [
|
||||||
|
"zeroize",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "rustversion"
|
name = "rustversion"
|
||||||
version = "1.0.23"
|
version = "1.0.23"
|
||||||
@@ -3095,6 +3203,15 @@ dependencies = [
|
|||||||
"winapi-util",
|
"winapi-util",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "schannel"
|
||||||
|
version = "0.1.29"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "91c1b7e4904c873ef0710c1f407dde2e6287de2bebc1bbbf7d430bb7cbffd939"
|
||||||
|
dependencies = [
|
||||||
|
"windows-sys 0.61.2",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "schemars"
|
name = "schemars"
|
||||||
version = "0.8.22"
|
version = "0.8.22"
|
||||||
@@ -3152,6 +3269,29 @@ version = "1.2.0"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
|
checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "security-framework"
|
||||||
|
version = "3.7.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d"
|
||||||
|
dependencies = [
|
||||||
|
"bitflags 2.13.2",
|
||||||
|
"core-foundation",
|
||||||
|
"core-foundation-sys",
|
||||||
|
"libc",
|
||||||
|
"security-framework-sys",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "security-framework-sys"
|
||||||
|
version = "2.17.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "6ce2691df843ecc5d231c0b14ece2acc3efb62c0a398c7e1d875f3983ce020e3"
|
||||||
|
dependencies = [
|
||||||
|
"core-foundation-sys",
|
||||||
|
"libc",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "selectors"
|
name = "selectors"
|
||||||
version = "0.36.1"
|
version = "0.36.1"
|
||||||
@@ -4060,6 +4200,16 @@ dependencies = [
|
|||||||
"windows-sys 0.61.2",
|
"windows-sys 0.61.2",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "tokio-native-tls"
|
||||||
|
version = "0.3.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "bbae76ab933c85776efabc971569dd6119c580d8f5d448769dec1764bf796ef2"
|
||||||
|
dependencies = [
|
||||||
|
"native-tls",
|
||||||
|
"tokio",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "tokio-util"
|
name = "tokio-util"
|
||||||
version = "0.7.19"
|
version = "0.7.19"
|
||||||
@@ -4422,6 +4572,12 @@ dependencies = [
|
|||||||
"wasm-bindgen",
|
"wasm-bindgen",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "vcpkg"
|
||||||
|
version = "0.2.15"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "version-compare"
|
name = "version-compare"
|
||||||
version = "0.2.1"
|
version = "0.2.1"
|
||||||
@@ -5317,6 +5473,12 @@ dependencies = [
|
|||||||
"synstructure",
|
"synstructure",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "zeroize"
|
||||||
|
version = "1.8.2"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "b97154e67e32c85465826e8bcc1c59429aaaf107c1e4a9e53c8d8ccd5eff88d0"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "zerotrie"
|
name = "zerotrie"
|
||||||
version = "0.2.5"
|
version = "0.2.5"
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "runestone"
|
name = "runestone"
|
||||||
version = "0.1.4"
|
version = "0.1.7"
|
||||||
description = "Writing workspace plus script editor"
|
description = "Writing workspace plus script editor"
|
||||||
authors = ["you"]
|
authors = ["you"]
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
@@ -28,6 +28,7 @@ portable-pty = "0.9.0"
|
|||||||
zip = { version = "8.6.0", default-features = false, features = ["deflate"] }
|
zip = { version = "8.6.0", default-features = false, features = ["deflate"] }
|
||||||
sha2 = "0.10"
|
sha2 = "0.10"
|
||||||
uuid = { version = "1", features = ["v4"] }
|
uuid = { version = "1", features = ["v4"] }
|
||||||
|
reqwest = { version = "0.13.5", default-features = false, features = ["blocking", "native-tls"] }
|
||||||
|
|
||||||
|
|
||||||
# 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
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ fn main() {
|
|||||||
"workspace_new",
|
"workspace_new",
|
||||||
"workspace_list",
|
"workspace_list",
|
||||||
"workspace_read",
|
"workspace_read",
|
||||||
|
"workspace_read_bytes",
|
||||||
"workspace_write",
|
"workspace_write",
|
||||||
"workspace_create",
|
"workspace_create",
|
||||||
"workspace_rename",
|
"workspace_rename",
|
||||||
@@ -21,6 +22,7 @@ fn main() {
|
|||||||
"workspace_search",
|
"workspace_search",
|
||||||
"plugins_snapshot",
|
"plugins_snapshot",
|
||||||
"plugins_choose",
|
"plugins_choose",
|
||||||
|
"plugins_from_git",
|
||||||
"plugins_cancel",
|
"plugins_cancel",
|
||||||
"plugins_install",
|
"plugins_install",
|
||||||
"plugins_set_enabled",
|
"plugins_set_enabled",
|
||||||
|
|||||||
@@ -19,6 +19,7 @@
|
|||||||
"allow-workspace-new",
|
"allow-workspace-new",
|
||||||
"allow-workspace-list",
|
"allow-workspace-list",
|
||||||
"allow-workspace-read",
|
"allow-workspace-read",
|
||||||
|
"allow-workspace-read-bytes",
|
||||||
"allow-workspace-write",
|
"allow-workspace-write",
|
||||||
"allow-workspace-create",
|
"allow-workspace-create",
|
||||||
"allow-workspace-rename",
|
"allow-workspace-rename",
|
||||||
@@ -31,6 +32,7 @@
|
|||||||
"allow-workspace-search",
|
"allow-workspace-search",
|
||||||
"allow-plugins-snapshot",
|
"allow-plugins-snapshot",
|
||||||
"allow-plugins-choose",
|
"allow-plugins-choose",
|
||||||
|
"allow-plugins-from-git",
|
||||||
"allow-plugins-cancel",
|
"allow-plugins-cancel",
|
||||||
"allow-plugins-install",
|
"allow-plugins-install",
|
||||||
"allow-plugins-set-enabled",
|
"allow-plugins-set-enabled",
|
||||||
|
|||||||
@@ -0,0 +1,11 @@
|
|||||||
|
# Automatically generated - DO NOT EDIT!
|
||||||
|
|
||||||
|
[[permission]]
|
||||||
|
identifier = "allow-plugins-from-git"
|
||||||
|
description = "Enables the plugins_from_git command without any pre-configured scope."
|
||||||
|
commands.allow = ["plugins_from_git"]
|
||||||
|
|
||||||
|
[[permission]]
|
||||||
|
identifier = "deny-plugins-from-git"
|
||||||
|
description = "Denies the plugins_from_git command without any pre-configured scope."
|
||||||
|
commands.deny = ["plugins_from_git"]
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
# Automatically generated - DO NOT EDIT!
|
||||||
|
|
||||||
|
[[permission]]
|
||||||
|
identifier = "allow-workspace-read-bytes"
|
||||||
|
description = "Enables the workspace_read_bytes command without any pre-configured scope."
|
||||||
|
commands.allow = ["workspace_read_bytes"]
|
||||||
|
|
||||||
|
[[permission]]
|
||||||
|
identifier = "deny-workspace-read-bytes"
|
||||||
|
description = "Denies the workspace_read_bytes command without any pre-configured scope."
|
||||||
|
commands.deny = ["workspace_read_bytes"]
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
mod pty;
|
mod pty;
|
||||||
mod plugins;
|
mod plugins;
|
||||||
|
mod plugin_sources;
|
||||||
mod workspace;
|
mod workspace;
|
||||||
|
|
||||||
use pty::PtyState;
|
use pty::PtyState;
|
||||||
@@ -22,6 +23,7 @@ pub fn run() {
|
|||||||
workspace::workspace_new,
|
workspace::workspace_new,
|
||||||
workspace::workspace_list,
|
workspace::workspace_list,
|
||||||
workspace::workspace_read,
|
workspace::workspace_read,
|
||||||
|
workspace::workspace_read_bytes,
|
||||||
workspace::workspace_write,
|
workspace::workspace_write,
|
||||||
workspace::workspace_create,
|
workspace::workspace_create,
|
||||||
workspace::workspace_rename,
|
workspace::workspace_rename,
|
||||||
@@ -34,6 +36,7 @@ pub fn run() {
|
|||||||
workspace::workspace_search,
|
workspace::workspace_search,
|
||||||
plugins::plugins_snapshot,
|
plugins::plugins_snapshot,
|
||||||
plugins::plugins_choose,
|
plugins::plugins_choose,
|
||||||
|
plugins::plugins_from_git,
|
||||||
plugins::plugins_cancel,
|
plugins::plugins_cancel,
|
||||||
plugins::plugins_install,
|
plugins::plugins_install,
|
||||||
plugins::plugins_set_enabled,
|
plugins::plugins_set_enabled,
|
||||||
|
|||||||
@@ -0,0 +1,373 @@
|
|||||||
|
//! Release downloads are separate from package validation and installation.
|
||||||
|
use reqwest::{blocking::Client, Url};
|
||||||
|
use serde_json::Value;
|
||||||
|
use std::{io::Read, time::Duration};
|
||||||
|
|
||||||
|
type Result<T> = std::result::Result<T, String>;
|
||||||
|
const MAX_METADATA: usize = 2 * 1024 * 1024;
|
||||||
|
const MAX_ARCHIVE: usize = 100 * 1024 * 1024;
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct Repository {
|
||||||
|
pub url: Url,
|
||||||
|
pub api: Url,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn web_url(input: &str) -> Result<Url> {
|
||||||
|
let url = Url::parse(input).map_err(|_| "Enter a complete HTTP or HTTPS link.")?;
|
||||||
|
if !matches!(url.scheme(), "http" | "https")
|
||||||
|
|| url.host_str().is_none()
|
||||||
|
|| !url.username().is_empty()
|
||||||
|
|| url.password().is_some()
|
||||||
|
|| url.fragment().is_some()
|
||||||
|
{
|
||||||
|
return Err("Use an HTTP or HTTPS link without credentials or a fragment.".into());
|
||||||
|
}
|
||||||
|
Ok(url)
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Repository {
|
||||||
|
pub fn parse(input: &str, tag: &str) -> Result<Self> {
|
||||||
|
let mut url = web_url(input.trim())?;
|
||||||
|
if url.query().is_some() {
|
||||||
|
return Err("Use a repository link without a query.".into());
|
||||||
|
}
|
||||||
|
let path = url
|
||||||
|
.path()
|
||||||
|
.trim_end_matches('/')
|
||||||
|
.trim_end_matches(".git")
|
||||||
|
.to_owned();
|
||||||
|
let parts: Vec<_> = path.trim_start_matches('/').split('/').collect();
|
||||||
|
if parts.len() != 2
|
||||||
|
|| parts.iter().any(|part| {
|
||||||
|
part.is_empty()
|
||||||
|
|| *part == "."
|
||||||
|
|| *part == ".."
|
||||||
|
|| !part
|
||||||
|
.bytes()
|
||||||
|
.all(|c| c.is_ascii_alphanumeric() || b"._-".contains(&c))
|
||||||
|
})
|
||||||
|
{
|
||||||
|
return Err(
|
||||||
|
"Use the repository root link, such as https://host/owner/repository.".into(),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
url.set_path(&path);
|
||||||
|
let mut api = url.clone();
|
||||||
|
api.set_path("/");
|
||||||
|
{
|
||||||
|
let mut segments = api
|
||||||
|
.path_segments_mut()
|
||||||
|
.map_err(|_| "Invalid repository link.")?;
|
||||||
|
segments.clear();
|
||||||
|
segments
|
||||||
|
.extend(["api", "v1", "repos"])
|
||||||
|
.extend(&parts)
|
||||||
|
.push("releases");
|
||||||
|
let tag = tag.trim();
|
||||||
|
if tag.is_empty() {
|
||||||
|
segments.push("latest");
|
||||||
|
} else {
|
||||||
|
if tag.len() > 200 || tag.chars().any(char::is_control) || matches!(tag, "." | "..")
|
||||||
|
{
|
||||||
|
return Err("Enter a release tag with at most 200 characters.".into());
|
||||||
|
}
|
||||||
|
segments.push("tags");
|
||||||
|
segments.push(tag);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(Self { url, api })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct Download {
|
||||||
|
pub bytes: Vec<u8>,
|
||||||
|
pub source: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn read_limited(reader: impl Read, limit: usize) -> Result<Vec<u8>> {
|
||||||
|
let mut bytes = Vec::new();
|
||||||
|
reader
|
||||||
|
.take(limit as u64 + 1)
|
||||||
|
.read_to_end(&mut bytes)
|
||||||
|
.map_err(|_| "The download was interrupted. Try again.")?;
|
||||||
|
if bytes.len() > limit {
|
||||||
|
return Err("The download exceeds its size limit.".into());
|
||||||
|
}
|
||||||
|
Ok(bytes)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Send credentials only to the release API's origin, including after redirects.
|
||||||
|
fn get(
|
||||||
|
client: &Client,
|
||||||
|
start: Url,
|
||||||
|
auth_origin: &Url,
|
||||||
|
authorization: Option<&str>,
|
||||||
|
limit: usize,
|
||||||
|
) -> Result<Vec<u8>> {
|
||||||
|
let mut url = start;
|
||||||
|
let started = std::time::Instant::now();
|
||||||
|
for _ in 0..=5 {
|
||||||
|
let remaining = Duration::from_secs(60)
|
||||||
|
.checked_sub(started.elapsed())
|
||||||
|
.filter(|remaining| !remaining.is_zero())
|
||||||
|
.ok_or("The download timed out. Try again.")?;
|
||||||
|
let mut request = client.get(url.clone()).timeout(remaining);
|
||||||
|
if url.origin() == auth_origin.origin() {
|
||||||
|
if let Some(value) = authorization {
|
||||||
|
request = request.header(reqwest::header::AUTHORIZATION, value);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let response = request
|
||||||
|
.send()
|
||||||
|
.map_err(|_| "Cannot reach the release server. Check the link and connection.")?;
|
||||||
|
if response.status().is_redirection() {
|
||||||
|
let location = response
|
||||||
|
.headers()
|
||||||
|
.get(reqwest::header::LOCATION)
|
||||||
|
.and_then(|value| value.to_str().ok())
|
||||||
|
.ok_or("The server returned an invalid redirect.")?;
|
||||||
|
let next = url
|
||||||
|
.join(location)
|
||||||
|
.map_err(|_| "The server returned an invalid redirect.")?;
|
||||||
|
web_url(next.as_str())?;
|
||||||
|
if url.scheme() == "https" && next.scheme() != "https" {
|
||||||
|
return Err("The server redirected a secure link to HTTP.".into());
|
||||||
|
}
|
||||||
|
url = next;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if !response.status().is_success() {
|
||||||
|
return Err(match response.status().as_u16() {
|
||||||
|
401 | 403 => "Access denied. Check the token and repository read access.".into(),
|
||||||
|
404 => "Release not found. Check the repository, release tag, and token for private access.".into(),
|
||||||
|
429 => "The server request limit was reached. Try again later.".into(),
|
||||||
|
code => format!("The release server returned HTTP {code}."),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if response
|
||||||
|
.content_length()
|
||||||
|
.is_some_and(|size| size > limit as u64)
|
||||||
|
{
|
||||||
|
return Err("The download exceeds its size limit.".into());
|
||||||
|
}
|
||||||
|
return read_limited(response, limit);
|
||||||
|
}
|
||||||
|
Err("The server returned too many redirects.".into())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn asset(metadata: &Value) -> Result<(String, Url)> {
|
||||||
|
if metadata["draft"].as_bool() == Some(true) {
|
||||||
|
return Err("Publish the release before installing its plugin.".into());
|
||||||
|
}
|
||||||
|
let tag = metadata["tag_name"]
|
||||||
|
.as_str()
|
||||||
|
.filter(|tag| !tag.is_empty())
|
||||||
|
.ok_or("The release has no tag.")?;
|
||||||
|
let assets = &metadata["assets"];
|
||||||
|
let zips: Vec<_> = assets
|
||||||
|
.as_array()
|
||||||
|
.ok_or("The release has no attached plugin ZIP.")?
|
||||||
|
.iter()
|
||||||
|
.filter(|item| {
|
||||||
|
item["name"]
|
||||||
|
.as_str()
|
||||||
|
.is_some_and(|name| name.to_ascii_lowercase().ends_with(".zip"))
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
if zips.len() != 1 {
|
||||||
|
return Err(
|
||||||
|
"The release must contain exactly one plugin ZIP. Source archives do not count.".into(),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
let item = zips[0];
|
||||||
|
let link = item["browser_download_url"]
|
||||||
|
.as_str()
|
||||||
|
.ok_or("The plugin ZIP has no download link.")?;
|
||||||
|
if item["size"]
|
||||||
|
.as_u64()
|
||||||
|
.is_some_and(|size| size > MAX_ARCHIVE as u64)
|
||||||
|
{
|
||||||
|
return Err("The archive exceeds 100 MiB.".into());
|
||||||
|
}
|
||||||
|
Ok((tag.to_owned(), web_url(link)?))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn download(repository: &Repository, token: Option<&str>) -> Result<Download> {
|
||||||
|
let authorization = token
|
||||||
|
.filter(|value| !value.is_empty())
|
||||||
|
.map(|value| format!("token {value}"));
|
||||||
|
download_authorized(repository, authorization.as_deref())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn download_authorized(repository: &Repository, authorization: Option<&str>) -> Result<Download> {
|
||||||
|
let client = Client::builder()
|
||||||
|
.user_agent("RuneStone-plugin-installer/0.1")
|
||||||
|
.connect_timeout(Duration::from_secs(10))
|
||||||
|
.timeout(Duration::from_secs(60))
|
||||||
|
.redirect(reqwest::redirect::Policy::none())
|
||||||
|
.build()
|
||||||
|
.map_err(|_| "Cannot start the download client.")?;
|
||||||
|
let metadata = get(
|
||||||
|
&client,
|
||||||
|
repository.api.clone(),
|
||||||
|
&repository.api,
|
||||||
|
authorization,
|
||||||
|
MAX_METADATA,
|
||||||
|
)?;
|
||||||
|
let metadata: Value = serde_json::from_slice(&metadata)
|
||||||
|
.map_err(|_| "The server did not return release metadata.")?;
|
||||||
|
let (tag, url) = asset(&metadata)?;
|
||||||
|
if repository.url.scheme() == "https" && url.scheme() != "https" {
|
||||||
|
return Err("The plugin ZIP must use HTTPS for this repository.".into());
|
||||||
|
}
|
||||||
|
let bytes = get(
|
||||||
|
&client,
|
||||||
|
url.clone(),
|
||||||
|
&repository.api,
|
||||||
|
authorization,
|
||||||
|
MAX_ARCHIVE,
|
||||||
|
)?;
|
||||||
|
// Query parameters can contain temporary download credentials.
|
||||||
|
let mut display = url;
|
||||||
|
display.set_query(None);
|
||||||
|
Ok(Download {
|
||||||
|
bytes,
|
||||||
|
source: format!("{} @ {}\n{}", repository.url, tag, display),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
pub(crate) mod tests {
|
||||||
|
use super::*;
|
||||||
|
use serde_json::json;
|
||||||
|
use std::{io::Write, net::TcpListener, thread, time::Instant};
|
||||||
|
|
||||||
|
pub fn server(responses: Vec<(String, Vec<u8>)>) -> (String, thread::JoinHandle<Vec<String>>) {
|
||||||
|
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||||
|
listener.set_nonblocking(true).unwrap();
|
||||||
|
let base = format!("http://{}", listener.local_addr().unwrap());
|
||||||
|
let handle = thread::spawn(move || {
|
||||||
|
let mut requests = Vec::new();
|
||||||
|
for (headers, body) in responses {
|
||||||
|
let start = Instant::now();
|
||||||
|
let mut stream = loop {
|
||||||
|
match listener.accept() {
|
||||||
|
Ok((stream, _)) => break stream,
|
||||||
|
Err(error)
|
||||||
|
if error.kind() == std::io::ErrorKind::WouldBlock
|
||||||
|
&& start.elapsed() < Duration::from_secs(15) =>
|
||||||
|
{
|
||||||
|
thread::sleep(Duration::from_millis(10))
|
||||||
|
}
|
||||||
|
Err(error) => panic!("Test server did not receive a request: {error}"),
|
||||||
|
}
|
||||||
|
};
|
||||||
|
stream.set_nonblocking(false).unwrap();
|
||||||
|
stream
|
||||||
|
.set_read_timeout(Some(Duration::from_secs(5)))
|
||||||
|
.unwrap();
|
||||||
|
let mut request = Vec::new();
|
||||||
|
while !request.ends_with(b"\r\n\r\n") {
|
||||||
|
let mut byte = [0];
|
||||||
|
stream.read_exact(&mut byte).unwrap();
|
||||||
|
request.push(byte[0]);
|
||||||
|
assert!(request.len() < 16384);
|
||||||
|
}
|
||||||
|
requests.push(String::from_utf8(request).unwrap());
|
||||||
|
write!(
|
||||||
|
stream,
|
||||||
|
"HTTP/1.1 {headers}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
|
||||||
|
body.len()
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
stream.write_all(&body).unwrap();
|
||||||
|
}
|
||||||
|
requests
|
||||||
|
});
|
||||||
|
(base, handle)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn network_errors_limits_and_redirect_credentials() {
|
||||||
|
let client = Client::builder()
|
||||||
|
.redirect(reqwest::redirect::Policy::none())
|
||||||
|
.build()
|
||||||
|
.unwrap();
|
||||||
|
let (target, target_server) = server(vec![("200 OK".into(), b"zip".to_vec())]);
|
||||||
|
let (origin, origin_server) = server(vec![(
|
||||||
|
format!("302 Found\r\nLocation: {target}/download"),
|
||||||
|
vec![],
|
||||||
|
)]);
|
||||||
|
let url = Url::parse(&origin).unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
get(&client, url.clone(), &url, Some("token secret"), 10).unwrap(),
|
||||||
|
b"zip"
|
||||||
|
);
|
||||||
|
assert!(origin_server.join().unwrap()[0].contains("authorization: token secret"));
|
||||||
|
assert!(!target_server.join().unwrap()[0]
|
||||||
|
.to_lowercase()
|
||||||
|
.contains("authorization:"));
|
||||||
|
for (status, body, limit, message) in [
|
||||||
|
("404 Not Found", vec![], 100, "Release not found"),
|
||||||
|
("403 Forbidden", vec![], 100, "Access denied"),
|
||||||
|
("200 OK", b"12345".to_vec(), 4, "size limit"),
|
||||||
|
(
|
||||||
|
"302 Found\r\nLocation: file:///secret",
|
||||||
|
vec![],
|
||||||
|
100,
|
||||||
|
"HTTP or HTTPS",
|
||||||
|
),
|
||||||
|
] {
|
||||||
|
let (base, handle) = server(vec![(status.into(), body)]);
|
||||||
|
let url = Url::parse(&base).unwrap();
|
||||||
|
assert!(get(&client, url.clone(), &url, None, limit)
|
||||||
|
.unwrap_err()
|
||||||
|
.contains(message));
|
||||||
|
handle.join().unwrap();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn repository_routes_and_tags() {
|
||||||
|
let cases = [
|
||||||
|
(
|
||||||
|
"https://git.example/owner/demo.git/",
|
||||||
|
"",
|
||||||
|
"https://git.example/api/v1/repos/owner/demo/releases/latest",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"http://localhost:6610/group/demo",
|
||||||
|
"trial/1",
|
||||||
|
"http://localhost:6610/api/v1/repos/group/demo/releases/tags/trial%2F1",
|
||||||
|
),
|
||||||
|
];
|
||||||
|
for (url, tag, expected) in cases {
|
||||||
|
assert_eq!(Repository::parse(url, tag).unwrap().api.as_str(), expected);
|
||||||
|
}
|
||||||
|
for bad in [
|
||||||
|
"file:///tmp/plugin",
|
||||||
|
"git@example:owner/demo",
|
||||||
|
"https://user:secret@example/a/b",
|
||||||
|
"https://example/a/b?token=secret",
|
||||||
|
"https://example/a/b/tree/main",
|
||||||
|
"https://example/a/b#main",
|
||||||
|
] {
|
||||||
|
assert!(Repository::parse(bad, "").is_err(), "{bad}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn release_assets_are_explicit_and_unambiguous() {
|
||||||
|
let zip = json!({"name":"org.test.demo-1.0.0.zip", "browser_download_url":"https://example/demo.zip"});
|
||||||
|
assert!(asset(&json!({"tag_name":"v1", "assets":[zip.clone()]})).is_ok());
|
||||||
|
assert!(asset(
|
||||||
|
&json!({"tag_name":"v1", "zipball_url":"https://example/source.zip", "assets":[]})
|
||||||
|
)
|
||||||
|
.is_err());
|
||||||
|
assert!(asset(&json!({"tag_name":"v1", "assets":[zip.clone(),zip.clone()]})).is_err());
|
||||||
|
assert!(asset(&json!({"tag_name":"v1", "draft":true, "assets":[zip]})).is_err());
|
||||||
|
assert!(read_limited(&b"12345"[..], 4).is_err());
|
||||||
|
assert_eq!(read_limited(&b"1234"[..], 4).unwrap(), b"1234");
|
||||||
|
}
|
||||||
|
}
|
||||||
+272
-53
@@ -6,7 +6,7 @@ use std::{
|
|||||||
io::Read,
|
io::Read,
|
||||||
path::{Path, PathBuf},
|
path::{Path, PathBuf},
|
||||||
sync::Mutex,
|
sync::Mutex,
|
||||||
time::{Duration, Instant},
|
time::{Duration, Instant, SystemTime, UNIX_EPOCH},
|
||||||
};
|
};
|
||||||
use tauri::{AppHandle, Emitter, Manager, State};
|
use tauri::{AppHandle, Emitter, Manager, State};
|
||||||
use tauri_plugin_dialog::DialogExt;
|
use tauri_plugin_dialog::DialogExt;
|
||||||
@@ -44,6 +44,8 @@ struct Installed {
|
|||||||
hash: String,
|
hash: String,
|
||||||
enabled: bool,
|
enabled: bool,
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
|
installed_at: Option<u64>,
|
||||||
|
#[serde(default)]
|
||||||
removal: Option<String>,
|
removal: Option<String>,
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
removal_files: BTreeMap<String, String>,
|
removal_files: BTreeMap<String, String>,
|
||||||
@@ -59,6 +61,7 @@ pub struct PluginRow {
|
|||||||
pub manifest: Manifest,
|
pub manifest: Manifest,
|
||||||
pub hash: String,
|
pub hash: String,
|
||||||
pub enabled: bool,
|
pub enabled: bool,
|
||||||
|
pub installed_at: Option<u64>,
|
||||||
pub path: String,
|
pub path: String,
|
||||||
pub error: Option<String>,
|
pub error: Option<String>,
|
||||||
pub removal: bool,
|
pub removal: bool,
|
||||||
@@ -77,7 +80,7 @@ pub struct CandidateRow {
|
|||||||
}
|
}
|
||||||
struct Candidate {
|
struct Candidate {
|
||||||
owner: String,
|
owner: String,
|
||||||
source: PathBuf,
|
source: Option<PathBuf>,
|
||||||
directory: PathBuf,
|
directory: PathBuf,
|
||||||
hash: String,
|
hash: String,
|
||||||
manifest: Manifest,
|
manifest: Manifest,
|
||||||
@@ -267,11 +270,6 @@ fn tree_hash(path: &Path) -> Result<String> {
|
|||||||
Ok(fingerprint(&directory_files(path)?))
|
Ok(fingerprint(&directory_files(path)?))
|
||||||
}
|
}
|
||||||
fn package(source: &Path) -> Result<Package> {
|
fn package(source: &Path) -> Result<Package> {
|
||||||
let source = if source.file_name().is_some_and(|n| n == "plugin.json") {
|
|
||||||
source.parent().ok_or("Missing plugin folder.")?
|
|
||||||
} else {
|
|
||||||
source
|
|
||||||
};
|
|
||||||
let mut files = BTreeMap::new();
|
let mut files = BTreeMap::new();
|
||||||
let mut names = BTreeSet::new();
|
let mut names = BTreeSet::new();
|
||||||
let mut total = 0;
|
let mut total = 0;
|
||||||
@@ -279,9 +277,7 @@ fn package(source: &Path) -> Result<Package> {
|
|||||||
if meta.is_dir() {
|
if meta.is_dir() {
|
||||||
walk(source, source, &mut files, &mut names, &mut total, &mut 0)?;
|
walk(source, source, &mut files, &mut names, &mut total, &mut 0)?;
|
||||||
} else {
|
} else {
|
||||||
if source.extension().and_then(|s| s.to_str()) != Some("runestone-plugin") {
|
require_zip(source)?;
|
||||||
return Err("Select a .runestone-plugin package or plugin.json.".into());
|
|
||||||
}
|
|
||||||
if meta.len() > MAX_TOTAL as u64 {
|
if meta.len() > MAX_TOTAL as u64 {
|
||||||
return Err("The archive exceeds 100 MiB.".into());
|
return Err("The archive exceeds 100 MiB.".into());
|
||||||
}
|
}
|
||||||
@@ -369,6 +365,19 @@ fn package(source: &Path) -> Result<Package> {
|
|||||||
hash,
|
hash,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
fn require_zip(source: &Path) -> Result<()> {
|
||||||
|
if !source
|
||||||
|
.extension()
|
||||||
|
.and_then(|s| s.to_str())
|
||||||
|
.is_some_and(|s| s.eq_ignore_ascii_case("zip"))
|
||||||
|
|| !plain(source)?.is_file()
|
||||||
|
{
|
||||||
|
return Err(
|
||||||
|
"Select a plugin .zip file. The archive must contain plugin.json at its root.".into(),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
fn safe_child(parent: &Path, child: &Path) -> Result<()> {
|
fn safe_child(parent: &Path, child: &Path) -> Result<()> {
|
||||||
plain(parent)?;
|
plain(parent)?;
|
||||||
plain(child)?;
|
plain(child)?;
|
||||||
@@ -517,6 +526,7 @@ impl Service {
|
|||||||
manifest,
|
manifest,
|
||||||
hash,
|
hash,
|
||||||
enabled: record.enabled && error.is_none() && !self.removing.contains_key(id),
|
enabled: record.enabled && error.is_none() && !self.removing.contains_key(id),
|
||||||
|
installed_at: record.installed_at,
|
||||||
path: path.to_string_lossy().into_owned(),
|
path: path.to_string_lossy().into_owned(),
|
||||||
error,
|
error,
|
||||||
removal: record.removal.is_some(),
|
removal: record.removal.is_some(),
|
||||||
@@ -543,6 +553,7 @@ impl Service {
|
|||||||
manifest: current.manifest,
|
manifest: current.manifest,
|
||||||
hash: current.hash,
|
hash: current.hash,
|
||||||
enabled: false,
|
enabled: false,
|
||||||
|
installed_at: None,
|
||||||
removal: None,
|
removal: None,
|
||||||
removal_files: BTreeMap::new(),
|
removal_files: BTreeMap::new(),
|
||||||
},
|
},
|
||||||
@@ -609,7 +620,7 @@ impl Service {
|
|||||||
token.clone(),
|
token.clone(),
|
||||||
Candidate {
|
Candidate {
|
||||||
owner: owner.into(),
|
owner: owner.into(),
|
||||||
source,
|
source: Some(source),
|
||||||
directory: staging,
|
directory: staging,
|
||||||
hash: current.hash,
|
hash: current.hash,
|
||||||
manifest: manifest.clone(),
|
manifest: manifest.clone(),
|
||||||
@@ -641,6 +652,22 @@ impl Service {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
fn inspect_download(&mut self, owner: &str, download: crate::plugin_sources::Download) -> Result<CandidateRow> {
|
||||||
|
let parent = self.directory("plugin-staging")?;
|
||||||
|
let archive = parent.join(format!("{}.zip", uid()));
|
||||||
|
fs::write(&archive, download.bytes).map_err(fail)?;
|
||||||
|
let mut row = self.inspect(owner, archive.clone());
|
||||||
|
if let Some(candidate) = self.candidates.get_mut(&row.token) {
|
||||||
|
// Review pins the downloaded bytes. Remote releases can change independently.
|
||||||
|
candidate.source = None;
|
||||||
|
}
|
||||||
|
row.source = download.source;
|
||||||
|
if let Err(error) = erase(&parent, &archive) {
|
||||||
|
if let Some(candidate) = self.candidates.remove(&row.token) { let _ = erase(&parent, &candidate.directory); }
|
||||||
|
return Err(error);
|
||||||
|
}
|
||||||
|
Ok(row)
|
||||||
|
}
|
||||||
fn install(&mut self, owner: &str, token: &str, enabled: bool) -> Result<String> {
|
fn install(&mut self, owner: &str, token: &str, enabled: bool) -> Result<String> {
|
||||||
let candidate = self
|
let candidate = self
|
||||||
.candidates
|
.candidates
|
||||||
@@ -653,7 +680,7 @@ impl Service {
|
|||||||
if self.catalog.plugins.contains_key(&id) {
|
if self.catalog.plugins.contains_key(&id) {
|
||||||
return Err("This plugin ID is already installed.".into());
|
return Err("This plugin ID is already installed.".into());
|
||||||
}
|
}
|
||||||
if package(&candidate.source)?.hash != candidate.hash
|
if candidate.source.as_ref().map(|source| package(source)).transpose()?.is_some_and(|source| source.hash != candidate.hash)
|
||||||
|| package(&candidate.directory)?.hash != candidate.hash
|
|| package(&candidate.directory)?.hash != candidate.hash
|
||||||
{
|
{
|
||||||
return Err("The package changed after review. Select it again.".into());
|
return Err("The package changed after review. Select it again.".into());
|
||||||
@@ -664,6 +691,10 @@ impl Service {
|
|||||||
return Err("The plugin directory already exists.".into());
|
return Err("The plugin directory already exists.".into());
|
||||||
}
|
}
|
||||||
safe_child(&self.directory("plugin-staging")?, &candidate.directory)?;
|
safe_child(&self.directory("plugin-staging")?, &candidate.directory)?;
|
||||||
|
let installed_at = SystemTime::now()
|
||||||
|
.duration_since(UNIX_EPOCH)
|
||||||
|
.map_err(fail)?
|
||||||
|
.as_millis() as u64;
|
||||||
// Persist disabled first. A crash cannot enable unreviewed or partial code.
|
// Persist disabled first. A crash cannot enable unreviewed or partial code.
|
||||||
self.catalog.plugins.insert(
|
self.catalog.plugins.insert(
|
||||||
id.clone(),
|
id.clone(),
|
||||||
@@ -671,6 +702,7 @@ impl Service {
|
|||||||
manifest: candidate.manifest.clone(),
|
manifest: candidate.manifest.clone(),
|
||||||
hash: candidate.hash.clone(),
|
hash: candidate.hash.clone(),
|
||||||
enabled: false,
|
enabled: false,
|
||||||
|
installed_at: Some(installed_at),
|
||||||
removal: None,
|
removal: None,
|
||||||
removal_files: BTreeMap::new(),
|
removal_files: BTreeMap::new(),
|
||||||
},
|
},
|
||||||
@@ -874,61 +906,56 @@ pub async fn plugins_snapshot(app: AppHandle, state: State<'_, PluginState>) ->
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
pub async fn plugins_choose(
|
pub async fn plugins_choose(app: AppHandle, window: tauri::Window) -> Result<Vec<CandidateRow>> {
|
||||||
app: AppHandle,
|
|
||||||
window: tauri::Window,
|
|
||||||
folder: bool,
|
|
||||||
) -> Result<Vec<CandidateRow>> {
|
|
||||||
let picker_app = app.clone();
|
let picker_app = app.clone();
|
||||||
let source = tauri::async_runtime::spawn_blocking(move || {
|
let source = tauri::async_runtime::spawn_blocking(move || {
|
||||||
let picker = picker_app
|
picker_app
|
||||||
.dialog()
|
.dialog()
|
||||||
.file()
|
.file()
|
||||||
.set_title("Install RuneStone plugins");
|
.set_title("Install plugin ZIP")
|
||||||
if folder {
|
.add_filter("Plugin ZIP archives", &["zip"])
|
||||||
picker.blocking_pick_folder()
|
.blocking_pick_files()
|
||||||
} else {
|
|
||||||
picker
|
|
||||||
.add_filter("RuneStone plugins", &["runestone-plugin", "json"])
|
|
||||||
.blocking_pick_file()
|
|
||||||
}
|
|
||||||
})
|
})
|
||||||
.await
|
.await
|
||||||
.map_err(fail)?;
|
.map_err(fail)?;
|
||||||
let Some(source) = source else {
|
let Some(sources) = source else {
|
||||||
return Ok(Vec::new());
|
return Ok(Vec::new());
|
||||||
};
|
};
|
||||||
let source = source.into_path().map_err(fail)?;
|
if sources.len() > 100 {
|
||||||
|
return Err("Select at most 100 plugin ZIP files.".into());
|
||||||
|
}
|
||||||
|
let paths: Vec<PathBuf> = sources
|
||||||
|
.into_iter()
|
||||||
|
.map(|source| source.into_path().map_err(fail))
|
||||||
|
.collect::<Result<_>>()?;
|
||||||
|
for path in &paths {
|
||||||
|
require_zip(path)?;
|
||||||
|
}
|
||||||
app.state::<PluginState>().with(&app, |service| {
|
app.state::<PluginState>().with(&app, |service| {
|
||||||
let mut paths = Vec::new();
|
|
||||||
if source.is_dir() && !source.join("plugin.json").exists() {
|
|
||||||
plain(&source)?;
|
|
||||||
for (index, entry) in fs::read_dir(&source).map_err(fail)?.enumerate() {
|
|
||||||
if index >= 100 {
|
|
||||||
return Err("Choose a collection with at most 100 entries.".into());
|
|
||||||
}
|
|
||||||
let path = entry.map_err(fail)?.path();
|
|
||||||
if path.is_dir()
|
|
||||||
|| path.extension().and_then(|n| n.to_str()) == Some("runestone-plugin")
|
|
||||||
{
|
|
||||||
paths.push(path);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if paths.len() > 100 {
|
|
||||||
return Err("Choose a collection with at most 100 plugins.".into());
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
paths.push(source);
|
|
||||||
}
|
|
||||||
if paths.is_empty() {
|
|
||||||
return Err("No plugin packages or folders were found.".into());
|
|
||||||
}
|
|
||||||
Ok(paths
|
Ok(paths
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.map(|path| service.inspect(window.label(), path))
|
.map(|path| service.inspect(window.label(), path))
|
||||||
.collect())
|
.collect())
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn plugins_from_git(
|
||||||
|
app: AppHandle,
|
||||||
|
window: tauri::Window,
|
||||||
|
url: String,
|
||||||
|
tag: String,
|
||||||
|
token: Option<String>,
|
||||||
|
) -> Result<Vec<CandidateRow>> {
|
||||||
|
let repository = crate::plugin_sources::Repository::parse(&url, &tag)?;
|
||||||
|
// Network access never holds the plugin service lock.
|
||||||
|
let download = tauri::async_runtime::spawn_blocking(move || {
|
||||||
|
crate::plugin_sources::download(&repository, token.as_deref())
|
||||||
|
}).await.map_err(fail)??;
|
||||||
|
app.state::<PluginState>().with(&app, |service| {
|
||||||
|
Ok(vec![service.inspect_download(window.label(), download)?])
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
pub async fn plugins_cancel(
|
pub async fn plugins_cancel(
|
||||||
app: AppHandle,
|
app: AppHandle,
|
||||||
@@ -1263,11 +1290,203 @@ mod tests {
|
|||||||
}
|
}
|
||||||
zip.finish().unwrap();
|
zip.finish().unwrap();
|
||||||
}
|
}
|
||||||
|
fn review_remote(fixture: &mut Fixture, bytes: Vec<u8>) -> CandidateRow {
|
||||||
|
use crate::plugin_sources::{tests::server, Repository};
|
||||||
|
let (asset_url, asset_server) = server(vec![("200 OK".into(), bytes)]);
|
||||||
|
let metadata = serde_json::json!({"tag_name":"trial-1", "assets":[{
|
||||||
|
"name":"plugin.zip", "browser_download_url":format!("{asset_url}/plugin.zip")
|
||||||
|
}]});
|
||||||
|
let (base, metadata_server) = server(vec![("200 OK".into(), serde_json::to_vec(&metadata).unwrap())]);
|
||||||
|
let repository = Repository::parse(&format!("{base}/owner/plugin.git"), "trial-1").unwrap();
|
||||||
|
let download = crate::plugin_sources::download(&repository, Some("test-token")).unwrap();
|
||||||
|
let requests = metadata_server.join().unwrap();
|
||||||
|
assert!(requests[0].starts_with("GET /api/v1/repos/owner/plugin/releases/tags/trial-1 "));
|
||||||
|
assert!(requests[0].contains("authorization: token test-token"));
|
||||||
|
assert!(!asset_server.join().unwrap()[0].contains("test-token"));
|
||||||
|
fixture.service.inspect_download("main", download).unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn remote_download_uses_review_and_package_checks() {
|
||||||
|
let mut f = Fixture::new();
|
||||||
|
let archive_path = f.root.join("demo.zip");
|
||||||
|
let manifest = fs::read(f.source.join("plugin.json")).unwrap();
|
||||||
|
archive(&archive_path, &[("plugin.json", &manifest), ("main.js", b"export function activate() {}")]);
|
||||||
|
let bytes = fs::read(&archive_path).unwrap();
|
||||||
|
let candidate = review_remote(&mut f, bytes.clone());
|
||||||
|
assert!(candidate.error.is_none(), "{:?}", candidate.error);
|
||||||
|
assert!(candidate.source.contains("trial-1"));
|
||||||
|
assert!(f.service.candidates[&candidate.token].source.is_none());
|
||||||
|
assert!(f.service.install("other-window", &candidate.token, false).is_err());
|
||||||
|
let staging = f.service.candidates[&candidate.token].directory.clone();
|
||||||
|
fs::write(staging.join("main.js"), "changed").unwrap();
|
||||||
|
assert!(f.service.install("main", &candidate.token, false).is_err());
|
||||||
|
let candidate = review_remote(&mut f, bytes);
|
||||||
|
let id = candidate.manifest.as_ref().unwrap().id.clone();
|
||||||
|
f.service.install("main", &candidate.token, false).unwrap();
|
||||||
|
assert!(!f.service.row(&id).unwrap().enabled);
|
||||||
|
assert!(f.service.install("main", &candidate.token, false).is_err());
|
||||||
|
let invalid = review_remote(&mut f, b"not a zip".to_vec());
|
||||||
|
assert!(invalid.error.is_some());
|
||||||
|
archive(&archive_path, &[("../outside", b"bad")]);
|
||||||
|
let invalid = review_remote(&mut f, fs::read(&archive_path).unwrap());
|
||||||
|
assert!(invalid.error.is_some());
|
||||||
|
assert!(!f.root.join("outside").exists());
|
||||||
|
assert!(fs::read_dir(f.service.directory("plugin-staging").unwrap()).unwrap()
|
||||||
|
.all(|entry| entry.unwrap().path().extension().is_none_or(|ext| ext != "zip")));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
#[ignore = "Set RUNESTONE_GIT_TRIAL_PACKAGES to the folder with the four trial ZIPs."]
|
||||||
|
fn four_plugin_release_trial() {
|
||||||
|
let directory = PathBuf::from(std::env::var("RUNESTONE_GIT_TRIAL_PACKAGES").unwrap());
|
||||||
|
let archives: Vec<_> = fs::read_dir(directory).unwrap().map(|entry| entry.unwrap().path())
|
||||||
|
.filter(|path| path.extension().is_some_and(|ext| ext == "zip")).collect();
|
||||||
|
assert_eq!(archives.len(), 4);
|
||||||
|
let mut f = Fixture::new();
|
||||||
|
let mut ids = BTreeSet::new();
|
||||||
|
for path in archives {
|
||||||
|
let expected = package(&path).unwrap();
|
||||||
|
let candidate = review_remote(&mut f, fs::read(&path).unwrap());
|
||||||
|
assert!(candidate.error.is_none(), "{:?}", candidate.error);
|
||||||
|
let id = candidate.manifest.as_ref().unwrap().id.clone();
|
||||||
|
f.service.install("main", &candidate.token, false).unwrap();
|
||||||
|
assert_eq!(f.service.row(&id).unwrap().hash, expected.hash);
|
||||||
|
assert!(!f.service.row(&id).unwrap().enabled);
|
||||||
|
println!("Release download, review, and isolated install passed: {} {}", id, expected.manifest.version);
|
||||||
|
ids.insert(id);
|
||||||
|
}
|
||||||
|
assert_eq!(ids.len(), 4);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
#[ignore = "Requires an approved live Gitea release and repository read access."]
|
||||||
|
fn live_gitea_release_trial() {
|
||||||
|
let repository = crate::plugin_sources::Repository::parse(
|
||||||
|
&std::env::var("RUNESTONE_GIT_TRIAL_URL").unwrap(),
|
||||||
|
&std::env::var("RUNESTONE_GIT_TRIAL_TAG").unwrap(),
|
||||||
|
).unwrap();
|
||||||
|
let token = std::env::var("RUNESTONE_GIT_TRIAL_TOKEN").ok();
|
||||||
|
let download = crate::plugin_sources::download(&repository, token.as_deref()).unwrap();
|
||||||
|
let expected = package(&PathBuf::from(std::env::var("RUNESTONE_GIT_TRIAL_ZIP").unwrap())).unwrap();
|
||||||
|
let mut f = Fixture::new();
|
||||||
|
let candidate = f.service.inspect_download("main", download).unwrap();
|
||||||
|
assert!(candidate.error.is_none(), "{:?}", candidate.error);
|
||||||
|
let id = candidate.manifest.as_ref().unwrap().id.clone();
|
||||||
|
f.service.install("main", &candidate.token, false).unwrap();
|
||||||
|
assert_eq!(f.service.row(&id).unwrap().hash, expected.hash);
|
||||||
|
assert!(!f.service.row(&id).unwrap().enabled);
|
||||||
|
println!("Live Gitea download, review, and isolated install passed: {} {}", id, expected.manifest.version);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn install_time_survives_reload_and_state_changes() {
|
||||||
|
let mut f = Fixture::new();
|
||||||
|
let before = SystemTime::now()
|
||||||
|
.duration_since(UNIX_EPOCH)
|
||||||
|
.unwrap()
|
||||||
|
.as_millis() as u64;
|
||||||
|
let id = f.install(false);
|
||||||
|
let after = SystemTime::now()
|
||||||
|
.duration_since(UNIX_EPOCH)
|
||||||
|
.unwrap()
|
||||||
|
.as_millis() as u64;
|
||||||
|
let installed_at = f.service.row(&id).unwrap().installed_at.unwrap();
|
||||||
|
assert!((before..=after).contains(&installed_at));
|
||||||
|
let mut reopened = Service::open(f.root.join("app")).unwrap();
|
||||||
|
reopened.catalog.plugins.get_mut(&id).unwrap().enabled = true;
|
||||||
|
reopened.persist().unwrap();
|
||||||
|
let mut reopened = Service::open(f.root.join("app")).unwrap();
|
||||||
|
let snapshot = serde_json::to_value(reopened.snapshot().unwrap()).unwrap();
|
||||||
|
assert_eq!(snapshot["plugins"][0]["installedAt"], installed_at);
|
||||||
|
let plan = reopened.prepare("main", &id).unwrap();
|
||||||
|
assert_eq!(plan.plugin.installed_at, Some(installed_at));
|
||||||
|
reopened.begin_remove("main", &plan.token).unwrap();
|
||||||
|
reopened.finish_remove(&id).unwrap();
|
||||||
|
assert!(!reopened.catalog.plugins.contains_key(&id));
|
||||||
|
f.service = reopened;
|
||||||
|
f.install(true);
|
||||||
|
assert!(f.service.row(&id).unwrap().installed_at.unwrap() >= installed_at);
|
||||||
|
}
|
||||||
|
#[test]
|
||||||
|
fn legacy_and_discovered_plugins_keep_unknown_install_times() {
|
||||||
|
let mut f = Fixture::new();
|
||||||
|
let id = f.install(false);
|
||||||
|
let path = f.root.join("app/plugin-state.json");
|
||||||
|
let mut catalog = serde_json::to_value(&f.service.catalog).unwrap();
|
||||||
|
catalog["plugins"][&id]
|
||||||
|
.as_object_mut()
|
||||||
|
.unwrap()
|
||||||
|
.remove("installedAt");
|
||||||
|
fs::write(&path, serde_json::to_vec(&catalog).unwrap()).unwrap();
|
||||||
|
let mut reopened = Service::open(f.root.join("app")).unwrap();
|
||||||
|
assert_eq!(reopened.snapshot().unwrap().plugins[0].installed_at, None);
|
||||||
|
reopened.catalog.plugins.clear();
|
||||||
|
reopened.persist().unwrap();
|
||||||
|
assert_eq!(reopened.snapshot().unwrap().plugins[0].installed_at, None);
|
||||||
|
let mut reopened = Service::open(f.root.join("app")).unwrap();
|
||||||
|
assert_eq!(reopened.snapshot().unwrap().plugins[0].installed_at, None);
|
||||||
|
}
|
||||||
|
#[test]
|
||||||
|
fn installer_accepts_only_zip_files() {
|
||||||
|
let f = Fixture::new();
|
||||||
|
assert!(require_zip(&f.source).is_err());
|
||||||
|
assert!(require_zip(&f.source.join("plugin.json")).is_err());
|
||||||
|
let legacy = f.root.join("demo.runestone-plugin");
|
||||||
|
archive(&legacy, &[("main.js", b"test")]);
|
||||||
|
assert!(require_zip(&legacy).is_err());
|
||||||
|
assert!(package(&legacy).is_err());
|
||||||
|
let upper = f.root.join("demo.ZIP");
|
||||||
|
fs::copy(&legacy, &upper).unwrap();
|
||||||
|
assert!(require_zip(&upper).is_ok());
|
||||||
|
let wrapped = f.root.join("wrapped.zip");
|
||||||
|
archive(&wrapped, &[("demo/plugin.json", b"{}")]);
|
||||||
|
assert!(package(&wrapped).unwrap_err().contains("at its root"));
|
||||||
|
}
|
||||||
|
#[test]
|
||||||
|
fn author_packager_produces_an_installable_repeatable_zip() {
|
||||||
|
let mut f = Fixture::new();
|
||||||
|
fs::create_dir(f.source.join("assets")).unwrap();
|
||||||
|
fs::write(f.source.join("assets/style.css"), "body { color: red; }").unwrap();
|
||||||
|
let script = Path::new(env!("CARGO_MANIFEST_DIR")).join("../scripts/packagePlugin.mjs");
|
||||||
|
let output = f.root.join("releases");
|
||||||
|
let build = || {
|
||||||
|
let result = std::process::Command::new("node")
|
||||||
|
.arg(&script)
|
||||||
|
.arg(&f.source)
|
||||||
|
.arg(&output)
|
||||||
|
.output()
|
||||||
|
.unwrap();
|
||||||
|
assert!(
|
||||||
|
result.status.success(),
|
||||||
|
"{}",
|
||||||
|
String::from_utf8_lossy(&result.stderr)
|
||||||
|
);
|
||||||
|
};
|
||||||
|
build();
|
||||||
|
let path = output.join("org.test.demo-1.0.0.zip");
|
||||||
|
let first = fs::read(&path).unwrap();
|
||||||
|
build();
|
||||||
|
assert_eq!(first, fs::read(&path).unwrap());
|
||||||
|
assert_eq!(
|
||||||
|
package(&path).unwrap().hash,
|
||||||
|
package(&f.source).unwrap().hash
|
||||||
|
);
|
||||||
|
let row = f.service.inspect("main", path);
|
||||||
|
assert!(row.error.is_none(), "{:?}", row.error);
|
||||||
|
f.service.install("main", &row.token, false).unwrap();
|
||||||
|
let installed = f.service.row("org.test.demo").unwrap();
|
||||||
|
assert!(!installed.enabled);
|
||||||
|
assert_eq!(
|
||||||
|
fs::read(Path::new(&installed.path).join("assets/style.css")).unwrap(),
|
||||||
|
b"body { color: red; }"
|
||||||
|
);
|
||||||
|
}
|
||||||
#[test]
|
#[test]
|
||||||
fn installs_directory_and_zip_without_changing_source() {
|
fn installs_directory_and_zip_without_changing_source() {
|
||||||
let mut f = Fixture::new();
|
let mut f = Fixture::new();
|
||||||
let original = package(&f.source).unwrap();
|
let original = package(&f.source).unwrap();
|
||||||
let archive_path = f.root.join("demo.runestone-plugin");
|
let archive_path = f.root.join("demo.zip");
|
||||||
let entries: Vec<_> = original
|
let entries: Vec<_> = original
|
||||||
.files
|
.files
|
||||||
.iter()
|
.iter()
|
||||||
@@ -1336,7 +1555,7 @@ mod tests {
|
|||||||
assert!(!valid_id(id), "{id}");
|
assert!(!valid_id(id), "{id}");
|
||||||
}
|
}
|
||||||
let f = Fixture::new();
|
let f = Fixture::new();
|
||||||
let path = f.root.join("bad.runestone-plugin");
|
let path = f.root.join("bad.zip");
|
||||||
archive(&path, &[("../outside", b"test")]);
|
archive(&path, &[("../outside", b"test")]);
|
||||||
assert!(package(&path).is_err());
|
assert!(package(&path).is_err());
|
||||||
assert!(!f.root.join("outside").exists());
|
assert!(!f.root.join("outside").exists());
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
use std::fs;
|
use std::fs;
|
||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
use std::io::Write;
|
use std::io::{Read, Write};
|
||||||
use std::path::{Path, PathBuf};
|
use std::path::{Path, PathBuf};
|
||||||
use std::sync::Mutex;
|
use std::sync::Mutex;
|
||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
@@ -511,14 +511,43 @@ fn list_entries(root: &Path, rel: &str) -> WsResult<Vec<TreeEntry>> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
pub fn workspace_read(window: tauri::Window, state: State<WorkspaceState>, rel: String) -> WsResult<String> {
|
pub fn workspace_read(window: tauri::Window, state: State<WorkspaceState>, rel: String, missing_ok: Option<bool>) -> WsResult<Option<String>> {
|
||||||
let root = current_root(&state, window.label())?;
|
let root = current_root(&state, window.label())?;
|
||||||
let path = resolve_existing(&root, &rel)?;
|
let path = if missing_ok.unwrap_or(false) { resolve_for_write(&root, &rel)? } else { resolve_existing(&root, &rel)? };
|
||||||
if path.is_dir() {
|
if path.is_dir() {
|
||||||
return Err(err("path is a folder"));
|
return Err(err("path is a folder"));
|
||||||
}
|
}
|
||||||
let bytes = fs::read(&path)?;
|
read_optional_text(&path, missing_ok.unwrap_or(false))
|
||||||
String::from_utf8(bytes).map_err(|_| err("file is not valid UTF-8"))
|
}
|
||||||
|
|
||||||
|
fn read_optional_text(path: &Path, missing_ok: bool) -> WsResult<Option<String>> {
|
||||||
|
match fs::read(path) {
|
||||||
|
Ok(bytes) => String::from_utf8(bytes).map(Some).map_err(|_| err("file is not valid UTF-8")),
|
||||||
|
Err(error) if missing_ok && error.kind() == std::io::ErrorKind::NotFound => Ok(None),
|
||||||
|
Err(error) => Err(error.into()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const MAX_BINARY_BYTES: u64 = 64 * 1024 * 1024;
|
||||||
|
|
||||||
|
fn read_workspace_bytes(root: &Path, rel: &str) -> WsResult<Vec<u8>> {
|
||||||
|
let path = resolve_existing(root, rel)?;
|
||||||
|
let file = fs::File::open(path)?;
|
||||||
|
let metadata = file.metadata()?;
|
||||||
|
if !metadata.is_file() { return Err(err("The path must be a file.")); }
|
||||||
|
if metadata.len() > MAX_BINARY_BYTES { return Err(err("The file exceeds the 64 MiB limit.")); }
|
||||||
|
let mut bytes = Vec::new();
|
||||||
|
file.take(MAX_BINARY_BYTES + 1).read_to_end(&mut bytes)?;
|
||||||
|
if bytes.len() as u64 > MAX_BINARY_BYTES { return Err(err("The file exceeds the 64 MiB limit.")); }
|
||||||
|
Ok(bytes)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn workspace_read_bytes(window: tauri::Window, state: State<'_, WorkspaceState>, rel: String) -> WsResult<tauri::ipc::Response> {
|
||||||
|
let root = current_root(&state, window.label())?;
|
||||||
|
let bytes = tauri::async_runtime::spawn_blocking(move || read_workspace_bytes(&root, &rel))
|
||||||
|
.await.map_err(|e| err(e.to_string()))??;
|
||||||
|
Ok(tauri::ipc::Response::new(bytes))
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
@@ -590,7 +619,7 @@ fn is_internal_name(name: &str) -> bool {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
pub fn workspace_create(window: tauri::Window, state: State<WorkspaceState>, rel: String, kind: String) -> WsResult<()> {
|
pub fn workspace_create(window: tauri::Window, state: State<WorkspaceState>, rel: String, kind: String, contents: Option<String>) -> WsResult<()> {
|
||||||
let root = current_root(&state, window.label())?;
|
let root = current_root(&state, window.label())?;
|
||||||
let path = resolve_for_write(&root, &rel)?;
|
let path = resolve_for_write(&root, &rel)?;
|
||||||
if path.exists() {
|
if path.exists() {
|
||||||
@@ -598,6 +627,8 @@ pub fn workspace_create(window: tauri::Window, state: State<WorkspaceState>, rel
|
|||||||
}
|
}
|
||||||
if kind == "folder" {
|
if kind == "folder" {
|
||||||
fs::create_dir_all(&path)?;
|
fs::create_dir_all(&path)?;
|
||||||
|
} else if let Some(contents) = contents {
|
||||||
|
create_text_if_absent(&path, &contents)?;
|
||||||
} else {
|
} else {
|
||||||
if let Some(parent) = path.parent() {
|
if let Some(parent) = path.parent() {
|
||||||
fs::create_dir_all(parent)?;
|
fs::create_dir_all(parent)?;
|
||||||
@@ -610,6 +641,24 @@ pub fn workspace_create(window: tauri::Window, state: State<WorkspaceState>, rel
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Publish a complete file without replacing a destination created by another writer.
|
||||||
|
fn create_text_if_absent(path: &Path, contents: &str) -> WsResult<()> {
|
||||||
|
static NEXT_CREATE: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
|
||||||
|
let parent = path.parent().ok_or_else(|| err("file has no parent"))?;
|
||||||
|
fs::create_dir_all(parent)?;
|
||||||
|
let temp = parent.join(format!(".runestone-save-create-{}-{}", std::process::id(), NEXT_CREATE.fetch_add(1, std::sync::atomic::Ordering::Relaxed)));
|
||||||
|
let mut file = fs::OpenOptions::new().write(true).create_new(true).open(&temp)?;
|
||||||
|
let result = (|| -> WsResult<()> {
|
||||||
|
file.write_all(contents.as_bytes())?;
|
||||||
|
file.sync_all()?;
|
||||||
|
drop(file);
|
||||||
|
fs::hard_link(&temp, path)?;
|
||||||
|
Ok(())
|
||||||
|
})();
|
||||||
|
let _ = fs::remove_file(&temp);
|
||||||
|
result
|
||||||
|
}
|
||||||
|
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
pub fn workspace_rename(window: tauri::Window, state: State<WorkspaceState>, from: String, to: String) -> WsResult<()> {
|
pub fn workspace_rename(window: tauri::Window, state: State<WorkspaceState>, from: String, to: String) -> WsResult<()> {
|
||||||
let root = current_root(&state, window.label())?;
|
let root = current_root(&state, window.label())?;
|
||||||
@@ -887,6 +936,42 @@ mod tests {
|
|||||||
use super::*;
|
use super::*;
|
||||||
use std::path::PathBuf;
|
use std::path::PathBuf;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn binary_reads_preserve_bytes_and_enforce_workspace_and_size_limits() {
|
||||||
|
let fixture = std::env::temp_dir().join(format!("rs-binary-{}", std::process::id()));
|
||||||
|
let root = fixture.join("workspace");
|
||||||
|
fs::create_dir_all(&root).unwrap();
|
||||||
|
let root = dunce::canonicalize(root).unwrap();
|
||||||
|
let bytes = b"%PDF-1.7\n\xff\x00\xfe";
|
||||||
|
fs::write(root.join("test.pdf"), bytes).unwrap();
|
||||||
|
fs::write(fixture.join("outside.pdf"), bytes).unwrap();
|
||||||
|
assert_eq!(read_workspace_bytes(&root, "test.pdf").unwrap(), bytes);
|
||||||
|
assert!(read_workspace_bytes(&root, "../outside.pdf").is_err());
|
||||||
|
assert!(read_workspace_bytes(&root, &fixture.join("outside.pdf").to_string_lossy()).is_err());
|
||||||
|
assert!(read_workspace_bytes(&root, "").is_err());
|
||||||
|
assert!(read_workspace_bytes(&root, "missing.pdf").is_err());
|
||||||
|
fs::File::create(root.join("large.pdf")).unwrap().set_len(MAX_BINARY_BYTES + 1).unwrap();
|
||||||
|
assert!(read_workspace_bytes(&root, "large.pdf").unwrap_err().to_string().contains("64 MiB"));
|
||||||
|
fs::remove_dir_all(fixture).unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn plugin_files_publish_complete_text_without_overwriting() {
|
||||||
|
let root = std::env::temp_dir().join(format!("rs-plugin-create-{}", std::process::id()));
|
||||||
|
fs::create_dir_all(&root).unwrap();
|
||||||
|
let path = root.join("note.md");
|
||||||
|
assert_eq!(read_optional_text(&path, true).unwrap(), None);
|
||||||
|
assert!(read_optional_text(&path, false).is_err());
|
||||||
|
create_text_if_absent(&path, "complete note\n").unwrap();
|
||||||
|
assert_eq!(read_optional_text(&path, true).unwrap().as_deref(), Some("complete note\n"));
|
||||||
|
assert!(create_text_if_absent(&path, "replacement").is_err());
|
||||||
|
assert_eq!(fs::read_to_string(&path).unwrap(), "complete note\n");
|
||||||
|
assert_eq!(fs::read_dir(&root).unwrap().count(), 1);
|
||||||
|
assert!(read_optional_text(&root, true).is_err());
|
||||||
|
fs::remove_file(path).unwrap();
|
||||||
|
fs::remove_dir(root).unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn ignore_files_do_not_hide_workspace_entries_or_search_results() {
|
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 fixture = std::env::temp_dir().join(format!("rs-ignore-rules-{}", std::process::id()));
|
||||||
|
|||||||
@@ -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.4",
|
"version": "0.1.7",
|
||||||
"identifier": "com.runestone.app",
|
"identifier": "com.runestone.app",
|
||||||
"build": {
|
"build": {
|
||||||
"beforeDevCommand": "pnpm dev",
|
"beforeDevCommand": "pnpm dev",
|
||||||
|
|||||||
+3
-7
@@ -1,4 +1,5 @@
|
|||||||
@import "./lib/theme/tokens.css";
|
@import "./lib/theme/tokens.css";
|
||||||
|
@import "./lib/ui/menu.css";
|
||||||
|
|
||||||
*,
|
*,
|
||||||
*::before,
|
*::before,
|
||||||
@@ -244,6 +245,8 @@ button:disabled {
|
|||||||
.table-edit-help { font: inherit; color: var(--rs-text-dim); }
|
.table-edit-help { font: inherit; color: var(--rs-text-dim); }
|
||||||
.reading table { border-collapse: collapse; width: 100%; font-size: 0.9em; overflow-wrap: normal; word-break: normal; }
|
.reading table { border-collapse: collapse; width: 100%; font-size: 0.9em; overflow-wrap: normal; word-break: normal; }
|
||||||
.reading th, .reading td { padding: 10px 14px; text-align: left; vertical-align: top; border-bottom: 1px solid var(--rs-border); min-width: 8rem; max-width: 26rem; white-space: normal; overflow-wrap: break-word; }
|
.reading th, .reading td { padding: 10px 14px; text-align: left; vertical-align: top; border-bottom: 1px solid var(--rs-border); min-width: 8rem; max-width: 26rem; white-space: normal; overflow-wrap: break-word; }
|
||||||
|
.reading :is(th, td):empty::before,
|
||||||
|
.reading :is(th, td) > p:empty::before { content: "\200b"; }
|
||||||
.reading th { background: var(--rs-bg-active); font-weight: 600; color: var(--rs-text-strong); }
|
.reading th { background: var(--rs-bg-active); font-weight: 600; color: var(--rs-text-strong); }
|
||||||
.reading tbody tr:nth-child(even) { background: var(--rs-line-highlight); }
|
.reading tbody tr:nth-child(even) { background: var(--rs-line-highlight); }
|
||||||
.reading tbody tr:last-child td { border-bottom: 0; }
|
.reading tbody tr:last-child td { border-bottom: 0; }
|
||||||
@@ -375,19 +378,12 @@ button:disabled {
|
|||||||
.table-drag-preview p { margin: 0; }
|
.table-drag-preview p { margin: 0; }
|
||||||
@keyframes table-drag-lift { from { opacity: 0; } to { opacity: .92; } }
|
@keyframes table-drag-lift { from { opacity: 0; } to { opacity: .92; } }
|
||||||
@media (prefers-reduced-motion: reduce) { .table-drag-handle { transition: none; } .table-drag-preview { animation: none; } }
|
@media (prefers-reduced-motion: reduce) { .table-drag-handle { transition: none; } .table-drag-preview { animation: none; } }
|
||||||
.table-cell-menu { position: fixed; z-index: 1000; width: 264px; max-width: calc(100vw - 16px); max-height: calc(100vh - 16px); overflow-y: auto; padding: 5px; border: 1px solid var(--rs-border); border-radius: 8px; background: var(--rs-bg-elevated); color: var(--rs-text); box-shadow: 0 8px 30px #0006; font: 13px/1.4 var(--rs-font-ui); }
|
|
||||||
.editor-notice { position: absolute; bottom: 12px; left: 12px; right: 12px; z-index: 20; margin: 0; padding: 10px 14px; border: 1px solid var(--rs-border); border-radius: 6px; background: var(--rs-bg-elevated); color: var(--rs-text); }
|
.editor-notice { position: absolute; bottom: 12px; left: 12px; right: 12px; z-index: 20; margin: 0; padding: 10px 14px; border: 1px solid var(--rs-border); border-radius: 6px; background: var(--rs-bg-elevated); color: var(--rs-text); }
|
||||||
.editor-notice button { margin-left: 12px; }
|
.editor-notice button { margin-left: 12px; }
|
||||||
.table-cell-menu button { display: flex; align-items: center; gap: 10px; width: 100%; padding: 6px 10px; border: 0; border-radius: 4px; background: transparent; color: inherit; font: inherit; text-align: left; cursor: pointer; }
|
|
||||||
.table-cell-menu button:disabled { opacity: .4; cursor: default; }
|
|
||||||
.table-cell-menu button:disabled:hover { background: transparent; }
|
|
||||||
.action-icon { width: 17px; height: 17px; flex: 0 0 17px; fill: none; stroke: currentColor; stroke-width: 1.6; stroke-linecap: round; stroke-linejoin: round; }
|
.action-icon { width: 17px; height: 17px; flex: 0 0 17px; fill: none; stroke: currentColor; stroke-width: 1.6; stroke-linecap: round; stroke-linejoin: round; }
|
||||||
.action-label { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
.action-label { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||||
.action-chevron { width: 13px; height: 13px; flex-basis: 13px; color: var(--rs-text-dim); }
|
.action-chevron { width: 13px; height: 13px; flex-basis: 13px; color: var(--rs-text-dim); }
|
||||||
.table-add .action-icon { width: 20px; height: 20px; margin: 2px; }
|
.table-add .action-icon { width: 20px; height: 20px; margin: 2px; }
|
||||||
.table-cell-menu button:hover, .table-cell-menu button:focus-visible { background: var(--rs-bg-active); outline: none; }
|
|
||||||
.table-cell-menu hr { margin: 4px 0; border: 0; border-top: 1px solid var(--rs-border); }
|
|
||||||
.table-cell-submenu { position: fixed; z-index: 1001; width: 248px; max-width: calc(100vw - 16px); max-height: calc(100vh - 16px); overflow-y: auto; padding: 5px; background: var(--rs-bg-elevated); border: 1px solid var(--rs-border); border-radius: 8px; box-shadow: 0 8px 30px #0006; }
|
|
||||||
.reading mark { background: color-mix(in srgb, #edc65b 30%, transparent); color: inherit; border-radius: 2px; }
|
.reading mark { background: color-mix(in srgb, #edc65b 30%, transparent); color: inherit; border-radius: 2px; }
|
||||||
.reading .md-inline-math { font-family: var(--rs-font-mono); font-style: italic; }
|
.reading .md-inline-math { font-family: var(--rs-font-mono); font-style: italic; }
|
||||||
.reading .md-inline-comment { display: none; }
|
.reading .md-inline-comment { display: none; }
|
||||||
|
|||||||
@@ -1,174 +1,45 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
import type { MenuAction, MenuItem } from "./menuTypes";
|
import { untrack } from "svelte";
|
||||||
import Icon from "$lib/ui/Icon.svelte";
|
import { actionMenu, type ActionMenuItem } from "$lib/ui/actionMenu";
|
||||||
|
import type { MenuItem } from "./menuTypes";
|
||||||
|
|
||||||
type Props = {
|
type Props = {
|
||||||
x: number;
|
x: number;
|
||||||
y: number;
|
y: number;
|
||||||
items: MenuItem[];
|
items: MenuItem[];
|
||||||
onClose: () => void;
|
onClose: () => void;
|
||||||
|
label?: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
let { x, y, items, onClose }: Props = $props();
|
let { x, y, items, onClose, label = "Context actions" }: Props = $props();
|
||||||
|
|
||||||
let root: HTMLElement | undefined = $state();
|
|
||||||
let left = $state(0);
|
|
||||||
let top = $state(0);
|
|
||||||
|
|
||||||
$effect(() => {
|
$effect(() => {
|
||||||
left = x;
|
const menuX = x, menuY = y, entries = items, name = label;
|
||||||
top = y;
|
const previous = document.activeElement instanceof HTMLElement ? document.activeElement : null;
|
||||||
void items;
|
function close(restoreFocus = false) {
|
||||||
queueMicrotask(() => {
|
root.remove();
|
||||||
if (!root) {
|
if (restoreFocus) previous?.focus({ preventScroll: true });
|
||||||
return;
|
|
||||||
}
|
|
||||||
const rect = root.getBoundingClientRect();
|
|
||||||
left = Math.min(x, window.innerWidth - rect.width - 8);
|
|
||||||
top = Math.min(y, window.innerHeight - rect.height - 8);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
function onWindowDown(event: MouseEvent) {
|
|
||||||
if (root && !root.contains(event.target as Node)) {
|
|
||||||
onClose();
|
onClose();
|
||||||
}
|
}
|
||||||
}
|
function convert(entries: MenuItem[]): ActionMenuItem[] {
|
||||||
|
return entries.map(item => {
|
||||||
function onKey(event: KeyboardEvent) {
|
if (item.kind === "sep") return { separator: true };
|
||||||
if (event.key === "Escape") {
|
if (item.kind === "group") return { label: item.label, icon: item.icon, children: convert(item.items) };
|
||||||
onClose();
|
return { label: item.label, icon: item.icon, disabled: item.disabled, run: () => {
|
||||||
}
|
close(true);
|
||||||
}
|
|
||||||
|
|
||||||
function runAction(item: MenuAction) {
|
|
||||||
if (item.disabled) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
item.run();
|
item.run();
|
||||||
onClose();
|
} };
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
const root = untrack(() => actionMenu(menuX, menuY, convert(entries), () => close(true), name));
|
||||||
|
const outside = (event: PointerEvent) => { if (!root.contains(event.target as Node)) close(); };
|
||||||
|
const resize = () => close();
|
||||||
|
window.addEventListener("pointerdown", outside);
|
||||||
|
window.addEventListener("resize", resize);
|
||||||
|
return () => {
|
||||||
|
root.remove();
|
||||||
|
window.removeEventListener("pointerdown", outside);
|
||||||
|
window.removeEventListener("resize", resize);
|
||||||
|
};
|
||||||
|
});
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<svelte:window onmousedown={onWindowDown} onkeydown={onKey} />
|
|
||||||
|
|
||||||
<div
|
|
||||||
bind:this={root}
|
|
||||||
class="menu"
|
|
||||||
style:left="{left}px"
|
|
||||||
style:top="{top}px"
|
|
||||||
role="menu"
|
|
||||||
>
|
|
||||||
{#each items as item, i (i)}
|
|
||||||
{#if item.kind === "sep"}
|
|
||||||
<div class="sep"></div>
|
|
||||||
{:else if item.kind === "group"}
|
|
||||||
<div class="group">
|
|
||||||
<div class="group-label" role="none">{item.label}</div>
|
|
||||||
<div class="flyout" role="menu">
|
|
||||||
{#each item.items as sub, j (`${i}-${j}`)}
|
|
||||||
{#if sub.kind === "sep"}
|
|
||||||
<div class="sep"></div>
|
|
||||||
{:else if sub.kind === "action"}
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
role="menuitem"
|
|
||||||
disabled={sub.disabled}
|
|
||||||
onclick={() => runAction(sub)}
|
|
||||||
>
|
|
||||||
{#if sub.icon}<Icon icon={sub.icon} />{/if}
|
|
||||||
{sub.label}
|
|
||||||
</button>
|
|
||||||
{/if}
|
|
||||||
{/each}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
{:else}
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
role="menuitem"
|
|
||||||
disabled={item.disabled}
|
|
||||||
onclick={() => runAction(item)}
|
|
||||||
>
|
|
||||||
{#if item.icon}<Icon icon={item.icon} />{/if}
|
|
||||||
{item.label}
|
|
||||||
</button>
|
|
||||||
{/if}
|
|
||||||
{/each}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<style>
|
|
||||||
.menu,
|
|
||||||
.flyout {
|
|
||||||
min-width: 200px;
|
|
||||||
padding: 4px 0;
|
|
||||||
background: var(--rs-bg-elevated);
|
|
||||||
border: 1px solid var(--rs-border);
|
|
||||||
border-radius: var(--rs-control-radius);
|
|
||||||
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.35);
|
|
||||||
}
|
|
||||||
|
|
||||||
.menu {
|
|
||||||
position: fixed;
|
|
||||||
z-index: 40;
|
|
||||||
}
|
|
||||||
|
|
||||||
.group {
|
|
||||||
position: relative;
|
|
||||||
}
|
|
||||||
|
|
||||||
.group-label {
|
|
||||||
padding: 6px 12px;
|
|
||||||
color: var(--rs-text);
|
|
||||||
cursor: default;
|
|
||||||
}
|
|
||||||
|
|
||||||
.group-label::after {
|
|
||||||
content: "▸";
|
|
||||||
float: right;
|
|
||||||
color: var(--rs-text-dim);
|
|
||||||
}
|
|
||||||
|
|
||||||
.flyout {
|
|
||||||
display: none;
|
|
||||||
position: absolute;
|
|
||||||
left: 100%;
|
|
||||||
top: 0;
|
|
||||||
z-index: 41;
|
|
||||||
}
|
|
||||||
|
|
||||||
.group:hover > .flyout,
|
|
||||||
.group:focus-within > .flyout {
|
|
||||||
display: block;
|
|
||||||
}
|
|
||||||
|
|
||||||
button {
|
|
||||||
display: flex;
|
|
||||||
align-items: center;
|
|
||||||
gap: 8px;
|
|
||||||
width: 100%;
|
|
||||||
border: 0;
|
|
||||||
background: transparent;
|
|
||||||
color: var(--rs-text-strong);
|
|
||||||
text-align: left;
|
|
||||||
padding: 6px 12px;
|
|
||||||
border-radius: var(--rs-control-radius);
|
|
||||||
}
|
|
||||||
|
|
||||||
button:hover,
|
|
||||||
button:focus-visible {
|
|
||||||
background: var(--rs-bg-active);
|
|
||||||
outline: none;
|
|
||||||
}
|
|
||||||
|
|
||||||
button:disabled {
|
|
||||||
color: var(--rs-text-dim);
|
|
||||||
opacity: 0.55;
|
|
||||||
}
|
|
||||||
|
|
||||||
.sep {
|
|
||||||
height: 1px;
|
|
||||||
margin: 4px 0;
|
|
||||||
background: var(--rs-border);
|
|
||||||
}
|
|
||||||
</style>
|
|
||||||
|
|||||||
@@ -24,13 +24,14 @@
|
|||||||
type DropPlace,
|
type DropPlace,
|
||||||
type DropTarget,
|
type DropTarget,
|
||||||
} from "$lib/workspace/treeDrop";
|
} from "$lib/workspace/treeDrop";
|
||||||
import { planRename } from "$lib/workspace/renamePath";
|
import { planRename, planDocumentTitleRename } from "$lib/workspace/renamePath";
|
||||||
import { selectTreePath, treeSelectionEdges, visibleTreePaths, type SelectionModifiers, type TreeSelection } from "$lib/workspace/treeSelection";
|
import { selectTreePath, treeSelectionEdges, visibleTreePaths, type SelectionModifiers, type TreeSelection } from "$lib/workspace/treeSelection";
|
||||||
import ContextMenu from "./ContextMenu.svelte";
|
import ContextMenu from "./ContextMenu.svelte";
|
||||||
import type { MenuItem } from "./menuTypes";
|
import type { MenuItem } from "./menuTypes";
|
||||||
import TreeNode from "./TreeNode.svelte";
|
import TreeNode from "./TreeNode.svelte";
|
||||||
import IconButton from "$lib/ui/IconButton.svelte";
|
import IconButton from "$lib/ui/IconButton.svelte";
|
||||||
import { dropWorkspaceImage, highlightImageDrop } from "$lib/editor/workspaceImageDrop";
|
import { dropWorkspaceImage, highlightImageDrop } from "$lib/editor/workspaceImageDrop";
|
||||||
|
import { pluginDocuments, pluginDocumentTypes, inspectPluginDocuments, createPluginDocument } from "$lib/plugins/external";
|
||||||
|
|
||||||
type Props = {
|
type Props = {
|
||||||
workspaceRoot: string;
|
workspaceRoot: string;
|
||||||
@@ -72,6 +73,7 @@
|
|||||||
const selectionEdges = $derived(treeSelectionEdges(visiblePaths, selection.paths));
|
const selectionEdges = $derived(treeSelectionEdges(visiblePaths, selection.paths));
|
||||||
let renameRel = $state<string | null>(null);
|
let renameRel = $state<string | null>(null);
|
||||||
let renameDraft = $state("");
|
let renameDraft = $state("");
|
||||||
|
let renameDocument = false;
|
||||||
let skipClick = false;
|
let skipClick = false;
|
||||||
let imageLanding = $state(false);
|
let imageLanding = $state(false);
|
||||||
let cancelDrag: (() => void) | undefined;
|
let cancelDrag: (() => void) | undefined;
|
||||||
@@ -117,6 +119,7 @@
|
|||||||
try {
|
try {
|
||||||
const entries = await workspaceList(rel);
|
const entries = await workspaceList(rel);
|
||||||
childrenMap = { ...childrenMap, [rel]: sortEntries(rel, entries) };
|
childrenMap = { ...childrenMap, [rel]: sortEntries(rel, entries) };
|
||||||
|
void inspectPluginDocuments(entries);
|
||||||
error = null;
|
error = null;
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
error = err instanceof Error ? err.message : String(err);
|
error = err instanceof Error ? err.message : String(err);
|
||||||
@@ -139,6 +142,7 @@
|
|||||||
|
|
||||||
$effect(() => {
|
$effect(() => {
|
||||||
void refreshToken;
|
void refreshToken;
|
||||||
|
void $pluginDocumentTypes;
|
||||||
const keys = untrack(() => Object.keys(childrenMap));
|
const keys = untrack(() => Object.keys(childrenMap));
|
||||||
for (const key of keys) {
|
for (const key of keys) {
|
||||||
void load(key);
|
void load(key);
|
||||||
@@ -348,7 +352,8 @@
|
|||||||
function startRename(entry: TreeEntry) {
|
function startRename(entry: TreeEntry) {
|
||||||
selectOnly(entry.rel_path);
|
selectOnly(entry.rel_path);
|
||||||
renameRel = entry.rel_path;
|
renameRel = entry.rel_path;
|
||||||
renameDraft = entry.name;
|
renameDocument = entry.kind === "file" && (!!$pluginDocuments[entry.rel_path] || /\.(md|markdown|mdown)$/i.test(entry.name));
|
||||||
|
renameDraft = renameDocument ? entry.name.replace(/\.[^.]+$/, "") : entry.name;
|
||||||
}
|
}
|
||||||
|
|
||||||
function cancelRename() {
|
function cancelRename() {
|
||||||
@@ -361,7 +366,7 @@
|
|||||||
if (!from) {
|
if (!from) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const plan = planRename(from, renameDraft);
|
const plan = renameDocument ? planDocumentTitleRename(from, renameDraft) : planRename(from, renameDraft);
|
||||||
cancelRename();
|
cancelRename();
|
||||||
if (plan.action === "noop") {
|
if (plan.action === "noop") {
|
||||||
return;
|
return;
|
||||||
@@ -531,6 +536,24 @@
|
|||||||
void createIn(parent, "note");
|
void createIn(parent, "note");
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
...$pluginDocumentTypes.filter(item => item.type.create).map(({ owner, type }): MenuItem => ({
|
||||||
|
kind: "action", label: type.create!.label, icon: type.icon === "kanban" ? "kanban" : "file-plus",
|
||||||
|
run: () => { void (async () => {
|
||||||
|
const create = type.create!;
|
||||||
|
const typed = await requestText(create.label, create.defaultName);
|
||||||
|
if (typed === null) return;
|
||||||
|
const name = typed.trim().replace(new RegExp(`\\.${create.extension}$`, "i"), "");
|
||||||
|
if (!name || name.length > 100 || /[<>:"/\\|?*\x00-\x1f]/.test(name) || /[. ]$/.test(name) || /^(con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(name)) { error = "Enter a valid document name."; return; }
|
||||||
|
const fileName = `${name}.${create.extension}`;
|
||||||
|
const path = joinRel(parent, fileName);
|
||||||
|
try {
|
||||||
|
await createPluginDocument(owner, type.id, path);
|
||||||
|
expanded = new Set([...expanded, parent]);
|
||||||
|
await load(parent);
|
||||||
|
onOpenFile({ name: fileName, rel_path: path, kind: "file" }, true);
|
||||||
|
} catch (reason) { error = String(reason); }
|
||||||
|
})(); },
|
||||||
|
})),
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -551,7 +574,7 @@
|
|||||||
{
|
{
|
||||||
kind: "action",
|
kind: "action",
|
||||||
label: multiple ? `Make copies (${entries.length})` : "Make a copy",
|
label: multiple ? `Make copies (${entries.length})` : "Make a copy",
|
||||||
icon: "files",
|
icon: "copy",
|
||||||
run: () => { void copyEntries(entries); },
|
run: () => { void copyEntries(entries); },
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -569,7 +592,7 @@
|
|||||||
{
|
{
|
||||||
kind: "action",
|
kind: "action",
|
||||||
label: multiple ? "Copy workspace paths" : "Copy workspace path",
|
label: multiple ? "Copy workspace paths" : "Copy workspace path",
|
||||||
icon: "files",
|
icon: "copy",
|
||||||
run: () => {
|
run: () => {
|
||||||
void copyText(entries.map(item => item.rel_path).join("\n"), multiple ? "workspace paths" : "workspace path");
|
void copyText(entries.map(item => item.rel_path).join("\n"), multiple ? "workspace paths" : "workspace path");
|
||||||
},
|
},
|
||||||
@@ -577,7 +600,7 @@
|
|||||||
{
|
{
|
||||||
kind: "action",
|
kind: "action",
|
||||||
label: multiple ? "Copy system paths" : "Copy system path",
|
label: multiple ? "Copy system paths" : "Copy system path",
|
||||||
icon: "files",
|
icon: "copy",
|
||||||
run: () => {
|
run: () => {
|
||||||
void (async () => {
|
void (async () => {
|
||||||
try {
|
try {
|
||||||
@@ -592,7 +615,7 @@
|
|||||||
{
|
{
|
||||||
kind: "action",
|
kind: "action",
|
||||||
label: "Show in Explorer",
|
label: "Show in Explorer",
|
||||||
icon: "folder-open",
|
icon: "folder",
|
||||||
run: () => {
|
run: () => {
|
||||||
void (async () => {
|
void (async () => {
|
||||||
const result = await runTreeActions(entries, item => workspaceReveal(item.rel_path));
|
const result = await runTreeActions(entries, item => workspaceReveal(item.rel_path));
|
||||||
@@ -604,6 +627,7 @@
|
|||||||
{
|
{
|
||||||
kind: "action",
|
kind: "action",
|
||||||
label: pinned ? "Unpin" : "Pin",
|
label: pinned ? "Unpin" : "Pin",
|
||||||
|
icon: "pin",
|
||||||
run: () => {
|
run: () => {
|
||||||
void persistMarks({
|
void persistMarks({
|
||||||
...marks,
|
...marks,
|
||||||
@@ -614,7 +638,7 @@
|
|||||||
{
|
{
|
||||||
kind: "action",
|
kind: "action",
|
||||||
label: "Rename",
|
label: "Rename",
|
||||||
icon: "pen",
|
icon: "rename",
|
||||||
disabled: multiple,
|
disabled: multiple,
|
||||||
run: () => {
|
run: () => {
|
||||||
startRename(entry);
|
startRename(entry);
|
||||||
@@ -714,6 +738,7 @@
|
|||||||
|
|
||||||
{#if menu}
|
{#if menu}
|
||||||
<ContextMenu
|
<ContextMenu
|
||||||
|
label="File actions"
|
||||||
x={menu.x}
|
x={menu.x}
|
||||||
y={menu.y}
|
y={menu.y}
|
||||||
items={menuItems(menu.entry)}
|
items={menuItems(menu.entry)}
|
||||||
|
|||||||
@@ -303,9 +303,6 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
.pin { width: 14px; height: 14px; margin-right: 6px; vertical-align: -2px; fill: none; stroke: currentColor; stroke-width: 1.6; stroke-linecap: round; stroke-linejoin: round; }
|
.pin { width: 14px; height: 14px; margin-right: 6px; vertical-align: -2px; fill: none; stroke: currentColor; stroke-width: 1.6; stroke-linecap: round; stroke-linejoin: round; }
|
||||||
:global(.tab-menu) { width: 244px; border-radius: var(--rs-control-radius); }
|
|
||||||
:global(.tab-menu button) { border-radius: var(--rs-control-radius); min-height: 30px; }
|
|
||||||
:global(.tab-menu .table-cell-submenu) { border-radius: var(--rs-control-radius); }
|
|
||||||
|
|
||||||
.close {
|
.close {
|
||||||
border: 0;
|
border: 0;
|
||||||
|
|||||||
@@ -4,6 +4,8 @@
|
|||||||
import type { SelectionModifiers, TreeSelectionEdges } from "$lib/workspace/treeSelection";
|
import type { SelectionModifiers, TreeSelectionEdges } from "$lib/workspace/treeSelection";
|
||||||
import { treeFileParts } from "$lib/workspace/chrome";
|
import { treeFileParts } from "$lib/workspace/chrome";
|
||||||
import TreeNode from "./TreeNode.svelte";
|
import TreeNode from "./TreeNode.svelte";
|
||||||
|
import Icon from "$lib/ui/Icon.svelte";
|
||||||
|
import { pluginDocuments } from "$lib/plugins/external";
|
||||||
|
|
||||||
type Props = {
|
type Props = {
|
||||||
entry: TreeEntry;
|
entry: TreeEntry;
|
||||||
@@ -125,6 +127,9 @@
|
|||||||
</span>
|
</span>
|
||||||
{/if}
|
{/if}
|
||||||
<span class="twist" class:open={isOpen} class:folder={entry.kind === "folder"}></span>
|
<span class="twist" class:open={isOpen} class:folder={entry.kind === "folder"}></span>
|
||||||
|
{#if $pluginDocuments[entry.rel_path]}
|
||||||
|
<span class="document-icon" title={$pluginDocuments[entry.rel_path].title}><Icon icon={$pluginDocuments[entry.rel_path].icon === "kanban" ? "kanban" : "files"} /></span>
|
||||||
|
{/if}
|
||||||
{#if isRenaming}
|
{#if isRenaming}
|
||||||
<input
|
<input
|
||||||
class="rename"
|
class="rename"
|
||||||
@@ -183,6 +188,7 @@
|
|||||||
</li>
|
</li>
|
||||||
|
|
||||||
<style>
|
<style>
|
||||||
|
.document-icon { display: inline-flex; width: 16px; height: 16px; flex-shrink: 0; margin-right: 5px; }
|
||||||
li {
|
li {
|
||||||
list-style: none;
|
list-style: none;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,9 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
import TerminalSlot from "$lib/plugins/TerminalSlot.svelte";
|
import TerminalSlot from "$lib/plugins/TerminalSlot.svelte";
|
||||||
import PluginTools from "$lib/plugins/PluginTools.svelte";
|
import PluginTools from "$lib/plugins/PluginTools.svelte";
|
||||||
|
import PluginEditor from "$lib/plugins/PluginEditor.svelte";
|
||||||
|
import PluginEditorTab from "$lib/plugins/PluginEditorTab.svelte";
|
||||||
|
import { pluginNavigation, openPluginView, pluginView, pluginEditors, pluginEditorActive, closePluginEditor, openPluginDocument, renamePluginDocuments, removePluginDocuments, notifyPluginWorkspace, guardPluginWrites, handlePluginDocumentRename, cancelPluginDocumentOpen } from "$lib/plugins/external";
|
||||||
import { onMount, tick } from "svelte";
|
import { onMount, tick } from "svelte";
|
||||||
import { selectedEditorText } from "$lib/editor/selection";
|
import { selectedEditorText } from "$lib/editor/selection";
|
||||||
import { pluginHost } from "$lib/plugins/registry";
|
import { pluginHost } from "$lib/plugins/registry";
|
||||||
@@ -44,7 +47,7 @@
|
|||||||
workspaceWriteBytes,
|
workspaceWriteBytes,
|
||||||
} from "$lib/workspace/api";
|
} from "$lib/workspace/api";
|
||||||
import { detectChrome } from "$lib/workspace/chrome";
|
import { detectChrome } from "$lib/workspace/chrome";
|
||||||
import { planRename, planMarkdownTitleRename } from "$lib/workspace/renamePath";
|
import { planRename, planMarkdownTitleRename, planDocumentTitleRename } from "$lib/workspace/renamePath";
|
||||||
import { attachmentRel, isImagePath, isMarkdownPath } from "$lib/workspace/media";
|
import { attachmentRel, isImagePath, isMarkdownPath } from "$lib/workspace/media";
|
||||||
import { linkCandidates } from "$lib/workspace/markdownLinks";
|
import { linkCandidates } from "$lib/workspace/markdownLinks";
|
||||||
import type { Chrome, OpenBuffer, TreeEntry, WorkspaceInfo } from "$lib/workspace/types";
|
import type { Chrome, OpenBuffer, TreeEntry, WorkspaceInfo } from "$lib/workspace/types";
|
||||||
@@ -109,6 +112,7 @@
|
|||||||
let dragging = $state<"left" | "right" | "bottom" | null>(null);
|
let dragging = $state<"left" | "right" | "bottom" | null>(null);
|
||||||
let centerStack: HTMLElement | undefined = $state();
|
let centerStack: HTMLElement | undefined = $state();
|
||||||
|
|
||||||
|
const editorPluginVisible = $derived($pluginView?.placement === "editor" && $pluginEditorActive);
|
||||||
const dirty = $derived(buffer !== null && buffer.contents !== buffer.saved);
|
const dirty = $derived(buffer !== null && buffer.contents !== buffer.saved);
|
||||||
const isIde = $derived(view === "Ide");
|
const isIde = $derived(view === "Ide");
|
||||||
const outlineItems = $derived(
|
const outlineItems = $derived(
|
||||||
@@ -202,13 +206,17 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
function selectTab(relPath: string) {
|
function selectTab(relPath: string) {
|
||||||
|
cancelPluginDocumentOpen();
|
||||||
|
pluginEditorActive.set(false);
|
||||||
focusLine = null;
|
focusLine = null;
|
||||||
documents?.select(relPath);
|
documents?.select(relPath);
|
||||||
status = documents?.active?.kind === "empty" ? "New tab" : relPath;
|
status = documents?.active?.kind === "empty" ? "New tab" : relPath;
|
||||||
}
|
}
|
||||||
|
|
||||||
function newTab() {
|
function newTab() {
|
||||||
|
cancelPluginDocumentOpen();
|
||||||
if (switching) return;
|
if (switching) return;
|
||||||
|
pluginEditorActive.set(false);
|
||||||
documents ??= createDocuments();
|
documents ??= createDocuments();
|
||||||
focusLine = null;
|
focusLine = null;
|
||||||
documents.newTab();
|
documents.newTab();
|
||||||
@@ -276,8 +284,13 @@
|
|||||||
const current = documents;
|
const current = documents;
|
||||||
if (!current || switching) return;
|
if (!current || switching) return;
|
||||||
try {
|
try {
|
||||||
|
const open = current.buffers.find(tab => tab.relPath === entry.rel_path);
|
||||||
|
if (!line && !(open && open.contents !== open.saved) && await openPluginDocument(entry.rel_path, () => documents === current && !switching)) {
|
||||||
|
status = entry.rel_path; error = null; return;
|
||||||
|
}
|
||||||
await current.open(entry, target);
|
await current.open(entry, target);
|
||||||
if (documents !== current) return;
|
if (documents !== current) return;
|
||||||
|
pluginEditorActive.set(false);
|
||||||
status = entry.rel_path;
|
status = entry.rel_path;
|
||||||
error = null;
|
error = null;
|
||||||
focusLine = null;
|
focusLine = null;
|
||||||
@@ -454,7 +467,7 @@
|
|||||||
}
|
}
|
||||||
if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === "s") {
|
if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === "s") {
|
||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
void save();
|
if (!editorPluginVisible) void save();
|
||||||
}
|
}
|
||||||
if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === "o") {
|
if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === "o") {
|
||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
@@ -466,7 +479,7 @@
|
|||||||
}
|
}
|
||||||
if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === "e") {
|
if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === "e") {
|
||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
toggleChrome();
|
if (!editorPluginVisible) toggleChrome();
|
||||||
}
|
}
|
||||||
if (terminalEnabled && (event.ctrlKey || event.metaKey) && event.key === "`") {
|
if (terminalEnabled && (event.ctrlKey || event.metaKey) && event.key === "`") {
|
||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
@@ -474,7 +487,9 @@
|
|||||||
}
|
}
|
||||||
if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === "w") {
|
if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === "w") {
|
||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
if (activePath) {
|
if (editorPluginVisible) {
|
||||||
|
if ($pluginView) closePluginEditor($pluginView.key);
|
||||||
|
} else if (activePath) {
|
||||||
closeTab(activePath);
|
closeTab(activePath);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -487,7 +502,7 @@
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
if (!(leftOpen && leftView === "files")) {
|
if (!editorPluginVisible && !(leftOpen && leftView === "files")) {
|
||||||
void renameActive();
|
void renameActive();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -495,6 +510,7 @@
|
|||||||
|
|
||||||
function applyPathRename(from: string, to: string) {
|
function applyPathRename(from: string, to: string) {
|
||||||
documents?.rename(from, to);
|
documents?.rename(from, to);
|
||||||
|
renamePluginDocuments(from, to);
|
||||||
}
|
}
|
||||||
|
|
||||||
async function renameNoteTitle(id: string, title: string) {
|
async function renameNoteTitle(id: string, title: string) {
|
||||||
@@ -566,7 +582,7 @@
|
|||||||
const shell = event.currentTarget as HTMLElement;
|
const shell = event.currentTarget as HTMLElement;
|
||||||
const rect = shell.getBoundingClientRect();
|
const rect = shell.getBoundingClientRect();
|
||||||
if (dragging === "left") {
|
if (dragging === "left") {
|
||||||
leftWidth = Math.min(480, Math.max(160, event.clientX - rect.left));
|
leftWidth = Math.min(480, Math.max(160, event.clientX - rect.left - ($pluginNavigation.length ? 44 : 0)));
|
||||||
}
|
}
|
||||||
if (dragging === "right") {
|
if (dragging === "right") {
|
||||||
rightWidth = Math.min(480, Math.max(160, rect.right - event.clientX));
|
rightWidth = Math.min(480, Math.max(160, rect.right - event.clientX));
|
||||||
@@ -608,6 +624,22 @@
|
|||||||
void restoreLast();
|
void restoreLast();
|
||||||
let disposed = false;
|
let disposed = false;
|
||||||
const unlisteners: (() => void)[] = [];
|
const unlisteners: (() => void)[] = [];
|
||||||
|
unlisteners.push(handlePluginDocumentRename(async (from, name) => {
|
||||||
|
const current = documents;
|
||||||
|
if (!current || switching) throw new Error("Open a workspace before renaming a document.");
|
||||||
|
const plan = planDocumentTitleRename(from, name);
|
||||||
|
if (plan.action === "error") throw new Error(plan.message);
|
||||||
|
if (plan.action === "noop") return from;
|
||||||
|
await workspaceRename(from, plan.to);
|
||||||
|
if (documents !== current) throw new Error("The workspace changed. Reopen the document.");
|
||||||
|
applyPathRename(from, plan.to);
|
||||||
|
refreshToken++;
|
||||||
|
return plan.to;
|
||||||
|
}));
|
||||||
|
unlisteners.push(guardPluginWrites(path => {
|
||||||
|
const open = documents?.buffers.find(tab => tab.relPath === path);
|
||||||
|
if (open && open.contents !== open.saved) throw new Error("Save or discard the open note's edits before changing it from a plugin.");
|
||||||
|
}));
|
||||||
let refreshTimer: ReturnType<typeof setTimeout>;
|
let refreshTimer: ReturnType<typeof setTimeout>;
|
||||||
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) => {
|
||||||
@@ -617,6 +649,7 @@
|
|||||||
refreshTimer = setTimeout(() => {
|
refreshTimer = setTimeout(() => {
|
||||||
refreshToken++;
|
refreshToken++;
|
||||||
void documents?.refresh();
|
void documents?.refresh();
|
||||||
|
notifyPluginWorkspace();
|
||||||
}, 200);
|
}, 200);
|
||||||
}).then(register).catch(err => error = String(err));
|
}).then(register).catch(err => error = String(err));
|
||||||
let closing = false;
|
let closing = false;
|
||||||
@@ -651,6 +684,7 @@
|
|||||||
|
|
||||||
<div
|
<div
|
||||||
class="shell"
|
class="shell"
|
||||||
|
class:has-ribbon={$pluginNavigation.length > 0}
|
||||||
class:left-open={leftOpen}
|
class:left-open={leftOpen}
|
||||||
class:right-open={rightOpen}
|
class:right-open={rightOpen}
|
||||||
role="application"
|
role="application"
|
||||||
@@ -685,16 +719,17 @@
|
|||||||
</div>
|
</div>
|
||||||
<div class="header-center" data-tauri-drag-region>
|
<div class="header-center" data-tauri-drag-region>
|
||||||
{#if tabs.length > 0}
|
{#if tabs.length > 0}
|
||||||
<TabBar {tabs} {activePath} onSelect={selectTab} onClose={closeTab}
|
<TabBar {tabs} activePath={editorPluginVisible ? null : activePath} onSelect={selectTab} onClose={closeTab}
|
||||||
onCloseTabs={(path, scope) => void closeTabs(path, scope)} onPin={(path) => documents?.togglePin(path)}
|
onCloseTabs={(path, scope) => void closeTabs(path, scope)} onPin={(path) => documents?.togglePin(path)}
|
||||||
fileActions={tabFileActions} onMove={(path, index) => documents?.move(path, index)} />
|
fileActions={tabFileActions} onMove={(path, index) => documents?.move(path, index)} />
|
||||||
{/if}
|
{/if}
|
||||||
|
<PluginEditorTab />
|
||||||
<IconButton icon="plus" label="New tab (Ctrl T)" onclick={newTab} />
|
<IconButton icon="plus" label="New tab (Ctrl T)" onclick={newTab} />
|
||||||
{#if desktop}<div class="window-drag-space" data-tauri-drag-region></div>{/if}
|
{#if desktop}<div class="window-drag-space" data-tauri-drag-region></div>{/if}
|
||||||
</div>
|
</div>
|
||||||
<div class="header-right" data-tauri-drag-region>
|
<div class="header-right" data-tauri-drag-region>
|
||||||
<PluginTools />
|
<PluginTools />
|
||||||
<IconButton icon="save" label="Save" disabled={!dirty || saving} onclick={() => void save()} />
|
<IconButton icon="save" label="Save" disabled={editorPluginVisible || !dirty || saving} onclick={() => void save()} />
|
||||||
{#if terminalEnabled}<IconButton icon="terminal" label="Terminal" active={terminalOpen} onclick={toggleTerminal} />{/if}
|
{#if terminalEnabled}<IconButton icon="terminal" label="Terminal" active={terminalOpen} onclick={toggleTerminal} />{/if}
|
||||||
<IconButton
|
<IconButton
|
||||||
icon="panel-right"
|
icon="panel-right"
|
||||||
@@ -706,6 +741,18 @@
|
|||||||
</div>
|
</div>
|
||||||
</header>
|
</header>
|
||||||
|
|
||||||
|
<nav class="plugin-ribbon" aria-label="Plugin shortcuts" hidden={$pluginNavigation.length === 0}>
|
||||||
|
{#each $pluginNavigation as item (`${item.owner}:${item.id}`)}
|
||||||
|
<IconButton
|
||||||
|
icon={item.icon === "list" || item.icon === "kanban" ? item.icon : "puzzle"}
|
||||||
|
label={item.title}
|
||||||
|
side="right"
|
||||||
|
active={$pluginView?.owner === item.owner && $pluginView?.id === item.id && !$pluginView?.document && ($pluginView?.placement === "dialog" || $pluginEditorActive)}
|
||||||
|
onclick={() => openPluginView(item.owner, item.id)}
|
||||||
|
/>
|
||||||
|
{/each}
|
||||||
|
</nav>
|
||||||
|
|
||||||
{#if leftOpen}
|
{#if leftOpen}
|
||||||
<aside class="left">
|
<aside class="left">
|
||||||
<div class="left-body">
|
<div class="left-body">
|
||||||
@@ -716,7 +763,7 @@
|
|||||||
<div class="left-layer" class:shown={leftView === "files"}>
|
<div class="left-layer" class:shown={leftView === "files"}>
|
||||||
<FileTree
|
<FileTree
|
||||||
workspaceRoot={workspace.root}
|
workspaceRoot={workspace.root}
|
||||||
{activePath}
|
activePath={editorPluginVisible ? $pluginView?.document?.path ?? null : activePath}
|
||||||
onOpenFile={(entry, newTab) => void openFile(entry, undefined, newTab ? "new" : "current")}
|
onOpenFile={(entry, newTab) => void openFile(entry, undefined, newTab ? "new" : "current")}
|
||||||
{refreshToken}
|
{refreshToken}
|
||||||
keysActive={leftView === "files"}
|
keysActive={leftView === "files"}
|
||||||
@@ -727,7 +774,7 @@
|
|||||||
status = message;
|
status = message;
|
||||||
error = null;
|
error = null;
|
||||||
}}
|
}}
|
||||||
onEntryGone={() => { void documents?.refresh(); }}
|
onEntryGone={(path) => { removePluginDocuments(path); void documents?.refresh(); }}
|
||||||
onEntryRenamed={applyPathRename}
|
onEntryRenamed={applyPathRename}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
@@ -760,7 +807,8 @@
|
|||||||
|
|
||||||
<div class="center-stack" class:terminal-maximized={terminalOpen && terminalMaximized} bind:this={centerStack}>
|
<div class="center-stack" class:terminal-maximized={terminalOpen && terminalMaximized} bind:this={centerStack}>
|
||||||
<main class="center">
|
<main class="center">
|
||||||
<div class="editor-host">
|
{#each $pluginEditors as view (view.key)}<PluginEditor {view} />{/each}
|
||||||
|
<div class="editor-host" class:plugin-covered={editorPluginVisible}>
|
||||||
{#if buffer?.diskError}
|
{#if buffer?.diskError}
|
||||||
<div class="conflict" role="alert"><span>{buffer.diskError}</span><button onclick={() => void saveCopy()}>Save a copy</button><button onclick={() => void documents?.refresh()}>Retry</button></div>
|
<div class="conflict" role="alert"><span>{buffer.diskError}</span><button onclick={() => void saveCopy()}>Save a copy</button><button onclick={() => void documents?.refresh()}>Retry</button></div>
|
||||||
{:else if buffer?.diskContents != null}
|
{:else if buffer?.diskContents != null}
|
||||||
@@ -824,6 +872,7 @@
|
|||||||
<OutlinePane
|
<OutlinePane
|
||||||
items={outlineItems}
|
items={outlineItems}
|
||||||
onJump={(line) => {
|
onJump={(line) => {
|
||||||
|
pluginEditorActive.set(false);
|
||||||
reading = false;
|
reading = false;
|
||||||
focusLine = null;
|
focusLine = null;
|
||||||
queueMicrotask(() => {
|
queueMicrotask(() => {
|
||||||
@@ -855,23 +904,43 @@
|
|||||||
.shell {
|
.shell {
|
||||||
height: 100vh;
|
height: 100vh;
|
||||||
display: grid;
|
display: grid;
|
||||||
grid-template-columns: minmax(0, 1fr);
|
--ribbon-width: 0px;
|
||||||
|
grid-template-columns: var(--ribbon-width) minmax(0, 1fr);
|
||||||
grid-template-rows: 36px minmax(0, 1fr) 22px;
|
grid-template-rows: 36px minmax(0, 1fr) 22px;
|
||||||
background: var(--rs-bg);
|
background: var(--rs-bg);
|
||||||
}
|
}
|
||||||
|
|
||||||
.shell.left-open {
|
.shell.left-open {
|
||||||
grid-template-columns: var(--left) 1px minmax(0, 1fr);
|
grid-template-columns: var(--ribbon-width) var(--left) 1px minmax(0, 1fr);
|
||||||
}
|
}
|
||||||
|
|
||||||
.shell.right-open {
|
.shell.right-open {
|
||||||
grid-template-columns: minmax(0, 1fr) 1px var(--right);
|
grid-template-columns: var(--ribbon-width) minmax(0, 1fr) 1px var(--right);
|
||||||
}
|
}
|
||||||
|
|
||||||
.shell.left-open.right-open {
|
.shell.left-open.right-open {
|
||||||
grid-template-columns: var(--left) 1px minmax(0, 1fr) 1px var(--right);
|
grid-template-columns: var(--ribbon-width) var(--left) 1px minmax(0, 1fr) 1px var(--right);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.shell.has-ribbon { --ribbon-width: 44px; }
|
||||||
|
|
||||||
|
.plugin-ribbon {
|
||||||
|
grid-column: 1;
|
||||||
|
grid-row: 2;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
align-items: center;
|
||||||
|
gap: 4px;
|
||||||
|
min-height: 0;
|
||||||
|
padding: 6px 5px;
|
||||||
|
overflow-y: auto;
|
||||||
|
background: var(--rs-bg-elevated);
|
||||||
|
border-right: 1px solid var(--rs-border);
|
||||||
|
}
|
||||||
|
|
||||||
|
.plugin-ribbon[hidden] { display: block; visibility: hidden; padding: 0; border: 0; }
|
||||||
|
.plugin-ribbon :global(.icon-btn) { width: 32px; height: 32px; flex-basis: 32px; }
|
||||||
|
|
||||||
.header {
|
.header {
|
||||||
grid-column: 1 / -1;
|
grid-column: 1 / -1;
|
||||||
display: grid;
|
display: grid;
|
||||||
@@ -885,7 +954,7 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
.shell.left-open .header {
|
.shell.left-open .header {
|
||||||
grid-template-columns: var(--left) minmax(0, 1fr) auto;
|
grid-template-columns: calc(var(--left) + var(--ribbon-width)) minmax(0, 1fr) auto;
|
||||||
}
|
}
|
||||||
|
|
||||||
.shell.right-open .header {
|
.shell.right-open .header {
|
||||||
@@ -893,7 +962,7 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
.shell.left-open.right-open .header {
|
.shell.left-open.right-open .header {
|
||||||
grid-template-columns: var(--left) minmax(0, 1fr) minmax(max-content, var(--right));
|
grid-template-columns: calc(var(--left) + var(--ribbon-width)) minmax(0, 1fr) minmax(max-content, var(--right));
|
||||||
}
|
}
|
||||||
|
|
||||||
.header-left,
|
.header-left,
|
||||||
@@ -977,6 +1046,8 @@
|
|||||||
position: relative;
|
position: relative;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.editor-host.plugin-covered { display: none; }
|
||||||
|
|
||||||
.left,
|
.left,
|
||||||
.right {
|
.right {
|
||||||
background: var(--rs-bg-elevated);
|
background: var(--rs-bg-elevated);
|
||||||
|
|||||||
@@ -1,11 +1,11 @@
|
|||||||
import type { IconName } from "$lib/ui/IconButton.svelte";
|
import type { ActionIcon } from "$lib/ui/actionIcons";
|
||||||
|
|
||||||
export type MenuAction = {
|
export type MenuAction = {
|
||||||
kind: "action";
|
kind: "action";
|
||||||
label: string;
|
label: string;
|
||||||
run: () => void;
|
run: () => void;
|
||||||
disabled?: boolean;
|
disabled?: boolean;
|
||||||
icon?: IconName;
|
icon?: ActionIcon;
|
||||||
};
|
};
|
||||||
|
|
||||||
export type MenuSep = { kind: "sep" };
|
export type MenuSep = { kind: "sep" };
|
||||||
@@ -13,6 +13,7 @@ export type MenuSep = { kind: "sep" };
|
|||||||
export type MenuGroup = {
|
export type MenuGroup = {
|
||||||
kind: "group";
|
kind: "group";
|
||||||
label: string;
|
label: string;
|
||||||
|
icon?: ActionIcon;
|
||||||
items: MenuItem[];
|
items: MenuItem[];
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,36 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import { untrack } from "svelte";
|
||||||
|
import { pluginView, pluginEditorActive, mountPluginView, type OpenPluginView } from "./external";
|
||||||
|
let { view }: { view: OpenPluginView } = $props();
|
||||||
|
let host: HTMLDivElement | undefined = $state();
|
||||||
|
let error = $state("");
|
||||||
|
|
||||||
|
$effect(() => {
|
||||||
|
const element = host;
|
||||||
|
if (!element) return;
|
||||||
|
error = "";
|
||||||
|
let cancelled = false;
|
||||||
|
let cleanup: (() => void | Promise<void>) | undefined;
|
||||||
|
void untrack(() => mountPluginView(view.owner, view.id, element, view.document)).then(dispose => {
|
||||||
|
if (cancelled) void Promise.resolve(dispose()).catch(() => {});
|
||||||
|
else cleanup = dispose;
|
||||||
|
}).catch(reason => { if (!cancelled) error = String(reason); });
|
||||||
|
return () => {
|
||||||
|
cancelled = true;
|
||||||
|
void Promise.resolve(cleanup?.()).catch(reason => console.error("Plugin view cleanup failed", reason));
|
||||||
|
};
|
||||||
|
});
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<div id={`plugin-editor-${view.key}`} class="plugin-editor-pane" class:inactive={!$pluginEditorActive || $pluginView?.key !== view.key}
|
||||||
|
role="tabpanel" aria-label={view.title} tabindex="-1">
|
||||||
|
{#if error}<p class="error" role="alert">{error}</p>{/if}
|
||||||
|
<div class="plugin-editor-content" bind:this={host}></div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<style>
|
||||||
|
.plugin-editor-pane { display: flex; flex: 1; min-height: 0; min-width: 0; flex-direction: column; overflow: hidden; }
|
||||||
|
.plugin-editor-pane.inactive { display: none; }
|
||||||
|
.plugin-editor-content { flex: 1; min-height: 0; min-width: 0; overflow: auto; }
|
||||||
|
.error { color: var(--rs-error); padding: 12px; }
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import Icon from "$lib/ui/Icon.svelte";
|
||||||
|
import IconButton from "$lib/ui/IconButton.svelte";
|
||||||
|
import { pluginView, pluginEditors, pluginEditorActive, selectPluginEditor, closePluginEditor } from "./external";
|
||||||
|
</script>
|
||||||
|
|
||||||
|
{#if $pluginEditors.length}
|
||||||
|
<div class="plugin-tabs" role="tablist" aria-label="Plugin views">
|
||||||
|
{#each $pluginEditors as view (view.key)}
|
||||||
|
<div class="plugin-tab" class:active={$pluginEditorActive && $pluginView?.key === view.key}>
|
||||||
|
<button role="tab" aria-selected={$pluginEditorActive && $pluginView?.key === view.key} aria-controls={`plugin-editor-${view.key}`}
|
||||||
|
title={view.document?.path ?? view.title} onclick={() => selectPluginEditor(view)}
|
||||||
|
onauxclick={event => { if (event.button === 1) { event.preventDefault(); closePluginEditor(view.key); } }}>
|
||||||
|
<Icon icon={view.icon === "file" ? "files" : view.icon ?? "puzzle"} /><span>{view.title}</span>
|
||||||
|
</button>
|
||||||
|
<IconButton icon="close" label={`Close ${view.title}`} onclick={() => closePluginEditor(view.key)} />
|
||||||
|
</div>
|
||||||
|
{/each}
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
|
||||||
|
<style>
|
||||||
|
.plugin-tabs { display: flex; flex-shrink: 1; min-width: 0; max-width: 70%; overflow-x: auto; }
|
||||||
|
.plugin-tab { display: flex; align-items: center; min-width: 0; border: 1px solid transparent; border-radius: var(--rs-control-radius); }
|
||||||
|
.plugin-tab.active { background: var(--rs-item-selection-bg); border-color: var(--rs-item-selection-border); }
|
||||||
|
.plugin-tab:hover { background: var(--rs-bg-active); }
|
||||||
|
button[role="tab"] { display: flex; align-items: center; gap: 7px; min-width: 0; height: 32px; padding: 0 9px; border: 0; border-radius: var(--rs-control-radius); background: transparent; color: var(--rs-text); }
|
||||||
|
button[role="tab"]:focus-visible { outline: 2px solid var(--rs-accent); outline-offset: -2px; }
|
||||||
|
span { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||||
|
:global(.plugin-tab svg) { width: 16px; height: 16px; flex-shrink: 0; }
|
||||||
|
</style>
|
||||||
@@ -6,18 +6,27 @@
|
|||||||
import { installedPlugins, externalErrors, pluginServiceError, restartPlugins, refreshPlugins, setPluginEnabled } from "./external";
|
import { installedPlugins, externalErrors, pluginServiceError, restartPlugins, refreshPlugins, setPluginEnabled } from "./external";
|
||||||
import type { Candidate, RemovalPlan, InstalledPlugin } from "./sdk";
|
import type { Candidate, RemovalPlan, InstalledPlugin } from "./sdk";
|
||||||
const desktop = isTauri();
|
const desktop = isTauri();
|
||||||
|
const installDateFormat = new Intl.DateTimeFormat(undefined, {
|
||||||
|
year: "numeric", month: "short", day: "numeric",
|
||||||
|
hour: "numeric", minute: "2-digit", second: "2-digit", timeZoneName: "short",
|
||||||
|
});
|
||||||
let busy = $state(false);
|
let busy = $state(false);
|
||||||
let error = $state("");
|
let error = $state("");
|
||||||
let message = $state("");
|
let message = $state("");
|
||||||
let candidates = $state<Candidate[]>([]);
|
let candidates = $state<Candidate[]>([]);
|
||||||
let selected = $state<string[]>([]);
|
let selected = $state<string[]>([]);
|
||||||
let plan = $state<RemovalPlan | null>(null);
|
let plan = $state<RemovalPlan | null>(null);
|
||||||
|
let gitForm = $state(false);
|
||||||
|
let gitUrl = $state("");
|
||||||
|
let gitTag = $state("");
|
||||||
|
let gitToken = $state("");
|
||||||
|
let disposed = false;
|
||||||
let modal: HTMLDialogElement | undefined = $state();
|
let modal: HTMLDialogElement | undefined = $state();
|
||||||
let cancelButton: HTMLButtonElement | undefined = $state();
|
let cancelButton: HTMLButtonElement | undefined = $state();
|
||||||
let previous: HTMLElement | null = null;
|
let previous: HTMLElement | null = null;
|
||||||
const external = $derived($installedPlugins.plugins);
|
const external = $derived($installedPlugins.plugins);
|
||||||
$effect(() => {
|
$effect(() => {
|
||||||
if (modal && (plan || candidates.length)) {
|
if (modal && (plan || candidates.length || gitForm)) {
|
||||||
if (!modal.open) { previous = document.activeElement instanceof HTMLElement ? document.activeElement : null; modal.showModal(); }
|
if (!modal.open) { previous = document.activeElement instanceof HTMLElement ? document.activeElement : null; modal.showModal(); }
|
||||||
if (!busy) cancelButton?.focus();
|
if (!busy) cancelButton?.focus();
|
||||||
}
|
}
|
||||||
@@ -26,19 +35,19 @@
|
|||||||
async function cancel() {
|
async function cancel() {
|
||||||
if (busy) return;
|
if (busy) return;
|
||||||
const pending = tokens();
|
const pending = tokens();
|
||||||
plan = null; candidates = []; selected = [];
|
plan = null; candidates = []; selected = []; gitForm = false; gitToken = "";
|
||||||
modal?.close(); previous?.focus();
|
modal?.close(); previous?.focus();
|
||||||
if (pending.length) await invoke("plugins_cancel", { tokens: pending }).catch(reason => error = String(reason));
|
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(() => {}); });
|
onDestroy(() => { disposed = true; gitToken = ""; const pending = tokens(); if (pending.length) void invoke("plugins_cancel", { tokens: pending }).catch(() => {}); });
|
||||||
async function run(action: () => Promise<void>) {
|
async function run(action: () => Promise<void>) {
|
||||||
busy = true; error = ""; message = "";
|
busy = true; error = ""; message = "";
|
||||||
try { await action(); } catch (reason) { error = String(reason); }
|
try { await action(); } catch (reason) { error = String(reason); }
|
||||||
finally { busy = false; }
|
finally { busy = false; }
|
||||||
}
|
}
|
||||||
async function choose(folder: boolean) {
|
async function choose() {
|
||||||
await run(async () => {
|
await run(async () => {
|
||||||
candidates = await invoke<Candidate[]>("plugins_choose", { folder });
|
candidates = await invoke<Candidate[]>("plugins_choose");
|
||||||
selected = candidates.filter(item => !item.error && item.manifest).map(item => item.token);
|
selected = candidates.filter(item => !item.error && item.manifest).map(item => item.token);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -51,6 +60,17 @@
|
|||||||
candidates = []; selected = []; await refreshPlugins(); previous?.focus();
|
candidates = []; selected = []; await refreshPlugins(); previous?.focus();
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
async function fromGit() {
|
||||||
|
await run(async () => {
|
||||||
|
try {
|
||||||
|
const result = await invoke<Candidate[]>("plugins_from_git", { url: gitUrl.trim(), tag: gitTag.trim(), token: gitToken || null });
|
||||||
|
if (disposed) { await invoke("plugins_cancel", { tokens: result.map(item => item.token) }); return; }
|
||||||
|
candidates = result;
|
||||||
|
selected = result.filter(item => !item.error && item.manifest).map(item => item.token);
|
||||||
|
gitForm = false;
|
||||||
|
} finally { gitToken = ""; }
|
||||||
|
});
|
||||||
|
}
|
||||||
async function toggle(id: string, enabled: boolean, hash?: string) {
|
async function toggle(id: string, enabled: boolean, hash?: string) {
|
||||||
await run(async () => {
|
await run(async () => {
|
||||||
await setPluginEnabled(id, enabled, hash);
|
await setPluginEnabled(id, enabled, hash);
|
||||||
@@ -73,7 +93,7 @@
|
|||||||
event.stopPropagation();
|
event.stopPropagation();
|
||||||
if (event.repeat && (event.key === "Enter" || event.key === " ")) event.preventDefault();
|
if (event.repeat && (event.key === "Enter" || event.key === " ")) event.preventDefault();
|
||||||
if (event.key !== "Tab" || !modal) return;
|
if (event.key !== "Tab" || !modal) return;
|
||||||
const controls = [...modal.querySelectorAll<HTMLElement>("button:not(:disabled),input:not(:disabled)")];
|
const controls = [...modal.querySelectorAll<HTMLElement>("button:not(:disabled),input:not(:disabled),select:not(:disabled)")];
|
||||||
const first = controls[0], last = controls.at(-1);
|
const first = controls[0], last = controls.at(-1);
|
||||||
if (event.shiftKey && document.activeElement === first) { event.preventDefault(); last?.focus(); }
|
if (event.shiftKey && document.activeElement === first) { event.preventDefault(); last?.focus(); }
|
||||||
else if (!event.shiftKey && document.activeElement === last) { event.preventDefault(); first?.focus(); }
|
else if (!event.shiftKey && document.activeElement === last) { event.preventDefault(); first?.focus(); }
|
||||||
@@ -81,10 +101,10 @@
|
|||||||
</script>
|
</script>
|
||||||
|
|
||||||
<h2>Plug-ins</h2>
|
<h2>Plug-ins</h2>
|
||||||
<p>Install a package file or select a folder containing plugins.</p>
|
<p>Install a plugin ZIP file or get a release from a Git repository link.</p>
|
||||||
<div class="toolbar">
|
<div class="toolbar">
|
||||||
<button disabled={!desktop || busy} onclick={() => choose(false)}><Icon icon="file-plus" />Install from file</button>
|
<button disabled={!desktop || busy} onclick={() => choose()}><Icon icon="file-plus" />Install plugin ZIP</button>
|
||||||
<button disabled={!desktop || busy} onclick={() => choose(true)}><Icon icon="folder-plus" />Install from folder</button>
|
<button disabled={!desktop || busy} onclick={() => { error = ""; gitForm = true; }}><Icon icon="link" />Install from Git link</button>
|
||||||
<IconButton icon="folder-open" label="Open plugins folder" disabled={!desktop || busy} onclick={() => reveal()} />
|
<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>
|
<button disabled={!desktop || busy} onclick={() => run(refreshPlugins)}><Icon icon="refresh" />Refresh</button>
|
||||||
</div>
|
</div>
|
||||||
@@ -100,26 +120,48 @@
|
|||||||
<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>
|
<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); }} />
|
<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>
|
</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}
|
{#if plugin.error || $externalErrors[plugin.manifest.id]}<p class="error" role="alert">{plugin.error || $externalErrors[plugin.manifest.id]}</p>{/if}
|
||||||
<div class="actions">
|
<div class="actions">
|
||||||
|
<div class="status">
|
||||||
<span class="badge">{plugin.removal ? "Removal incomplete" : plugin.enabled ? "Enabled" : "Disabled"}</span>
|
<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>
|
<span class="note">
|
||||||
|
{#if plugin.installedAt != null}
|
||||||
|
Installed <time datetime={new Date(plugin.installedAt).toISOString()}>{installDateFormat.format(plugin.installedAt)}</time>
|
||||||
|
{:else}
|
||||||
|
Install date unknown
|
||||||
|
{/if}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<div class="controls">
|
||||||
|
<IconButton icon="folder-open" label="Show files" disabled={busy || plugin.removal} onclick={() => reveal(plugin.manifest.id)} />
|
||||||
{#if plugin.removal}
|
{#if plugin.removal}
|
||||||
<button disabled={busy} onclick={() => run(async () => { await invoke("plugins_retry_remove", { id: plugin.manifest.id }); await refreshPlugins(); message = "Plugin file cleanup completed."; })}><Icon icon="refresh" />Retry cleanup</button>
|
<button disabled={busy} onclick={() => run(async () => { await invoke("plugins_retry_remove", { id: plugin.manifest.id }); await refreshPlugins(); message = "Plugin file cleanup completed."; })}><Icon icon="refresh" />Retry cleanup</button>
|
||||||
{:else}
|
{:else}
|
||||||
<button class="danger" disabled={busy} aria-label={`Uninstall ${plugin.manifest.name}`} onclick={() => prepare(plugin)}><Icon icon="trash" />Uninstall</button>
|
<span class="danger"><IconButton icon="trash" label="Uninstall" disabled={busy} onclick={() => prepare(plugin)} /></span>
|
||||||
{/if}
|
{/if}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
</div>
|
||||||
{/each}
|
{/each}
|
||||||
{#if $restartPlugins.length}<p class="note" role="status">Restart RuneStone to clear all code from plugins that stopped in this window.</p>{/if}
|
{#if $restartPlugins.length}<p class="note" role="status">Restart RuneStone to clear all code from plugins that stopped in this window.</p>{/if}
|
||||||
{#if error}<p class="error" role="alert">{error}</p>{/if}
|
{#if error}<p class="error" role="alert">{error}</p>{/if}
|
||||||
<p class="saved" role="status">{message}</p>
|
<p class="saved" role="status">{message}</p>
|
||||||
|
|
||||||
{#if candidates.length || plan}
|
{#if candidates.length || plan || gitForm}
|
||||||
<dialog bind:this={modal} aria-labelledby="plugin-dialog-title" onkeydown={trap} oncancel={event => { event.preventDefault(); event.stopPropagation(); void cancel(); }}>
|
<dialog bind:this={modal} aria-labelledby="plugin-dialog-title" onkeydown={trap} oncancel={event => { event.preventDefault(); event.stopPropagation(); void cancel(); }}>
|
||||||
{#if plan}
|
{#if gitForm}
|
||||||
|
<h2 id="plugin-dialog-title">Install from Git link</h2>
|
||||||
|
<p>Get a Gitea release ZIP, then review it before installation. Git-link installation is an experimental feature.</p>
|
||||||
|
<form onsubmit={event => { event.preventDefault(); if (!busy) void fromGit(); }}>
|
||||||
|
<label class="field">Repository link<input type="url" required bind:value={gitUrl} disabled={busy} placeholder="https://host/owner/repository" /></label>
|
||||||
|
<label class="field">Release tag (optional)<input bind:value={gitTag} disabled={busy} placeholder="Latest release" maxlength="200" /></label>
|
||||||
|
<label class="field">Access token (optional)<input type="password" bind:value={gitToken} disabled={busy} autocomplete="off" /></label>
|
||||||
|
<p class="note">Private repositories need a token with read access. RuneStone does not save the token.</p>
|
||||||
|
{#if gitUrl.trim().startsWith("http:")}<p class="note">HTTP sends the token and package without encryption. Use it only for a trusted local server.</p>{/if}
|
||||||
|
{#if error}<p class="error" role="alert">{error}</p>{/if}
|
||||||
|
<footer><button type="button" bind:this={cancelButton} disabled={busy} onclick={() => cancel()}>Cancel</button><button type="submit" disabled={busy || !gitUrl.trim()}><Icon icon="link" />{busy ? "Downloading…" : "Review release"}</button></footer>
|
||||||
|
</form>
|
||||||
|
{:else if plan}
|
||||||
<h2 id="plugin-dialog-title">{`Uninstall ${plan.plugin.manifest.name}?`}</h2>
|
<h2 id="plugin-dialog-title">{`Uninstall ${plan.plugin.manifest.name}?`}</h2>
|
||||||
<p>{plan.plugin.manifest.author} · {plan.plugin.manifest.version}</p>
|
<p>{plan.plugin.manifest.author} · {plan.plugin.manifest.version}</p>
|
||||||
<p class="path">{plan.plugin.path}</p>
|
<p class="path">{plan.plugin.path}</p>
|
||||||
@@ -155,13 +197,18 @@
|
|||||||
button:hover:not(:disabled) { background: var(--rs-bg-active); }
|
button:hover:not(:disabled) { background: var(--rs-bg-active); }
|
||||||
button:disabled { opacity: .5; }
|
button:disabled { opacity: .5; }
|
||||||
.toolbar, .actions, footer { display: flex; align-items: center; flex-wrap: wrap; gap: 8px; }
|
.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; }
|
.card { background: var(--rs-bg-elevated); border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); padding: 0 14px 10px; margin-bottom: 10px; }
|
||||||
.row { display: flex; align-items: center; justify-content: space-between; gap: 20px; padding: 18px 0; }
|
.row { display: flex; align-items: center; justify-content: space-between; gap: 20px; padding: 14px 0 8px; }
|
||||||
|
.row > div { min-width: 0; overflow-wrap: anywhere; }
|
||||||
.row p { margin: 5px 0; font-size: 12px; }
|
.row p { margin: 5px 0; font-size: 12px; }
|
||||||
label { font-weight: 500; }
|
label { font-weight: 500; }
|
||||||
.path { overflow-wrap: anywhere; font-size: 11px; }
|
.path { overflow-wrap: anywhere; font-size: 11px; }
|
||||||
small, .badge, .note { color: var(--rs-text-dim); font-size: 12px; }
|
small, .badge, .note { color: var(--rs-text-dim); font-size: 12px; }
|
||||||
.badge { margin-right: auto; }
|
.status { display: flex; flex: 1 1 240px; flex-wrap: wrap; align-items: center; gap: 4px 12px; }
|
||||||
|
.controls { display: flex; align-items: center; gap: 6px; margin-left: auto; }
|
||||||
|
.controls :global(.icon-btn) { width: 32px; height: 32px; flex-basis: 32px; }
|
||||||
|
.controls .danger { display: flex; }
|
||||||
|
.controls .danger :global(.icon-btn) { color: var(--rs-error); }
|
||||||
.error { color: var(--rs-error); white-space: pre-wrap; }
|
.error { color: var(--rs-error); white-space: pre-wrap; }
|
||||||
.saved { color: var(--rs-ok); min-height: 20px; }
|
.saved { color: var(--rs-ok); min-height: 20px; }
|
||||||
.danger { color: var(--rs-error); }
|
.danger { color: var(--rs-error); }
|
||||||
@@ -174,4 +221,6 @@
|
|||||||
footer { justify-content: flex-end; margin-top: 24px; }
|
footer { justify-content: flex-end; margin-top: 24px; }
|
||||||
.candidate { padding: 16px 0; border-bottom: 1px solid var(--rs-border); }
|
.candidate { padding: 16px 0; border-bottom: 1px solid var(--rs-border); }
|
||||||
.candidate label { display: flex; gap: 8px; }
|
.candidate label { display: flex; gap: 8px; }
|
||||||
|
.field { display: flex; flex-direction: column; gap: 6px; margin: 14px 0; }
|
||||||
|
.field input { min-width: 0; padding: 8px 10px; color: var(--rs-text); background: var(--rs-bg-elevated); border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); }
|
||||||
</style>
|
</style>
|
||||||
|
|||||||
@@ -12,7 +12,7 @@
|
|||||||
const view = $pluginView;
|
const view = $pluginView;
|
||||||
const element = host;
|
const element = host;
|
||||||
const modal = dialog;
|
const modal = dialog;
|
||||||
if (!view || !element || !modal) return;
|
if (!view || view.placement === "editor" || !element || !modal) return;
|
||||||
previous = document.activeElement instanceof HTMLElement ? document.activeElement : null;
|
previous = document.activeElement instanceof HTMLElement ? document.activeElement : null;
|
||||||
modal.showModal(); error = "";
|
modal.showModal(); error = "";
|
||||||
let cancelled = false;
|
let cancelled = false;
|
||||||
@@ -41,8 +41,8 @@
|
|||||||
{/if}
|
{/if}
|
||||||
</div>
|
</div>
|
||||||
{/if}
|
{/if}
|
||||||
{#if error && !$pluginView}<p class="error" role="alert">{error}<button onclick={() => error = ""}>Dismiss</button></p>{/if}
|
{#if error && $pluginView?.placement !== "dialog"}<p class="error" role="alert">{error}<button onclick={() => error = ""}>Dismiss</button></p>{/if}
|
||||||
{#if $pluginView}
|
{#if $pluginView?.placement === "dialog"}
|
||||||
<dialog bind:this={dialog} aria-label={$pluginView.title} oncancel={event => { event.preventDefault(); pluginView.set(null); }}>
|
<dialog bind:this={dialog} aria-label={$pluginView.title} oncancel={event => { event.preventDefault(); pluginView.set(null); }}>
|
||||||
<header><h2>{$pluginView.title}</h2><IconButton icon="close" label="Close plugin view" onclick={() => pluginView.set(null)} /></header>
|
<header><h2>{$pluginView.title}</h2><IconButton icon="close" label="Close plugin view" onclick={() => pluginView.set(null)} /></header>
|
||||||
{#if error}<p class="error" role="alert">{error}</p>{/if}
|
{#if error}<p class="error" role="alert">{error}</p>{/if}
|
||||||
|
|||||||
+135
-9
@@ -1,14 +1,20 @@
|
|||||||
import { writable } from "svelte/store";
|
import { get, writable } from "svelte/store";
|
||||||
import { invoke, isTauri } from "@tauri-apps/api/core";
|
import { invoke, isTauri } from "@tauri-apps/api/core";
|
||||||
import { listen } from "@tauri-apps/api/event";
|
import { listen } from "@tauri-apps/api/event";
|
||||||
import { workspaceList, workspaceRead, workspaceWrite } from "../workspace/api";
|
import { workspaceList, workspaceRead, workspaceReadBytes, workspaceWrite } from "../workspace/api";
|
||||||
import { ExternalSession, deadline } from "./externalSession";
|
import { ExternalSession, deadline } from "./externalSession";
|
||||||
import type { PluginModule, PluginSnapshot, InstalledPlugin, Dispose } from "./sdk";
|
import type { PluginModule, PluginSnapshot, InstalledPlugin, Dispose, PluginView, PluginDocumentContext, PluginDocumentType } from "./sdk";
|
||||||
|
|
||||||
export const installedPlugins = writable<PluginSnapshot>({ root: "", plugins: [] });
|
export const installedPlugins = writable<PluginSnapshot>({ root: "", plugins: [] });
|
||||||
export const externalErrors = writable<Record<string, string>>({});
|
export const externalErrors = writable<Record<string, string>>({});
|
||||||
export const pluginTools = writable<{ owner: string; id: string; title: string; kind: "command" | "view" }[]>([]);
|
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 interface OpenPluginView { key: string; owner: string; id: string; title: string; placement: "dialog" | "editor"; document?: PluginDocumentContext; icon?: "kanban" | "file" }
|
||||||
|
export const pluginView = writable<OpenPluginView | null>(null);
|
||||||
|
export const pluginEditors = writable<OpenPluginView[]>([]);
|
||||||
|
export const pluginDocumentTypes = writable<{ owner: string; type: PluginDocumentType }[]>([]);
|
||||||
|
export const pluginDocuments = writable<Record<string, { icon: "kanban" | "file"; title: string }>>({});
|
||||||
|
export const pluginNavigation = writable<{ owner: string; id: string; title: string; icon?: PluginView["icon"] }[]>([]);
|
||||||
|
export const pluginEditorActive = writable(false);
|
||||||
export const pluginServiceError = writable("");
|
export const pluginServiceError = writable("");
|
||||||
export const restartPlugins = writable<string[]>([]);
|
export const restartPlugins = writable<string[]>([]);
|
||||||
const sessions = new Map<string, { hash: string; session: ExternalSession }>();
|
const sessions = new Map<string, { hash: string; session: ExternalSession }>();
|
||||||
@@ -18,8 +24,98 @@ const restarted = new Set<string>();
|
|||||||
let queue: Promise<void> = Promise.resolve();
|
let queue: Promise<void> = Promise.resolve();
|
||||||
let started = false;
|
let started = false;
|
||||||
let generation = 0;
|
let generation = 0;
|
||||||
|
let documentOpenVersion = 0;
|
||||||
|
export function cancelPluginDocumentOpen() { documentOpenVersion++; }
|
||||||
|
const workspaceListeners = new Set<() => void>();
|
||||||
|
let renameDocument: ((path: string, name: string) => Promise<string>) | undefined;
|
||||||
|
export function handlePluginDocumentRename(handler: (path: string, name: string) => Promise<string>): () => void {
|
||||||
|
renameDocument = handler;
|
||||||
|
return () => { if (renameDocument === handler) renameDocument = undefined; };
|
||||||
|
}
|
||||||
|
let canWrite: (path: string) => void = () => {};
|
||||||
|
export function guardPluginWrites(guard: (path: string) => void): () => void {
|
||||||
|
canWrite = guard;
|
||||||
|
return () => { if (canWrite === guard) canWrite = () => {}; };
|
||||||
|
}
|
||||||
|
export function notifyPluginWorkspace() { for (const listener of workspaceListeners) listener(); }
|
||||||
|
export function selectPluginEditor(view: OpenPluginView) { cancelPluginDocumentOpen(); pluginView.set(view); pluginEditorActive.set(true); }
|
||||||
|
export function closePluginEditor(key: string) {
|
||||||
|
cancelPluginDocumentOpen();
|
||||||
|
const remaining = get(pluginEditors).filter(view => view.key !== key);
|
||||||
|
pluginEditors.set(remaining);
|
||||||
|
if (get(pluginView)?.key === key) {
|
||||||
|
pluginView.set(remaining.at(-1) ?? null);
|
||||||
|
pluginEditorActive.set(remaining.length > 0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
export function renamePluginDocuments(from: string, to: string) {
|
||||||
|
const editors = get(pluginEditors).map(view => {
|
||||||
|
const path = view.document?.path;
|
||||||
|
if (!path || (path !== from && !path.startsWith(from + "/"))) return view;
|
||||||
|
view.document!.path = to + path.slice(from.length);
|
||||||
|
return { ...view, title: documentTitle(view.document!.path) };
|
||||||
|
});
|
||||||
|
pluginEditors.set(editors);
|
||||||
|
const selected = editors.find(view => view.key === get(pluginView)?.key);
|
||||||
|
if (selected) pluginView.set(selected);
|
||||||
|
pluginDocuments.set({}); notifyPluginWorkspace();
|
||||||
|
}
|
||||||
|
export function removePluginDocuments(path: string) {
|
||||||
|
for (const view of get(pluginEditors)) if (view.document && (view.document.path === path || view.document.path.startsWith(path + "/"))) closePluginEditor(view.key);
|
||||||
|
pluginDocuments.set({}); notifyPluginWorkspace();
|
||||||
|
}
|
||||||
|
const documentTitle = (path: string) => path.split("/").at(-1)!.replace(/\.[^.]+$/, "");
|
||||||
|
async function identifyDocument(path: string) {
|
||||||
|
const types = get(pluginDocumentTypes).filter(({ type }) => type.extensions.includes(path.split(".").at(-1)!.toLowerCase()));
|
||||||
|
if (!types.length) return null;
|
||||||
|
let source: string | undefined;
|
||||||
|
for (const { owner, type } of types) {
|
||||||
|
if (!sessions.has(owner)) continue;
|
||||||
|
try {
|
||||||
|
if (type.content !== "binary" && source === undefined) source = await workspaceRead(path);
|
||||||
|
const result = type.identify(path, type.content === "binary" ? "" : source!);
|
||||||
|
if (result && typeof result.id === "string" && result.id.trim()) return { owner, type, document: { id: result.id, path } };
|
||||||
|
} catch { /* Invalid documents remain available in the text editor. */ }
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
export async function inspectPluginDocuments(entries: { rel_path: string; kind: string }[]) {
|
||||||
|
const updates: Record<string, { icon: "kanban" | "file"; title: string } | null> = {};
|
||||||
|
await Promise.all(entries.filter(entry => entry.kind === "file").map(async entry => {
|
||||||
|
try { const match = await identifyDocument(entry.rel_path); updates[entry.rel_path] = match ? { icon: match.type.icon ?? "file", title: match.type.title } : null; }
|
||||||
|
catch { updates[entry.rel_path] = null; }
|
||||||
|
}));
|
||||||
|
pluginDocuments.update(current => {
|
||||||
|
const next = { ...current };
|
||||||
|
for (const [path, value] of Object.entries(updates)) { if (value) next[path] = value; else delete next[path]; }
|
||||||
|
return next;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
export async function openPluginDocument(path: string, current: () => boolean = () => true): Promise<boolean> {
|
||||||
|
const request = ++documentOpenVersion;
|
||||||
|
const match = await identifyDocument(path);
|
||||||
|
if (request !== documentOpenVersion || !current()) return true;
|
||||||
|
if (!match) return false;
|
||||||
|
const { owner, type, document } = match;
|
||||||
|
const existing = get(pluginEditors).find(view => view.owner === owner && view.id === type.id && view.document?.path === path && view.document.id === document.id);
|
||||||
|
if (existing) { selectPluginEditor(existing); return true; }
|
||||||
|
const view: OpenPluginView = { key: crypto.randomUUID(), owner, id: type.id, title: documentTitle(path), placement: "editor", document, icon: type.icon };
|
||||||
|
pluginEditors.update(views => [...views, view]); selectPluginEditor(view);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
export async function createPluginDocument(owner: string, id: string, path: string) {
|
||||||
|
const session = sessions.get(owner)?.session;
|
||||||
|
const create = session?.documentTypes.get(id)?.create;
|
||||||
|
if (!create || session!.controller.signal.aborted) throw new Error("This document type is unavailable.");
|
||||||
|
const contents = create.contents();
|
||||||
|
if (typeof contents !== "string") throw new Error("Document contents must be text.");
|
||||||
|
await invoke("workspace_create", { rel: path, kind: "file", contents });
|
||||||
|
notifyPluginWorkspace();
|
||||||
|
}
|
||||||
|
|
||||||
function publish() {
|
function publish() {
|
||||||
|
pluginNavigation.set([...sessions].flatMap(([owner, { session }]) => [...session.views.values()].filter(view => view.navigation).map(view => ({ owner, id: view.id, title: view.title, icon: view.icon }))));
|
||||||
|
pluginDocumentTypes.set([...sessions].flatMap(([owner, { session }]) => [...session.documentTypes.values()].map(type => ({ owner, type }))));
|
||||||
pluginTools.set([...sessions].flatMap(([owner, { session }]) => [
|
pluginTools.set([...sessions].flatMap(([owner, { session }]) => [
|
||||||
...[...session.commands.values()].map(({ id, title }) => ({ owner, id, title, kind: "command" as const })),
|
...[...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 })),
|
...[...session.views.values()].map(({ id, title }) => ({ owner, id, title, kind: "view" as const })),
|
||||||
@@ -34,6 +130,8 @@ async function stop(id: string) {
|
|||||||
const loaded = sessions.get(id);
|
const loaded = sessions.get(id);
|
||||||
if (!loaded) return;
|
if (!loaded) return;
|
||||||
sessions.delete(id);
|
sessions.delete(id);
|
||||||
|
for (const view of get(pluginEditors)) if (view.owner === id) closePluginEditor(view.key);
|
||||||
|
pluginDocuments.set({});
|
||||||
pluginView.update(view => view?.owner === id ? null : view);
|
pluginView.update(view => view?.owner === id ? null : view);
|
||||||
restarted.add(id); restartPlugins.set([...restarted]);
|
restarted.add(id); restartPlugins.set([...restarted]);
|
||||||
let error: string | undefined;
|
let error: string | undefined;
|
||||||
@@ -42,19 +140,47 @@ async function stop(id: string) {
|
|||||||
}
|
}
|
||||||
function show(owner: string, id: string) {
|
function show(owner: string, id: string) {
|
||||||
const view = sessions.get(owner)?.session.views.get(id);
|
const view = sessions.get(owner)?.session.views.get(id);
|
||||||
if (view) pluginView.set({ owner, id, title: view.title });
|
if (view) {
|
||||||
|
const placement = view.placement ?? "dialog";
|
||||||
|
if (placement === "editor") {
|
||||||
|
const existing = get(pluginEditors).find(item => item.owner === owner && item.id === id && !item.document);
|
||||||
|
const editor: OpenPluginView = existing ?? { key: crypto.randomUUID(), owner, id, title: view.title, placement };
|
||||||
|
if (!existing) pluginEditors.update(views => [...views, editor]);
|
||||||
|
selectPluginEditor(editor); return;
|
||||||
|
}
|
||||||
|
const current = get(pluginView);
|
||||||
|
if (current?.owner !== owner || current.id !== id) {
|
||||||
|
pluginView.set({ key: crypto.randomUUID(), owner, id, title: view.title, placement });
|
||||||
|
}
|
||||||
|
pluginEditorActive.set(false);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
async function activate(row: InstalledPlugin) {
|
async function activate(row: InstalledPlugin) {
|
||||||
const id = row.manifest.id;
|
const id = row.manifest.id;
|
||||||
let leased = false;
|
let leased = false;
|
||||||
const session = new ExternalSession(id, {
|
const session = new ExternalSession(id, {
|
||||||
workspace: { list: path => workspaceList(path ?? ""), read: workspaceRead, write: workspaceWrite },
|
workspace: {
|
||||||
|
list: path => workspaceList(path ?? ""), read: workspaceRead,
|
||||||
|
readBytes: workspaceReadBytes,
|
||||||
|
write: async (path, source, expected) => { canWrite(path); await workspaceWrite(path, source, expected); notifyPluginWorkspace(); },
|
||||||
|
subscribe: listener => { workspaceListeners.add(listener); return () => { workspaceListeners.delete(listener); }; },
|
||||||
|
readOptional: rel => invoke<string | null>("workspace_read", { rel, missingOk: true }),
|
||||||
|
create: async (rel, contents) => { await invoke<void>("workspace_create", { rel, kind: "file", contents }); notifyPluginWorkspace(); },
|
||||||
|
},
|
||||||
settings: {
|
settings: {
|
||||||
read: async () => JSON.parse(await invoke<string>("plugins_data", { id, value: null })),
|
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 }); },
|
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)) },
|
assets: { read: async path => Uint8Array.from(atob(await invoke<string>("plugins_asset", { id, path })), char => char.charCodeAt(0)) },
|
||||||
}, publish, view => show(id, view));
|
}, publish, view => show(id, view), undefined, async path => { if (!await openPluginDocument(path)) throw new Error("No enabled plugin recognizes this document."); }, async (document, name) => {
|
||||||
|
const match = await identifyDocument(document.path);
|
||||||
|
if (session.controller.signal.aborted) throw new Error("This plugin is disabled.");
|
||||||
|
if (!match || match.owner !== id || match.document.id !== document.id)
|
||||||
|
throw new Error("The document changed. Refresh before renaming it.");
|
||||||
|
if (!renameDocument) throw new Error("Document renaming is unavailable.");
|
||||||
|
canWrite(document.path);
|
||||||
|
return renameDocument(document.path, name);
|
||||||
|
});
|
||||||
try {
|
try {
|
||||||
const code = await invoke<string>("plugins_load", { id, hash: row.hash }); leased = true;
|
const code = await invoke<string>("plugins_load", { id, hash: row.hash }); leased = true;
|
||||||
const url = URL.createObjectURL(new Blob([code], { type: "text/javascript" }));
|
const url = URL.createObjectURL(new Blob([code], { type: "text/javascript" }));
|
||||||
@@ -104,10 +230,10 @@ export async function runPluginCommand(owner: string, id: string) {
|
|||||||
try { await sessions.get(owner)?.session.run(id); } catch (error) { report(owner, error); throw error; }
|
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 function openPluginView(owner: string, id: string) { show(owner, id); }
|
||||||
export async function mountPluginView(owner: string, id: string, element: HTMLElement): Promise<Dispose> {
|
export async function mountPluginView(owner: string, id: string, element: HTMLElement, document?: PluginDocumentContext): Promise<Dispose> {
|
||||||
const session = sessions.get(owner)?.session;
|
const session = sessions.get(owner)?.session;
|
||||||
if (!session) throw new Error("The plugin is disabled.");
|
if (!session) throw new Error("The plugin is disabled.");
|
||||||
return session.mount(id, element);
|
return session.mount(id, element, document);
|
||||||
}
|
}
|
||||||
export function startExternalPlugins(): () => void {
|
export function startExternalPlugins(): () => void {
|
||||||
if (!isTauri() || started) return () => {};
|
if (!isTauri() || started) return () => {};
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { pluginHost, type ContributionRegistry } from "./registry.ts";
|
import { pluginHost, type ContributionRegistry } from "./registry.ts";
|
||||||
import type { Dispose, PluginApi, PluginCommand, PluginModule, PluginView } from "./sdk.ts";
|
import type { Dispose, PluginApi, PluginCommand, PluginModule, PluginView, PluginDocumentType, PluginDocumentContext } from "./sdk.ts";
|
||||||
|
|
||||||
export function deadline<T>(work: Promise<T>, milliseconds = 5000): Promise<T> {
|
export function deadline<T>(work: Promise<T>, milliseconds = 5000): Promise<T> {
|
||||||
let timer: ReturnType<typeof setTimeout>;
|
let timer: ReturnType<typeof setTimeout>;
|
||||||
@@ -11,6 +11,7 @@ export class ExternalSession {
|
|||||||
readonly controller = new AbortController();
|
readonly controller = new AbortController();
|
||||||
readonly commands = new Map<string, PluginCommand>();
|
readonly commands = new Map<string, PluginCommand>();
|
||||||
readonly views = new Map<string, PluginView>();
|
readonly views = new Map<string, PluginView>();
|
||||||
|
readonly documentTypes = new Map<string, PluginDocumentType>();
|
||||||
private cleanups: Dispose[] = [];
|
private cleanups: Dispose[] = [];
|
||||||
private stopped = false;
|
private stopped = false;
|
||||||
private activation: Promise<void> = Promise.resolve();
|
private activation: Promise<void> = Promise.resolve();
|
||||||
@@ -23,7 +24,11 @@ export class ExternalSession {
|
|||||||
private services: Pick<PluginApi, "workspace" | "settings" | "assets">;
|
private services: Pick<PluginApi, "workspace" | "settings" | "assets">;
|
||||||
private changed: () => void;
|
private changed: () => void;
|
||||||
private show: (id: string) => void;
|
private show: (id: string) => void;
|
||||||
constructor(id: string, services: Pick<PluginApi, "workspace" | "settings" | "assets">, changed: () => void, show: (id: string) => void, registry: ContributionRegistry = pluginHost) {
|
private openDocument: (path: string) => Promise<void>;
|
||||||
|
private renameDocument?: PluginApi["renameDocument"];
|
||||||
|
constructor(id: string, services: Pick<PluginApi, "workspace" | "settings" | "assets">, changed: () => void, show: (id: string) => void, registry: ContributionRegistry = pluginHost, openDocument: (path: string) => Promise<void> = async () => { throw new Error("Document views are unavailable."); }, renameDocument?: PluginApi["renameDocument"]) {
|
||||||
|
this.openDocument = openDocument;
|
||||||
|
this.renameDocument = renameDocument;
|
||||||
this.registry = registry; this.id = id; this.services = services; this.changed = changed; this.show = show;
|
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."); }
|
private check() { if (this.stopped) throw new Error("This plugin is disabled."); }
|
||||||
@@ -37,12 +42,33 @@ export class ExternalSession {
|
|||||||
id: this.id, signal: this.controller.signal,
|
id: this.id, signal: this.controller.signal,
|
||||||
contribute: (key, value) => { this.check(); this.contributions.push(this.registry.register(this.id, key, value)); },
|
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); },
|
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); },
|
registerView: item => { if (item.placement !== undefined && !["dialog", "editor"].includes(item.placement)) throw new Error("Unknown plugin view placement."); if (typeof item.mount !== "function") throw new Error("A view needs a mount function."); register(this.views, item); },
|
||||||
|
registerDocumentType: item => {
|
||||||
|
if (item.content !== undefined && !["text", "binary"].includes(item.content)) throw new Error("Invalid document content type.");
|
||||||
|
if (typeof item.identify !== "function" || typeof item.mount !== "function" || !Array.isArray(item.extensions) || !item.extensions.length || item.extensions.some(ext => !/^[a-z0-9]+$/.test(ext)) || (item.icon && !["kanban", "file"].includes(item.icon))) throw new Error("Invalid document type.");
|
||||||
|
if (item.create && (!item.create.label?.trim() || !item.create.defaultName?.trim() || !item.extensions.includes(item.create.extension) || typeof item.create.contents !== "function")) throw new Error("Invalid document creation action.");
|
||||||
|
register(this.documentTypes, item);
|
||||||
|
},
|
||||||
|
openDocument: path => { this.check(); return this.openDocument(path); },
|
||||||
|
...(this.renameDocument ? { renameDocument: (document: PluginDocumentContext, name: string) => { this.check(); return this.renameDocument!(document, name); } } : {}),
|
||||||
openView: id => { this.check(); if (!this.views.has(id)) throw new Error("Unknown plugin view."); this.show(id); },
|
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); },
|
onDispose: cleanup => { this.check(); if (typeof cleanup !== "function") throw new Error("Cleanup must be a function."); this.cleanups.push(cleanup); },
|
||||||
workspace: {
|
workspace: {
|
||||||
|
...(this.services.workspace.subscribe ? { subscribe: (listener: () => void) => {
|
||||||
|
this.check(); const off = this.services.workspace.subscribe!(() => { if (!this.stopped) listener(); });
|
||||||
|
let active = true;
|
||||||
|
const cleanup: Dispose = () => {
|
||||||
|
if (!active) return;
|
||||||
|
active = false; this.cleanups = this.cleanups.filter(item => item !== cleanup);
|
||||||
|
return off();
|
||||||
|
};
|
||||||
|
this.cleanups.push(cleanup); return cleanup;
|
||||||
|
} } : {}),
|
||||||
list: path => { this.check(); return this.services.workspace.list(path); },
|
list: path => { this.check(); return this.services.workspace.list(path); },
|
||||||
read: path => { this.check(); return this.services.workspace.read(path); },
|
read: path => { this.check(); return this.services.workspace.read(path); },
|
||||||
|
...(this.services.workspace.readBytes ? { readBytes: (path: string) => { this.check(); return this.services.workspace.readBytes!(path); } } : {}),
|
||||||
|
...(this.services.workspace.readOptional ? { readOptional: (path: string) => { this.check(); return this.services.workspace.readOptional!(path); } } : {}),
|
||||||
|
...(this.services.workspace.create ? { create: (path: string, contents: string) => { this.check(); return this.services.workspace.create!(path, contents); } } : {}),
|
||||||
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); },
|
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: {
|
settings: {
|
||||||
@@ -62,10 +88,10 @@ export class ExternalSession {
|
|||||||
await deadline(this.activation);
|
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 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> {
|
async mount(id: string, element: HTMLElement, document?: PluginDocumentContext): Promise<Dispose> {
|
||||||
this.check(); const view = this.views.get(id); if (!view) throw new Error("Unknown plugin view.");
|
this.check(); const view = document ? this.documentTypes.get(id) : this.views.get(id); if (!view) throw new Error("Unknown plugin view.");
|
||||||
let cleaning: Promise<void> | undefined;
|
let cleaning: Promise<void> | undefined;
|
||||||
const pending = Promise.resolve().then(() => { this.check(); return view.mount(element); });
|
const pending = Promise.resolve().then(() => { this.check(); return document ? (view as PluginDocumentType).mount(element, document) : (view as PluginView).mount(element); });
|
||||||
const cleanup = () => {
|
const cleanup = () => {
|
||||||
cleaning ??= (async () => {
|
cleaning ??= (async () => {
|
||||||
const dispose = await pending;
|
const dispose = await pending;
|
||||||
@@ -81,7 +107,7 @@ export class ExternalSession {
|
|||||||
}
|
}
|
||||||
stop(): Promise<void> {
|
stop(): Promise<void> {
|
||||||
if (this.stopping) return this.stopping;
|
if (this.stopping) return this.stopping;
|
||||||
this.stopped = true; this.controller.abort(); this.commands.clear(); this.views.clear(); this.changed();
|
this.stopped = true; this.controller.abort(); this.commands.clear(); this.views.clear(); this.documentTypes.clear(); this.changed();
|
||||||
for (const remove of this.contributions.splice(0)) remove();
|
for (const remove of this.contributions.splice(0)) remove();
|
||||||
this.stopping = (async () => {
|
this.stopping = (async () => {
|
||||||
const errors: unknown[] = [];
|
const errors: unknown[] = [];
|
||||||
|
|||||||
+20
-2
@@ -2,19 +2,37 @@ import type { Contributions } from "./contracts.ts";
|
|||||||
/** Package API v1. Compiled plugins export activate(api). */
|
/** Package API v1. Compiled plugins export activate(api). */
|
||||||
export type Dispose = () => void | Promise<void>;
|
export type Dispose = () => void | Promise<void>;
|
||||||
export interface PluginCommand { id: string; title: string; run: () => 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 PluginView { id: string; title: string; placement?: "dialog" | "editor"; navigation?: boolean; icon?: "list" | "kanban" | "puzzle"; mount: (container: HTMLElement) => void | Dispose | Promise<void | Dispose> }
|
||||||
|
export interface PluginDocumentContext { id: string; path: string }
|
||||||
|
export interface PluginDocumentType {
|
||||||
|
id: string;
|
||||||
|
title: string;
|
||||||
|
icon?: "kanban" | "file";
|
||||||
|
extensions: string[];
|
||||||
|
content?: "text" | "binary";
|
||||||
|
identify(path: string, source: string): { id: string } | null;
|
||||||
|
create?: { label: string; defaultName: string; extension: string; contents(): string };
|
||||||
|
mount(container: HTMLElement, document: PluginDocumentContext): void | Dispose | Promise<void | Dispose>;
|
||||||
|
}
|
||||||
export interface PluginApi {
|
export interface PluginApi {
|
||||||
readonly id: string;
|
readonly id: string;
|
||||||
readonly signal: AbortSignal;
|
readonly signal: AbortSignal;
|
||||||
contribute<K extends keyof Contributions>(key: K, value: Contributions[K]): void;
|
contribute<K extends keyof Contributions>(key: K, value: Contributions[K]): void;
|
||||||
registerCommand(command: PluginCommand): void;
|
registerCommand(command: PluginCommand): void;
|
||||||
registerView(view: PluginView): void;
|
registerView(view: PluginView): void;
|
||||||
|
registerDocumentType(type: PluginDocumentType): void;
|
||||||
|
openDocument(path: string): Promise<void>;
|
||||||
|
renameDocument?(document: PluginDocumentContext, name: string): Promise<string>;
|
||||||
openView(id: string): void;
|
openView(id: string): void;
|
||||||
onDispose(cleanup: Dispose): void;
|
onDispose(cleanup: Dispose): void;
|
||||||
workspace: {
|
workspace: {
|
||||||
list(path?: string): Promise<{ name: string; rel_path: string; kind: string }[]>;
|
list(path?: string): Promise<{ name: string; rel_path: string; kind: string }[]>;
|
||||||
read(path: string): Promise<string>;
|
read(path: string): Promise<string>;
|
||||||
|
readBytes?(path: string): Promise<Uint8Array>;
|
||||||
|
readOptional?(path: string): Promise<string | null>;
|
||||||
|
create?(path: string, contents: string): Promise<void>;
|
||||||
write(path: string, contents: string, expected: string): Promise<void>;
|
write(path: string, contents: string, expected: string): Promise<void>;
|
||||||
|
subscribe?(listener: () => void): Dispose;
|
||||||
};
|
};
|
||||||
settings: { read(): Promise<unknown>; write(value: unknown): Promise<void> };
|
settings: { read(): Promise<unknown>; write(value: unknown): Promise<void> };
|
||||||
assets: { read(path: string): Promise<Uint8Array> };
|
assets: { read(path: string): Promise<Uint8Array> };
|
||||||
@@ -24,7 +42,7 @@ export interface ExternalManifest {
|
|||||||
schemaVersion: 1; id: string; name: string; author: string; description: string;
|
schemaVersion: 1; id: string; name: string; author: string; description: string;
|
||||||
version: string; apiVersion: 1; entry: string; access: "full-app";
|
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 InstalledPlugin { manifest: ExternalManifest; hash: string; enabled: boolean; installedAt: number | null; path: string; error: string | null; removal: boolean }
|
||||||
export interface PluginSnapshot { root: string; plugins: InstalledPlugin[] }
|
export interface PluginSnapshot { root: string; plugins: InstalledPlugin[] }
|
||||||
export interface Candidate { token: string; source: string; manifest: ExternalManifest | null; error: string | null }
|
export interface Candidate { token: string; source: string; manifest: ExternalManifest | null; error: string | null }
|
||||||
export interface RemovalPlan { token: string; plugin: InstalledPlugin }
|
export interface RemovalPlan { token: string; plugin: InstalledPlugin }
|
||||||
|
|||||||
@@ -1,5 +1,12 @@
|
|||||||
:root {
|
:root {
|
||||||
--rs-control-radius: 5px;
|
--rs-control-radius: 5px;
|
||||||
|
--rs-menu-width: 264px;
|
||||||
|
--rs-menu-padding: 5px;
|
||||||
|
--rs-menu-row-height: 30px;
|
||||||
|
--rs-menu-row-padding: 6px 10px;
|
||||||
|
--rs-menu-icon-size: 17px;
|
||||||
|
--rs-menu-icon-gap: 10px;
|
||||||
|
--rs-menu-shadow: 0 8px 30px #0006;
|
||||||
--rs-item-selection-radius: var(--rs-control-radius);
|
--rs-item-selection-radius: var(--rs-control-radius);
|
||||||
--rs-item-selection-bg: color-mix(in srgb, var(--rs-accent) 20%, transparent);
|
--rs-item-selection-bg: color-mix(in srgb, var(--rs-accent) 20%, transparent);
|
||||||
--rs-item-selection-border: var(--rs-accent);
|
--rs-item-selection-border: var(--rs-accent);
|
||||||
|
|||||||
@@ -10,7 +10,7 @@
|
|||||||
<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" />
|
<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"}
|
{: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" />
|
<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"}
|
{:else if icon === "up" || icon === "down" || icon === "kanban" || icon === "link"}
|
||||||
{@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" />
|
||||||
|
|||||||
@@ -5,6 +5,8 @@
|
|||||||
| "settings"
|
| "settings"
|
||||||
| "help"
|
| "help"
|
||||||
| "puzzle"
|
| "puzzle"
|
||||||
|
| "link"
|
||||||
|
| "kanban"
|
||||||
| "split"
|
| "split"
|
||||||
| "more"
|
| "more"
|
||||||
| "chevron-down"
|
| "chevron-down"
|
||||||
|
|||||||
@@ -1,5 +1,10 @@
|
|||||||
// Stroke icons share the same 24px grid and weight as IconButton.
|
// Stroke icons share the same 24px grid and weight as IconButton.
|
||||||
export const actionIcons = {
|
export const actionIcons = {
|
||||||
|
kanban: '<rect x="3" y="4" width="5" height="16" rx="1"/><rect x="10" y="4" width="5" height="11" rx="1"/><rect x="17" y="4" width="4" height="7" rx="1"/>',
|
||||||
|
bookmark: '<path d="M6 4h12v16l-6-3-6 3z"/>',
|
||||||
|
'file-plus': '<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8zM14 2v6h6M12 18v-6M9 15h6"/>',
|
||||||
|
'folder-plus': '<path d="M4 20h16a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.7-.9L9.2 3.9A2 2 0 0 0 7.5 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2zM12 10v6M9 13h6"/>',
|
||||||
|
|
||||||
pin: '<path d="m16 3 5 5-4 1-3 3 1 4-2 2-7-7 2-2 4 1 3-3ZM8 16l-5 5"/>',
|
pin: '<path d="m16 3 5 5-4 1-3 3 1 4-2 2-7-7 2-2 4 1 3-3ZM8 16l-5 5"/>',
|
||||||
book: '<path d="M12 6v15M3 3h5a4 4 0 0 1 4 3 4 4 0 0 1 4-3h5v15h-5a4 4 0 0 0-4 3 4 4 0 0 0-4-3H3Z"/>',
|
book: '<path d="M12 6v15M3 3h5a4 4 0 0 1 4 3 4 4 0 0 1 4-3h5v15h-5a4 4 0 0 0-4 3 4 4 0 0 0-4-3H3Z"/>',
|
||||||
folder: '<path d="M3 7V4h6l3 3h9v13H3Z"/>',
|
folder: '<path d="M3 7V4h6l3 3h9v13H3Z"/>',
|
||||||
|
|||||||
@@ -1,9 +1,9 @@
|
|||||||
import { actionIcon, type ActionIcon } from "./actionIcons";
|
import { actionIcon, type ActionIcon } from "./actionIcons";
|
||||||
|
|
||||||
export type ActionMenuItem = { label: string; icon: ActionIcon; shortcut?: string; run?: () => void; children?: ActionMenuItem[]; disabled?: boolean; title?: string } | { separator: true };
|
export type ActionMenuItem = { label: string; icon?: ActionIcon; shortcut?: string; run?: () => void; children?: ActionMenuItem[]; disabled?: boolean; title?: string } | { separator: true };
|
||||||
|
|
||||||
export function actionMenu(x: number, y: number, items: ActionMenuItem[], onClose: () => void, label = "Table actions") {
|
export function actionMenu(x: number, y: number, items: ActionMenuItem[], onClose: () => void, label = "Table actions") {
|
||||||
const root = document.createElement("div"); root.className = "table-cell-menu"; root.setAttribute("role", "menu"); root.setAttribute("aria-label", label);
|
const root = document.createElement("div"); root.className = "rs-menu table-cell-menu"; root.setAttribute("role", "menu"); root.setAttribute("aria-label", label);
|
||||||
let opened: HTMLElement | undefined, owner: HTMLButtonElement | undefined;
|
let opened: HTMLElement | undefined, owner: HTMLButtonElement | undefined;
|
||||||
if (label.startsWith("Terminal")) root.style.width = "min(430px, calc(100vw - 16px))";
|
if (label.startsWith("Terminal")) root.style.width = "min(430px, calc(100vw - 16px))";
|
||||||
const submenus = new Map<HTMLButtonElement, HTMLElement>();
|
const submenus = new Map<HTMLButtonElement, HTMLElement>();
|
||||||
@@ -25,12 +25,14 @@ export function actionMenu(x: number, y: number, items: ActionMenuItem[], onClos
|
|||||||
const button = document.createElement("button"); button.type = "button"; button.setAttribute("role", "menuitem"); button.disabled = !!item.disabled;
|
const button = document.createElement("button"); button.type = "button"; button.setAttribute("role", "menuitem"); button.disabled = !!item.disabled;
|
||||||
if (item.title) button.title = item.title;
|
if (item.title) button.title = item.title;
|
||||||
const label = document.createElement("span"); label.className = "action-label"; label.textContent = item.label;
|
const label = document.createElement("span"); label.className = "action-label"; label.textContent = item.label;
|
||||||
button.append(actionIcon(item.icon), label); panel.append(button);
|
const icon = item.icon ? actionIcon(item.icon) : document.createElement("span");
|
||||||
|
icon.classList.add("action-icon"); icon.setAttribute("aria-hidden", "true");
|
||||||
|
button.append(icon, label); panel.append(button);
|
||||||
if (item.shortcut) { const shortcut = document.createElement("span"); shortcut.textContent = item.shortcut; shortcut.style.cssText = "margin-left:auto;color:var(--rs-text-dim);font-size:12px;white-space:nowrap"; button.append(shortcut); }
|
if (item.shortcut) { const shortcut = document.createElement("span"); shortcut.textContent = item.shortcut; shortcut.style.cssText = "margin-left:auto;color:var(--rs-text-dim);font-size:12px;white-space:nowrap"; button.append(shortcut); }
|
||||||
if (item.children) {
|
if (item.children) {
|
||||||
button.setAttribute("aria-haspopup", "menu"); button.setAttribute("aria-expanded", "false");
|
button.setAttribute("aria-haspopup", "menu"); button.setAttribute("aria-expanded", "false");
|
||||||
const arrow = actionIcon("chevron"); arrow.classList.add("action-chevron"); button.append(arrow);
|
const arrow = actionIcon("chevron"); arrow.classList.add("action-chevron"); button.append(arrow);
|
||||||
const submenu = document.createElement("div"); submenu.className = "table-cell-submenu"; submenu.setAttribute("role", "menu"); submenu.setAttribute("aria-label", item.label); submenu.hidden = true;
|
const submenu = document.createElement("div"); submenu.className = "rs-menu table-cell-submenu"; submenu.setAttribute("role", "menu"); submenu.setAttribute("aria-label", item.label); submenu.hidden = true;
|
||||||
populate(submenu, item.children); root.append(submenu); submenus.set(button, submenu);
|
populate(submenu, item.children); root.append(submenu); submenus.set(button, submenu);
|
||||||
button.addEventListener("mousemove", () => { if (!button.disabled) reveal(button, submenu); });
|
button.addEventListener("mousemove", () => { if (!button.disabled) reveal(button, submenu); });
|
||||||
button.addEventListener("click", () => reveal(button, submenu, true));
|
button.addEventListener("click", () => reveal(button, submenu, true));
|
||||||
|
|||||||
@@ -0,0 +1,42 @@
|
|||||||
|
.rs-menu {
|
||||||
|
position: fixed;
|
||||||
|
z-index: 1000;
|
||||||
|
width: var(--rs-menu-width);
|
||||||
|
max-width: calc(100vw - 16px);
|
||||||
|
max-height: calc(100vh - 16px);
|
||||||
|
overflow-y: auto;
|
||||||
|
padding: var(--rs-menu-padding);
|
||||||
|
border: 1px solid var(--rs-border);
|
||||||
|
border-radius: var(--rs-control-radius);
|
||||||
|
background: var(--rs-bg-elevated);
|
||||||
|
color: var(--rs-text);
|
||||||
|
box-shadow: var(--rs-menu-shadow);
|
||||||
|
font: 13px/1.4 var(--rs-font-ui);
|
||||||
|
}
|
||||||
|
|
||||||
|
.rs-menu.table-cell-submenu { z-index: 1001; }
|
||||||
|
|
||||||
|
.rs-menu > button {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: var(--rs-menu-icon-gap);
|
||||||
|
width: 100%;
|
||||||
|
min-height: var(--rs-menu-row-height);
|
||||||
|
padding: var(--rs-menu-row-padding);
|
||||||
|
border: 0;
|
||||||
|
border-radius: var(--rs-control-radius);
|
||||||
|
background: transparent;
|
||||||
|
color: inherit;
|
||||||
|
font: inherit;
|
||||||
|
text-align: left;
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
|
||||||
|
.rs-menu > button:disabled { opacity: .4; cursor: default; }
|
||||||
|
.rs-menu > button:not(:disabled):is(:hover, :focus-visible, [aria-expanded="true"]) {
|
||||||
|
background: var(--rs-bg-active);
|
||||||
|
outline: none;
|
||||||
|
}
|
||||||
|
.rs-menu > hr { margin: 4px 0; border: 0; border-top: 1px solid var(--rs-border); }
|
||||||
|
.rs-menu > button > .action-icon { width: var(--rs-menu-icon-size); height: var(--rs-menu-icon-size); flex-basis: var(--rs-menu-icon-size); }
|
||||||
|
.rs-menu > button > .action-chevron { width: 13px; height: 13px; flex-basis: 13px; }
|
||||||
@@ -43,6 +43,10 @@ export function workspaceRead(rel: string): Promise<string> {
|
|||||||
return invoke("workspace_read", { rel });
|
return invoke("workspace_read", { rel });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export async function workspaceReadBytes(rel: string): Promise<Uint8Array> {
|
||||||
|
return new Uint8Array(await invoke<ArrayBuffer>("workspace_read_bytes", { rel }));
|
||||||
|
}
|
||||||
|
|
||||||
export function workspaceWrite(rel: string, contents: string, expected?: string): Promise<void> {
|
export function workspaceWrite(rel: string, contents: string, expected?: string): Promise<void> {
|
||||||
return invoke("workspace_write", { rel, contents, expected });
|
return invoke("workspace_write", { rel, contents, expected });
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -43,10 +43,16 @@ export function planTitleRename(fromRel: string, title: string): RenamePlan {
|
|||||||
/** The writing title edits the basename, keeping the note's Markdown format. */
|
/** The writing title edits the basename, keeping the note's Markdown format. */
|
||||||
export function planMarkdownTitleRename(fromRel: string, title: string): RenamePlan {
|
export function planMarkdownTitleRename(fromRel: string, title: string): RenamePlan {
|
||||||
const extension = fromRel.match(/\.(?:md|markdown|mdown)$/i)?.[0] ?? ".md";
|
const extension = fromRel.match(/\.(?:md|markdown|mdown)$/i)?.[0] ?? ".md";
|
||||||
|
return planDocumentTitleRename(fromRel, title, extension);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function planDocumentTitleRename(fromRel: string, title: string, extension = fromRel.match(/\.[^./]+$/)?.[0] ?? ""): RenamePlan {
|
||||||
const name = title.trim();
|
const name = title.trim();
|
||||||
|
if (!name || name.startsWith(".") || /[<>:"/\\|?*\u0000-\u001f]/.test(name))
|
||||||
|
return { action: "error", message: "Enter a document name without a leading dot or reserved filename characters." };
|
||||||
const current = fromRel.split("/").pop() ?? fromRel;
|
const current = fromRel.split("/").pop() ?? fromRel;
|
||||||
if (name === current.slice(0, -extension.length)) return { action: "noop" };
|
if (name === (extension ? current.slice(0, -extension.length) : current)) return { action: "noop" };
|
||||||
const stem = name.toLowerCase().endsWith(extension.toLowerCase())
|
const stem = extension && name.toLowerCase().endsWith(extension.toLowerCase())
|
||||||
? name.slice(0, -extension.length).trim() : name;
|
? name.slice(0, -extension.length).trim() : name;
|
||||||
if (!stem) return { action: "error", message: "Name is empty" };
|
if (!stem) return { action: "error", message: "Name is empty" };
|
||||||
return planRename(fromRel, stem + extension);
|
return planRename(fromRel, stem + extension);
|
||||||
|
|||||||
@@ -4,4 +4,6 @@
|
|||||||
let { children } = $props();
|
let { children } = $props();
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
|
<svelte:window oncontextmenu={(event) => event.preventDefault()} />
|
||||||
|
|
||||||
{@render children()}
|
{@render children()}
|
||||||
|
|||||||
Reference in New Issue
Block a user