From d3218b250129fe3e3e3579265ec14f1d9882f3dc Mon Sep 17 00:00:00 2001 From: Knotty Wyvern Date: Thu, 29 Oct 2026 15:51:21 -0700 Subject: [PATCH] Make Git a native feature with an off switch MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Add the native feature runtime in src/lib/features/: the catalog, the switches, the first-start migration, the loader, and the feature sessions. - Add Settings → Features and the features settings section. - Add features_legacy. It reads the old plugin packages and changes nothing. - Move Git from the plugin into src/lib/features/git/, on host internals. - Remove api.git, the git contribution key, and the SDK Git types. - Add pnpm check:features. It fails when a feature module loads at start. - Update the tests, the menu inventory, the docs, and UI-055. --- CLAUDE.md | 4 +- docs/design-decisions.md | 15 ++ docs/development.md | 36 ++- docs/guides/git.md | 53 ++++ docs/menu-surfaces.json | 15 +- docs/plugin-development.md | 27 +- docs/plugin-host.md | 2 + docs/plugins.md | 6 +- docs/ui-design.md | 6 +- docs/user-guide.md | 18 +- package.json | 1 + packages/plugin-sdk/src/api.ts | 2 - packages/plugin-sdk/src/contributions.ts | 2 - packages/plugin-sdk/src/features.ts | 13 - packages/plugin-sdk/src/git.ts | 64 ----- packages/plugin-sdk/src/index.ts | 1 - scripts/featureChunks.mjs | 80 ++++++ scripts/menuSurfaceAudit.mjs | 2 +- src-tauri/build.rs | 1 + src-tauri/capabilities/default.json | 1 + src-tauri/capabilities/settings.json | 1 + .../autogenerated/features_legacy.toml | 11 + src-tauri/src/features.rs | 42 +++ src-tauri/src/lib.rs | 2 + src-tauri/src/plugins.rs | 58 +++++ src-tauri/src/preferences.rs | 3 +- src/lib/features/catalog.ts | 68 +++++ src/lib/features/git/DiffText.svelte | 20 ++ src/lib/features/git/GitDiff.svelte | 39 +++ src/lib/features/git/GitGraph.svelte | 244 ++++++++++++++++++ src/lib/features/git/SourceControl.svelte | 201 +++++++++++++++ src/lib/features/git/index.ts | 62 +++++ src/lib/features/git/model.ts | 86 ++++++ src/lib/features/git/state.svelte.ts | 20 ++ src/lib/features/loader.ts | 41 +++ src/lib/features/migration.ts | 60 +++++ src/lib/features/session.ts | 81 ++++++ src/lib/features/state.ts | 41 +++ src/lib/features/types.ts | 26 ++ src/lib/git/contracts.ts | 66 ++++- src/lib/i18n/messages.ts | 72 ++++++ src/lib/layout/EditorPane.svelte | 6 +- src/lib/layout/SettingsDialog.svelte | 27 ++ src/lib/layout/Workbench.svelte | 10 +- src/lib/plugins/PluginAccessMenu.svelte | 3 +- src/lib/plugins/PluginEditor.svelte | 8 +- src/lib/plugins/external.ts | 49 +++- src/lib/plugins/externalSession.ts | 15 +- src/lib/plugins/registry.ts | 2 +- src/lib/settings/store.ts | 3 +- src/lib/ui/Icon.svelte | 6 + src/lib/ui/IconButton.svelte | 5 +- src/routes/+layout.ts | 3 + tests/smoke/_harness/index.mjs | 6 +- tests/smoke/appearance/density.smoke.mjs | 18 +- tests/smoke/browser/builtin.smoke.mjs | 6 +- tests/smoke/features/git.smoke.mjs | 113 ++++++++ tests/smoke/features/settings.smoke.mjs | 65 +++++ tests/smoke/plugins/gitToolbar.smoke.mjs | 76 ------ tests/smoke/tree/renameUndo.smoke.mjs | 35 +-- tests/unit/features/features.spec.ts | 138 ++++++++++ tests/unit/features/gitModel.spec.ts | 67 +++++ .../unit/plugins/pluginHostExtensions.spec.ts | 30 +-- tests/unit/plugins/plugins.spec.ts | 25 +- tests/unit/release/featureChunks.spec.ts | 41 +++ tests/unit/sdk/features.spec.ts | 15 +- tests/unit/settings/migration.spec.ts | 3 +- vite.config.js | 24 +- 68 files changed, 2068 insertions(+), 324 deletions(-) create mode 100644 docs/guides/git.md delete mode 100644 packages/plugin-sdk/src/git.ts create mode 100644 scripts/featureChunks.mjs create mode 100644 src-tauri/permissions/autogenerated/features_legacy.toml create mode 100644 src-tauri/src/features.rs create mode 100644 src/lib/features/catalog.ts create mode 100644 src/lib/features/git/DiffText.svelte create mode 100644 src/lib/features/git/GitDiff.svelte create mode 100644 src/lib/features/git/GitGraph.svelte create mode 100644 src/lib/features/git/SourceControl.svelte create mode 100644 src/lib/features/git/index.ts create mode 100644 src/lib/features/git/model.ts create mode 100644 src/lib/features/git/state.svelte.ts create mode 100644 src/lib/features/loader.ts create mode 100644 src/lib/features/migration.ts create mode 100644 src/lib/features/session.ts create mode 100644 src/lib/features/state.ts create mode 100644 src/lib/features/types.ts create mode 100644 tests/smoke/features/git.smoke.mjs create mode 100644 tests/smoke/features/settings.smoke.mjs delete mode 100644 tests/smoke/plugins/gitToolbar.smoke.mjs create mode 100644 tests/unit/features/features.spec.ts create mode 100644 tests/unit/features/gitModel.spec.ts create mode 100644 tests/unit/release/featureChunks.spec.ts diff --git a/CLAUDE.md b/CLAUDE.md index 6a252a4..37c25a0 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -2,7 +2,8 @@ RuneStone is a desktop workspace for Markdown notes, code, and project work in ordinary local files. A Tauri 2 host in Rust (`src-tauri/`) serves a Svelte 5 and TypeScript interface (`src/`). -Optional features are plugins. Each plugin is a separate repository beside this one, for example `../RuneStone_Terminal`. +Git is a native feature with an off switch in Settings → Features (`src/lib/features/`). It does not use the plugin API. +Other optional features are plugins. Each plugin is a separate repository beside this one, for example `../RuneStone_Terminal`. The [development guide](docs/development.md#architecture) maps the source folders. ## Skills @@ -24,6 +25,7 @@ The [development guide](docs/development.md#architecture) maps the source folder | `pnpm test` | Unit tests (`tests/unit/`) | | `cargo test --manifest-path src-tauri/Cargo.toml --lib` | Rust tests | | `pnpm check:menus` | Menu surface inventory | +| `pnpm check:features` | Build check: no native feature module loads at start | | `pnpm smoke [filter...]` | Browser smoke tests (`tests/smoke/`). See [Browser smoke tests](docs/development.md#browser-smoke-tests). | | `pnpm build:installer --version ` | Windows installer. See [Builds](docs/builds.md). | | `pnpm build:browser-engine --release-url --version ` | Browser engine ZIP and its pin. See [Build the browser engine](docs/builds.md#build-the-browser-engine). | diff --git a/docs/design-decisions.md b/docs/design-decisions.md index 648b145..e3120eb 100644 --- a/docs/design-decisions.md +++ b/docs/design-decisions.md @@ -1012,3 +1012,18 @@ Native shell, background image, and desktop acceptance remain open. - Evidence: `tests/smoke/browser/engine.smoke.mjs`, with screenshots of each state in both themes and a 360-pixel Settings window. - Replaces / replaced by: The bundled engine. - Limits: The download does not resume. A failed download starts again from zero. The engine installs for the current Windows account only. Browser checks mock the native download. + +### UI-055 — Settings → Features and native Git + +- Type: Rule change +- Date: 2026-10-29 +- Status: Implemented for user review +- Decision source: The owner decisions "Native features decision" and "Phase 7 replaced" of 2026-10-29, and Phase 7 decisions 1A, 2A, 3A, 4A, and 5C. +- Previous rule: Git was the optional Git plugin. Settings → Plug-ins enabled or disabled it. Its strings were English only, its file rows and buttons drew their own icons, and its status refreshed every 10 seconds. The "Show Git graph" command showed in the **Plug-in views** menu. +- New rule: Git is a native feature. A new Settings page, **Features**, between Appearance and Plug-ins, has one switch for each native feature with its name and one line of description. A feature that is off loads no code and shows no controls. A feature that is on loads its code at first need. Off applies at once in all windows. Source control uses the shared `IconButton`, tooltips, icons, and catalog. Its status refreshes after a workspace change, on window focus, and after each Git action. **Show Git graph** is in the command palette and in Source control. The new shared icons are `toggle`, `minus`, and `upload`. +- Reason: The owner chose response time and memory over the versatility of the plugin API. A switch lets users remove the controls of a feature that they do not use. +- Scope: Settings → Features, the Source control pane, the Git diff and Git graph tabs, the line history in the status bar, and the command palette. +- Shared implementation: `src/lib/features/`, `src/lib/layout/SettingsDialog.svelte`, `src/lib/plugins/external.ts`, and `src-tauri/src/features.rs`. +- Evidence: `tests/smoke/features/settings.smoke.mjs` and `tests/smoke/features/git.smoke.mjs`, with screenshots in both themes and at 360 pixels in `output/smoke/features/`. +- Replaces / replaced by: The Git plugin (`runestone.git` 0.1.10). +- Limits: Code that a window loaded stays in memory until the window reloads. The old package stays installed until the user removes it. diff --git a/docs/development.md b/docs/development.md index dd4dab1..ee3c4e4 100644 --- a/docs/development.md +++ b/docs/development.md @@ -62,7 +62,8 @@ Windows is the primary platform. macOS and Linux builds are experimental. | `workspace.rs` | The workspace root of each window, path checks, atomic saves, the file watcher, search | | `plugins.rs` | Plugin package review, installation, enable state, removal, and recovery | | `plugin_sources.rs` | Plugin downloads from Gitea releases | -| `git.rs` | The Git service for the Git plugin. It runs the `git` program. | +| `git.rs` | The Git service of the Git feature. It runs the `git` program. | +| `features.rs` | Reads the old plugin packages of the native features one time, for the switch migration. It changes no plugin file. | | `pty.rs`, `terminal_platform.rs` | Pseudo-terminals for the Terminal plugin | | `browser.rs` | The process of the built-in browser engine | | `backgrounds.rs` | Background image folders for themes and plugins | @@ -87,7 +88,9 @@ A new command needs an entry in `generate_handler!` in `lib.rs`, in the command | `settings/` | The settings store (`store.ts`), and the code that moves the old browser values to the settings file (`migration.ts`) | | `plugins/` | The plugin runtime, the host types (`sdk.ts`, which also exports the SDK types), and Settings → Plug-ins | | `browser/` | The interface of the built-in browser | -| `completion/`, `git/` | Contracts and services that plugins use | +| `features/` | The native features with an off switch: the catalog (`catalog.ts`), the switches (`state.ts`), the first-start migration, the loader, and one folder for each feature (`git/`). See [Native features](#native-features). | +| `completion/` | Contracts and services that plugins use | +| `git/` | The Git service and its types, for the Git feature and the line history in the status bar | | `theme/` | Appearance settings, palettes, and the theme tokens (`tokens.css`) | | `ui/` | Shared menus, pickers, and action icons | | `i18n/` | Interface text in English, French, Japanese, and Simplified Chinese | @@ -131,13 +134,14 @@ On macOS, it is `~/Library/Application Support//`. On Linux, it is ` "appearance": { "theme": "default", "mode": "dark" }, "customThemes": [], "customThemesLegacy": [], - "language": "en" + "language": "en", + "features": { "git": true } } ``` | Rule | Detail | | --- | --- | -| Sections | `general`, `appearance`, `customThemes`, `customThemesLegacy` (the original version 1 themes), and `language`. The host does not interpret their values. The frontend normalizes each section. | +| Sections | `general`, `appearance`, `customThemes`, `customThemesLegacy` (the original version 1 themes), `language`, and `features` (the switches of the native features). The host does not interpret their values. The frontend normalizes each section. | | Size | At most 8 MiB in total. The appearance can hold an image data URL of up to 3,000,000 characters. | | Writes | `settings_write` replaces one section. The host writes a complete temporary file and renames it. Then it sends `settings-changed` to all windows with the section, the revision, and the value. | | Damaged file | The host moves the file to `settings.corrupt-.json` and writes a new file with the defaults. The first window that reads the settings shows a message one time. | @@ -152,7 +156,7 @@ After that, `src/lib/settings/store.ts` reads the sections from memory and tells - Workspace documents stay ordinary local files. Users keep access to them when plugins are disabled. - The core includes Markdown table editing, rendering, and table formulas. - Native file access, file watching, search, Git, and terminals belong in Rust. -- Optional features ship as plugins. The [plugin development reference](plugin-development.md) defines the package format and the API. +- Built-in features with an off switch live in `src/lib/features/`. Other optional features ship as plugins. The [plugin development reference](plugin-development.md) defines the package format and the API. - For sync, prefer a local Git clone. Do not use a live network share as the sync path. These stay outside the product: @@ -177,6 +181,7 @@ Run these commands from the repository folder. They do not need an installer. | `pnpm smoke` | Browser smoke tests. See [Browser smoke tests](#browser-smoke-tests). | | `pnpm build` | The production frontend build | | `pnpm check:menus` | The inventory of menu surfaces. See [Interface design](ui-design.md). | +| `pnpm check:features` | A full build. It fails when a native feature module loads at start. See [Native features](#native-features). | To run one test file, use `node --experimental-strip-types --import ./tests/unit/_svelte/register.mjs --test tests/unit/tables/selection.spec.ts`. The `--import` hook compiles `.svelte.ts` modules, so a test can import them. @@ -199,6 +204,25 @@ All text that a user reads goes through the catalog in `src/lib/i18n/messages.ts Errors of the plugin API stay in English, because they are for plugin developers. `pnpm check` runs `scripts/i18nAudit.mjs`. It fails for a key that the catalog does not have, a catalog key that the code does not use, and a row without all translations. +## Native features + +Git is a native feature: host code with an off switch in **Settings → Features**. It does not use the plugin API. + +| Part | File | +| --- | --- | +| The catalog: ID, old plugin ID, name, views, and commands | `src/lib/features/catalog.ts` | +| The switches: the `features` settings section | `src/lib/features/state.ts` | +| The first start: each switch takes the state of the old plugin package | `src/lib/features/migration.ts` and `src-tauri/src/features.rs` | +| One import at first need in each window | `src/lib/features/loader.ts` | +| Views and commands in the workbench | `src/lib/features/session.ts` and `src/lib/plugins/external.ts` | +| The feature code | `src/lib/features//index.ts` and its components | + +- The catalog holds only static data, so the main bundle stays small. The feature code loads when the user first opens a view, a tab, or a command of the feature. An off feature loads nothing. +- Host code never imports a feature folder statically. `pnpm check:features` builds the app. It fails when a feature module, or a library that only a feature needs, is in a chunk that loads at start. +- Saved tabs and tab transfers keep the ID of the old plugin package as the owner ID, for example `runestone.git`. `builtInPackages` in `external.ts` lists the old package, so it never loads. +- Off stops the feature at once in each window and closes its views. The loaded module stays in memory until the window reloads. +- To add a feature, add its entry to `catalog.ts`, its import to `loader.ts`, its folder to `FEATURE_FOLDERS` in `scripts/featureChunks.mjs`, and its old plugin ID to `LEGACY_PACKAGES` in `src-tauri/src/features.rs`. + ## Plugin SDK The plugin SDK in `packages/plugin-sdk/` is the only source of the public plugin types. @@ -241,7 +265,7 @@ A test states what it needs near its top. The runner skips the test, with the re | Line | Requirement | | --- | --- | | `// @requires plugin:terminal` | The compiled Terminal plugin | -| `// @requires repo:RuneStone_Git/dist` | A file or folder in a sibling plugin checkout | +| `// @requires repo:RuneStone_Local_Autocomplete/src` | A file or folder in a sibling plugin checkout | | `// @requires electron` | The browser engine dependencies. Run `npm ci --prefix browser-runtime`. | | `// @known-issue ` | The test fails because of a known app defect. The run reports it as `known`. If the test passes, the run fails, so that someone removes the line. | diff --git a/docs/guides/git.md b/docs/guides/git.md new file mode 100644 index 0000000..3538456 --- /dev/null +++ b/docs/guides/git.md @@ -0,0 +1,53 @@ +# Git guide + +[RuneStone](../../README.md) · [User guide](../user-guide.md) + +This guide explains how to review changes, stage files, commit, push, and pull with Git in RuneStone. + +Git is part of RuneStone and is on by default. It needs the `git` program on the system path. To turn it off, see [Turn features on or off](../user-guide.md#turn-features-on-or-off). + +## Review and stage changes + +1. Open the root folder of the repository as the workspace. +2. Select **Source control** in the navigation buttons at the top of the side pane. +3. Select a file to open its diff in an editor tab. **Open file** in that tab opens the file in the editor. +4. Select the plus button beside a file to stage it, or the minus button to unstage it. The button beside a group stages or unstages all files in that group. + +Source control shows the current branch and two groups. **Staged changes** go into the next commit. **Changes** holds the files that still need review or staging. +A file shows in both groups when only part of its content is staged. Unstage keeps the content of the working file. + +Source control reads the repository again after each change in the workspace, also in the `.git` folder, and when the window gets focus. **Refresh source control** reads it at once. +A diff tab shows the file as it was when you selected it. Select the file again to update the diff. Git reads the files on disk, so save your edits first. + +## Commit + +1. Stage the files for the commit. +2. Enter a commit message. +3. Select **Commit staged**, or press Ctrl+Enter (⌘+Enter on macOS). + +A commit contains only the staged changes. Git hooks and signing settings apply as usual. Set your author name, email, and signing tools in Git outside RuneStone. +If a hook stops the commit, the error stays visible, and the message stays in the field. + +## Push and pull + +**Push to the upstream branch** and **Pull from the upstream branch** use the upstream branch of the current branch and your current Git sign-in. +Pull accepts only a fast-forward update. It stops when local changes or diverging commits prevent that update. RuneStone never forces a push, and it does not set an upstream branch. + +## Commit graph + +Select **Show Git graph** in Source control, or run **Show Git graph** from the command palette (Ctrl+Shift+P). The graph opens in an editor tab. + +The graph shows the latest 100 commits with their branches, tags, IDs, authors, dates, and messages. Dashed lines continue to parents outside these 100 commits. +Select a commit to see its changed files, then select a file to see its diff. The arrow keys, Home, and End move through the commits. + +## Line history + +While a saved text file is open, the status bar shows the author and the date of the last commit for the line of the cursor. A new or changed line can show no author until you commit it. + +## Limits + +- Parent repositories and linked worktrees with their metadata outside the workspace do not work. Open the repository root. +- RuneStone does not include a Git program. +- Create repositories, switch branches, resolve conflicts, and set remotes with Git outside RuneStone. RuneStone has no discard, reset, or force push. +- A Git operation stops after 30 seconds or 2 MiB of output. If an operation stops, refresh to see its result before you do it again. +- The diff of a new text file shows at most 512 KiB. A binary file shows a notice instead of a diff. diff --git a/docs/menu-surfaces.json b/docs/menu-surfaces.json index 993bf1c..8d61bc3 100644 --- a/docs/menu-surfaces.json +++ b/docs/menu-surfaces.json @@ -6,7 +6,6 @@ "RuneStone_Terminal", "RuneStone_Background_Slideshow", "RuneStone_Local_Autocomplete", - "RuneStone_Git", "RuneStone_PDF_Viewer", "RuneStone_CSV_Viewer" ], @@ -94,6 +93,13 @@ "design": "Shared action menu", "check": "tests/smoke/menus/consistency.smoke.mjs" }, + "RuneStone/src/lib/features/git/GitGraph.svelte": { + "counts": { + "picker": 1 + }, + "design": "Commit history listbox of the native Git feature, not a popup menu", + "check": "tests/smoke/features/git.smoke.mjs" + }, "RuneStone/src/lib/layout/CommandPalette.svelte": { "counts": { "picker": 1, @@ -298,13 +304,6 @@ "design": "Host radio menu; native server select only on older hosts", "check": "tests/smoke/plugins/choiceMenus.smoke.mjs" }, - "RuneStone_Git/src/view.js": { - "counts": { - "picker": 1 - }, - "design": "Commit history listbox, not a popup menu", - "check": "Source inspection: persistent history list retains its own layout" - }, "RuneStone_CSV_Viewer/src/index.js": { "counts": { "action": 1, diff --git a/docs/plugin-development.md b/docs/plugin-development.md index d9f07d2..c3479e5 100644 --- a/docs/plugin-development.md +++ b/docs/plugin-development.md @@ -14,7 +14,6 @@ This reference gives the package contract, the build procedure, and the API for - [Terminal API](#terminal-api) - [Folder grants](#folder-grants) - [Plugin services](#plugin-services) -- [Git API](#git-api) - [Background API](#background-api) ## Install the SDK @@ -265,7 +264,6 @@ Older hosts ignore unknown fields in objects that you pass to the host, such as | `assets.read(path)` | | Read a package file as a `Uint8Array`. | | `ui.showActionMenu(options)` | yes | Open the shared RuneStone action menu. See [Menus](#menus). | | `completion` | yes | Autocomplete fields and providers. See the [completion API](completion.md). | -| `git` | yes | Git operations for the active workspace. See [Git API](#git-api). | | `pty` | yes | Terminal sessions. See [Terminal API](#terminal-api). | | `files` | yes | Folders outside the workspace that the user granted to the plugin. See [Folder grants](#folder-grants). | | `services` | yes | Data that one plugin offers to other plugins. See [Plugin services](#plugin-services). | @@ -388,7 +386,6 @@ Only one enabled plugin can own each key. The host removes contributions before | Key | Purpose | Owner | | --- | --- | --- | | `terminal` | Mounts terminal controls in a host element. Returns update, command, and dispose functions. | Terminal plugin | -| `git` | Supplies line blame for the editor. | Git plugin | | `browser` | The built-in browser. `newTab(url?)` opens a browser tab. `open(url)` returns false when the system browser must open a web link, for example before the engine is installed. | RuneStone | A terminal contribution must stop its controls and native sessions before its cleanup finishes. @@ -442,7 +439,7 @@ The host still accepts the native calls of released plugins. A later host can re | Background Slideshow | `api.backgrounds.chooseFolder`, `list`, `read`, `defaultFolder`, `readImageSettings`, `writeImageSettings` | Read images and per-image settings from a folder outside the workspace | `api.files` with a folder grant | | Background Slideshow | `api.workspace.readOptional(".runestone/pm/workspace.json")` | Read the board names of Project Management | A service of Project Management through `api.services` | -The Git, Project Management, Local Autocomplete, PDF Viewer, and CSV Viewer plugins make no native calls. +The Project Management, Local Autocomplete, PDF Viewer, and CSV Viewer plugins make no native calls. Their test scripts replace `window.__TAURI_INTERNALS__` with a test double. That is test code and does not go into the package. ## Terminal API @@ -509,28 +506,6 @@ Each method call returns a promise. The host copies the arguments and the result When the provider stops, the host removes its services and notifies the subscribers. Calls through an old service object then fail. Call `get` again after a notification. Make the data of a service a documented contract of the provider. Give its name, methods, and result shapes in the documentation of the provider plugin. -## Git API - -`api.git` gives Git operations for the active workspace of the window. The host runs the `git` command, one operation at a time. -The SDK type is `GitApi`. Every method checks for plugin shutdown first. - -| Method | Contract | -| --- | --- | -| `status()` | Returns `{ available, repository, branch, changes }`. Each change has `path`, `originalPath?`, `index`, and `worktree`. | -| `diff(path, staged)` | Returns the diff text of one file. | -| `stage(paths)` / `unstage(paths)` | Change the index for 1 to 10,000 paths. | -| `commit(message)` | Commit the staged changes. The message has 1 to 65,536 bytes. | -| `push()` / `pull()` | Push or pull the current branch. | -| `graph()` | Returns `{ commits }` with at most 100 commits from all refs. | -| `commitDetails(commit)` | Returns `{ id, parents, author, date, message, files }` for a full commit ID. | -| `commitDiff(commit, path)` | Returns the diff of one file in a commit, compared to the first parent. | -| `blame(path, line)` | Returns `{ commit, author, date, summary }` for one line, or `null`. `date` is ISO 8601. | - -Each graph commit is `{ id, parents, refs, summary, author, date }`. Parent IDs can refer to commits outside the 100 returned commits. -Older hosts can have `git` without `push`, `pull`, `graph`, `commitDetails`, or `commitDiff`. Make sure that a method exists before you call it. -Example: the [Git plugin](https://git.knottywyvern.com/kwyvern/RuneStone_Git/src/branch/main/docs/usage.md#commit-graph) draws the graph from these commits. -For its native service and test setup, see the [Git plugin development guide](https://git.knottywyvern.com/kwyvern/RuneStone_Git/src/branch/main/docs/development.md). - ## Background API `api.backgrounds` (`version: 1`) lets a plugin show image frames behind the RuneStone interface. diff --git a/docs/plugin-host.md b/docs/plugin-host.md index 34c988c..be2b646 100644 --- a/docs/plugin-host.md +++ b/docs/plugin-host.md @@ -33,6 +33,8 @@ The browser preview (`pnpm dev`) has no installed plugins unless a smoke test su The built-in browser and the theme editor use the plugin API, but they are not packages. `builtInModules` in `src/lib/plugins/external.ts` lists them. The host starts them in each window, and the plugin menus do not list their tools. A browser window starts only the browser. `builtInPackages` lists the IDs of old packages for features that RuneStone now includes. The host never loads such a package. Settings → Plug-ins shows it as included with RuneStone, so that the user can remove it. +Native features, such as Git, do not use the plugin API. `syncFeatures` in `external.ts` gives each feature that is on a feature session (`src/lib/features/session.ts`) under the ID of its old package, so that its views share the tab model of plugin views. Browser windows start no native feature. See [Native features](development.md#native-features). +`features_legacy` (`src-tauri/src/features.rs`) reads the catalog row and the kept `plugin-data//settings.json` of an old package. It accepts only the IDs of native features and changes no file. ### Scans diff --git a/docs/plugins.md b/docs/plugins.md index d9c1031..b7fbc4d 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -2,9 +2,9 @@ [RuneStone](../README.md) · [User guide](user-guide.md) -This guide explains how to install, enable, update, and remove optional plugins such as Terminal, Git, and PDF Viewer. +This guide explains how to install, enable, update, and remove optional plugins such as Terminal, PDF Viewer, and CSV Viewer. -Manage all plugins in **Settings → Plug-ins**. The built-in browser and table formulas are part of RuneStone and are not plugins. +Manage all plugins in **Settings → Plug-ins**. The built-in browser, table formulas, and Git are part of RuneStone and are not plugins. To turn Git off, see [Turn features on or off](user-guide.md#turn-features-on-or-off). Plugins run with the full access of RuneStone, including your files. There is no permission sandbox, and the author field does not prove who published the plugin. Enable only code that you trust. @@ -76,7 +76,6 @@ RuneStone uses the token for this request only and does not save it. | Plugin | Guide | | --- | --- | | Terminal | [Terminal guide](guides/terminal.md) | -| Git | [Git usage](https://git.knottywyvern.com/kwyvern/RuneStone_Git/src/branch/main/docs/usage.md) | | Project Management | [Project Management guide](https://git.knottywyvern.com/kwyvern/RuneStone_PM/src/branch/main/project-management.md) | | Background Slideshow | [Background Slideshow usage](https://git.knottywyvern.com/kwyvern/RuneStone_BG_Slideshow/src/branch/main/docs/usage.md) | | Local Autocomplete | [Local Autocomplete trial guide](https://git.knottywyvern.com/kwyvern/RuneStone_LocalModel/src/branch/main/docs/trial-guide.md) | @@ -95,6 +94,7 @@ RuneStone uses the token for this request only and does not save it. | The plugin shows **Removal incomplete** | Choose **Retry cleanup** to finish the removal. If the error names changed files, check that path first. | | A Gitea release has no usable package | Check the release tag. Ask the publisher for a release with one attached plugin ZIP. | | An old Browser plugin shows in the list | Uninstall it. The built-in browser keeps your profiles and bookmarks. | +| An old Git plugin shows in the list | Uninstall it. RuneStone includes Git, and the first start after the update kept the plugin state. See [Turn features on or off](user-guide.md#turn-features-on-or-off). | | An old Table Formulas plugin shows in the list | Uninstall it. RuneStone does not run it. Your formulas stay in your files. See [Calculate with table formulas](guides/document-tools.md#calculate-with-table-formulas). | To see the installed files of a plugin, choose **Show files** beside it. **Open plugins folder** opens the folder for all plugins. diff --git a/docs/ui-design.md b/docs/ui-design.md index ea4b72b..20406fd 100644 --- a/docs/ui-design.md +++ b/docs/ui-design.md @@ -151,7 +151,7 @@ Decisions: [UI-002](design-decisions.md#ui-002--share-the-requested-dropdown-des - The left ribbon is always present. It holds the tools (New browser tab, Terminal, Plug-in views, and Commands), then a line, then the plugin view shortcuts. Its menus open at its right. While the side pane is closed, the workspace switcher, Help, and Settings move to the bottom of the ribbon, so they stay reachable. - Tabs keep a minimum width of 120 pixels and scroll. Fades show tabs out of view, and ⌄ lists all tabs. A drag area of 120 pixels sits after the tabs. In a narrow header, the tabs shrink first, and the drag area keeps at least 48 pixels. - Windows and Linux title bars use square caption buttons, 46 pixels wide and full height. Rest the pointer on maximize for Snap Layouts on Windows 11. macOS keeps its native traffic lights, and title bars leave `--rs-titlebar-inset-start` free for them. -- Files, Search, Bookmarks, and installed sidebar views such as Git share the top navigation group. The active navigation button shows which view fills the left pane. +- Files, Search, Bookmarks, Source control (while Git is on), and the sidebar views of installed plugins share the top navigation group. The active navigation button shows which view fills the left pane. - Plugin editor views can use the left ribbon. - The built-in browser opens from its own ribbon action. Project Management opens from Plug-in views. Keep Plug-in views in the ribbon, away from the new-tab button. - Document and plugin tabs share the tab bar. The new-tab button follows the tabs. Tabs keep their order and pin state when a plugin replaces its view. @@ -172,12 +172,14 @@ Decisions: [UI-004](design-decisions.md#ui-004--detached-tab-work-area), [UI-039 - Put related plugin metadata and actions in compact rows. - Controls wrap at narrow widths, and the content area scrolls. Long navigation must leave room for the selected page. - General offers the interface language through the shared action menu. +- **Features** lists each native feature in one card: its name, one line of description, and a switch. The page sits between Appearance and Plug-ins, and the `toggle` icon marks it. A failed load shows its cause under the switch in the error color. +- A feature that is off shows no controls: no navigation button, ribbon button, command, or tab. - The transparency slider covers 0% to 100% and uses the accent and surface tokens of the current theme. - Appearance shows a preview card for each theme. The arrow keys move between the cards and select a theme. The current card has the selection outline and a check mark. - **Edit theme** opens the theme editor as a workbench tab in the window that opened Settings. The editor shows every color role in groups, with a swatch, a hex field, the lowest contrast result, and a reset button. Each change shows at once in that window. Save writes a short schema 3 theme with a base. - Custom theme files use schema 3: one `mode`, an optional built-in `base` theme, the `colors` that differ from the base, and `fonts` stacks for interface, prose, headings, and code. The export writes every color and font. Schema 1 and 2 imports convert to schema 3. A schema 1 import selects the palette of the current appearance. -Decisions: [UI-028](design-decisions.md#ui-028--adjustable-surface-transparency-and-fixed-custom-palettes), [UI-042](design-decisions.md#ui-042--theme-file-format-3-and-terminal-colors), [UI-047](design-decisions.md#ui-047--theme-editor-tab-and-theme-cards). +Decisions: [UI-028](design-decisions.md#ui-028--adjustable-surface-transparency-and-fixed-custom-palettes), [UI-042](design-decisions.md#ui-042--theme-file-format-3-and-terminal-colors), [UI-047](design-decisions.md#ui-047--theme-editor-tab-and-theme-cards), [UI-055](design-decisions.md#ui-055--settings--features-and-native-git). ## Typography and tables diff --git a/docs/user-guide.md b/docs/user-guide.md index eb3af8b..f6f35b3 100644 --- a/docs/user-guide.md +++ b/docs/user-guide.md @@ -14,7 +14,9 @@ This guide explains how to work with files, documents, tabs, settings, and the b | Arrange tabs and windows | [Manage tabs](#manage-tabs) | | Save, or recover from a changed file | [Save your work](#save-your-work) and [Resolve file conflicts](#resolve-file-conflicts) | | Change the language or colors | [Change settings](#change-settings) and [Appearance](guides/themes.md) | -| Add Terminal, Git, or other features | [Install and manage plugins](plugins.md) | +| Review changes and commit with Git | [Git guide](guides/git.md) | +| Turn a built-in feature on or off | [Turn features on or off](#turn-features-on-or-off) | +| Add Terminal or other plugins | [Install and manage plugins](plugins.md) | | Browse websites | [Use the built-in browser](#use-the-built-in-browser) | | Run commands or scripts | [Terminal guide](guides/terminal.md) | @@ -198,9 +200,23 @@ Settings apply at once to all workspaces on this computer and update all open wi | --- | --- | | General | Display language, **File name title**, **Keep line breaks**, **Table formulas**, **Show .runestone folder**, and auto-save | | Appearance | Color theme, transparency, background image, and custom themes. See [Appearance and custom themes](guides/themes.md). | +| Features | Turn Git on or off. See [Turn features on or off](#turn-features-on-or-off). | | Plug-ins | Install, enable, update, and remove plugins. See [Install and manage plugins](plugins.md). | | Browser | Homepage, search engine, profiles, ad blocking, and web data | +### Turn features on or off + +Git is a built-in feature with an off switch. Open **Settings → Features** and use the switch beside the feature. + +- A feature that is on uses no extra memory until you first use it, for example when you open Source control. +- A feature that is off does not load. Its buttons, commands, and tabs do not show. +- A change applies at once in all windows. The code that a window loaded stays in memory until you restart RuneStone. + +After an update, each new built-in feature takes the state of its old plugin package: on when the package was enabled, off when it was disabled. +Without an old package, the feature starts on. Settings → Plug-ins shows an old package as **Included with RuneStone**. You can uninstall it. + +### Display language + **Display language** sets the RuneStone controls to English, Français, 日本語, or 简体中文. It does not translate documents, plugin content, or operating system messages. Some error messages stay in English. Reopen a document to update its editor tooltips after a language change. diff --git a/package.json b/package.json index 5d6bc17..f8bd79a 100644 --- a/package.json +++ b/package.json @@ -12,6 +12,7 @@ "check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json && svelte-check --tsconfig ./tests/tsconfig.json && tsc -p packages/plugin-sdk/tsconfig.json --noEmit && tsc -p fixtures/plugins/tsconfig.json && node scripts/i18nAudit.mjs", "check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch", "check:menus": "node scripts/menuSurfaceAudit.mjs", + "check:features": "node scripts/featureChunks.mjs", "tauri": "tauri", "test": "node --experimental-strip-types --import ./tests/unit/_svelte/register.mjs --test \"tests/unit/**/*.spec.ts\"", "smoke": "node scripts/smoke.mjs", diff --git a/packages/plugin-sdk/src/api.ts b/packages/plugin-sdk/src/api.ts index e74ca9e..cf26126 100644 --- a/packages/plugin-sdk/src/api.ts +++ b/packages/plugin-sdk/src/api.ts @@ -1,7 +1,6 @@ import type { BackgroundApi } from "./backgrounds.ts"; import type { CompletionApi } from "./completion.ts"; import type { Contributions } from "./contributions.ts"; -import type { GitApi } from "./git.ts"; import type { ActionIcon } from "./icons.ts"; import type { ActionMenuItem, ActionMenuOptions } from "./menu.ts"; @@ -95,7 +94,6 @@ export interface PluginApi { services?: ServicesApi; backgrounds?: BackgroundApi; ui?: UiApi; - git?: GitApi; completion?: CompletionApi; readonly id: string; readonly signal: AbortSignal; diff --git a/packages/plugin-sdk/src/contributions.ts b/packages/plugin-sdk/src/contributions.ts index 3c868c3..a1360ba 100644 --- a/packages/plugin-sdk/src/contributions.ts +++ b/packages/plugin-sdk/src/contributions.ts @@ -1,5 +1,4 @@ import type { Dispose } from "./api.ts"; -import type { GitLineInfo } from "./git.ts"; export type TerminalAction = "toggle" | "new" | "window" | "split" | "previous" | "next" | "commands" | "directories"; export interface TerminalProps { @@ -14,7 +13,6 @@ export interface TerminalMount { } /** Host features that `api.contribute(key, value)` registers. Only one enabled plugin can own each key. */ export interface Contributions { - git: { blame(path: string, line: number): Promise }; browser: { /** Opens a browser tab, with `url` when it is given. */ newTab?(url?: string): Promise; diff --git a/packages/plugin-sdk/src/features.ts b/packages/plugin-sdk/src/features.ts index d6a6d97..3c83ecf 100644 --- a/packages/plugin-sdk/src/features.ts +++ b/packages/plugin-sdk/src/features.ts @@ -1,7 +1,6 @@ import type { FilesApi, PluginApi, PtyApi, ServicesApi, SettingsApi, UiApi, WorkspaceApi } from "./api.ts"; import type { BackgroundApi } from "./backgrounds.ts"; import type { CompletionApi } from "./completion.ts"; -import type { GitApi } from "./git.ts"; /** * The optional members of `PluginApi`, by path, and the type that `requireFeature` returns for each path. @@ -12,12 +11,6 @@ export interface PluginFeatures { files: FilesApi; services: ServicesApi; backgrounds: BackgroundApi; - git: GitApi; - "git.push": GitApi["push"]; - "git.pull": GitApi["pull"]; - "git.graph": GitApi["graph"]; - "git.commitDetails": GitApi["commitDetails"]; - "git.commitDiff": GitApi["commitDiff"]; completion: CompletionApi; "completion.transport": NonNullable; "ui.showActionMenu": UiApi["showActionMenu"]; @@ -44,12 +37,6 @@ const descriptions: { [K in PluginFeature]: string } = { files: "the folder grant API", services: "the plugin service API", backgrounds: "the background API", - git: "the Git API", - "git.push": "Git push", - "git.pull": "Git pull", - "git.graph": "the Git commit graph", - "git.commitDetails": "Git commit details", - "git.commitDiff": "Git commit diffs", completion: "the completion API", "completion.transport": "the completion model transport", "ui.showActionMenu": "the shared action menu", diff --git a/packages/plugin-sdk/src/git.ts b/packages/plugin-sdk/src/git.ts deleted file mode 100644 index 0a29c34..0000000 --- a/packages/plugin-sdk/src/git.ts +++ /dev/null @@ -1,64 +0,0 @@ -/** Git types. The host runs the `git` program for the active workspace. */ -export interface GitChange { - path: string; - originalPath?: string; - index: string; - worktree: string; -} - -export interface GitStatus { - available: boolean; - repository: boolean; - branch: string | null; - changes: GitChange[]; -} - -export interface GitLineInfo { - commit: string; - author: string; - /** The author date in ISO 8601 format. */ - date: string; - summary: string; -} - -/** Older hosts can have `git` without `push`, `pull`, `graph`, `commitDetails`, or `commitDiff`. Use `hasFeature` first. */ -export interface GitApi { - status(): Promise; - diff(path: string, staged: boolean): Promise; - stage(paths: string[]): Promise; - unstage(paths: string[]): Promise; - commit(message: string): Promise; - push(): Promise; - pull(): Promise; - graph(): Promise; - commitDetails(commit: string): Promise; - commitDiff(commit: string, path: string): Promise; - blame(path: string, line: number): Promise; -} - -export interface GitGraphCommit { - id: string; - parents: string[]; - refs: string[]; - summary: string; - author: string; - date: string; -} - -export interface GitGraph { - commits: GitGraphCommit[]; -} - -export interface GitCommitFile { - path: string; - originalPath?: string; - status: string; -} -export interface GitCommitDetails { - id: string; - parents: string[]; - author: string; - date: string; - message: string; - files: GitCommitFile[]; -} diff --git a/packages/plugin-sdk/src/index.ts b/packages/plugin-sdk/src/index.ts index 59b7c37..7046e25 100644 --- a/packages/plugin-sdk/src/index.ts +++ b/packages/plugin-sdk/src/index.ts @@ -4,7 +4,6 @@ export type * from "./api.ts"; export type * from "./backgrounds.ts"; export type * from "./completion.ts"; export type * from "./contributions.ts"; -export type * from "./git.ts"; export type * from "./menu.ts"; export type { ActionIcon } from "./icons.ts"; export { API_VERSION, type PluginManifest } from "./manifest.ts"; diff --git a/scripts/featureChunks.mjs b/scripts/featureChunks.mjs new file mode 100644 index 0000000..b659c37 --- /dev/null +++ b/scripts/featureChunks.mjs @@ -0,0 +1,80 @@ +// Check the build output for the native features (src/lib/features/). +// Each feature module must load only through its dynamic import in `src/lib/features/loader.ts`. +// The check fails when a feature folder, or a library that only a feature needs, is in an entry chunk +// or in a chunk that an entry chunk imports statically. It also reports the size of each feature chunk. +// +// Usage: node scripts/featureChunks.mjs (also `pnpm check:features`) +// It runs a full build with Vite, so it takes about a minute. +import { execFileSync } from "node:child_process"; +import { mkdtempSync, readFileSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; + +/** The feature folders. The runtime files directly in `src/lib/features/` stay in the main bundle. */ +export const FEATURE_FOLDERS = ["git"]; +/** Libraries that only features need. */ +export const FEATURE_LIBRARIES = ["@xterm", "pdfjs-dist", "yaml"]; + +const normal = id => id.replaceAll("\\", "/"); + +/** The chunk names that the entry chunks load, directly or through static imports. */ +export function staticClosure(chunks) { + const byName = new Map(chunks.map(chunk => [chunk.fileName, chunk])); + const seen = new Set(); + const queue = chunks.filter(chunk => chunk.isEntry).map(chunk => chunk.fileName); + while (queue.length) { + const name = queue.pop(); + if (seen.has(name)) continue; + seen.add(name); + for (const next of byName.get(name)?.imports ?? []) queue.push(next); + } + return seen; +} + +/** True when a module belongs to a feature folder or to a feature library. */ +export function featureModule(id, folders = FEATURE_FOLDERS, libraries = FEATURE_LIBRARIES) { + const path = normal(id); + return folders.some(folder => path.includes(`/src/lib/features/${folder}/`)) + || libraries.some(library => path.includes(`/node_modules/${library}/`) || path.includes(`/node_modules/.pnpm/${library.replace("/", "+")}`)); +} + +/** + * Check the chunks of one client build. `chunks` has the Rollup fields `fileName`, `isEntry`, `isDynamicEntry`, + * `facadeModuleId`, `imports`, `moduleIds`, and `size`. Returns the problems and the size of each feature chunk. + */ +export function checkChunks(chunks, folders = FEATURE_FOLDERS) { + const problems = []; + const closure = staticClosure(chunks); + for (const chunk of chunks) { + if (!closure.has(chunk.fileName)) continue; + for (const id of chunk.moduleIds ?? []) { + if (featureModule(id, folders)) problems.push(`${chunk.fileName} loads at start and contains ${normal(id).replace(/^.*?\/(src|node_modules)\//, "$1/")}`); + } + } + const sizes = {}; + for (const folder of folders) { + const entry = chunks.find(chunk => chunk.facadeModuleId && normal(chunk.facadeModuleId).endsWith(`/src/lib/features/${folder}/index.ts`)); + if (!entry) { problems.push(`No chunk starts at src/lib/features/${folder}/index.ts.`); continue; } + if (!entry.isDynamicEntry || entry.isEntry) problems.push(`src/lib/features/${folder}/index.ts must be a dynamic entry only.`); + sizes[folder] = entry.size; + } + return { problems, sizes }; +} + +async function main() { + // The client build of SvelteKit runs as a nested Vite build, so the report comes from a plugin in vite.config.js. + const report = path.join(mkdtempSync(path.join(tmpdir(), "runestone-chunks-")), "chunks.json"); + const vite = fileURLToPath(new URL("../node_modules/vite/bin/vite.js", import.meta.url)); + execFileSync(process.execPath, [vite, "build", "--logLevel", "warn"], { stdio: ["ignore", "ignore", "inherit"], env: { ...process.env, RUNESTONE_FEATURE_CHUNKS: report } }); + const chunks = JSON.parse(readFileSync(report, "utf8")); + rmSync(path.dirname(report), { recursive: true, force: true }); + const { problems, sizes } = checkChunks(chunks); + for (const [folder, size] of Object.entries(sizes)) console.log(`${folder}: ${(size / 1024).toFixed(1)} KiB in its own chunk`); + if (problems.length) { + for (const problem of problems) console.error(`FAIL: ${problem}`); + process.exitCode = 1; + } else console.log(`PASS: ${FEATURE_FOLDERS.length} feature module(s) load only at first need.`); +} + +if (process.argv[1] === fileURLToPath(import.meta.url)) await main(); diff --git a/scripts/menuSurfaceAudit.mjs b/scripts/menuSurfaceAudit.mjs index 368ee46..5a4a1c9 100644 --- a/scripts/menuSurfaceAudit.mjs +++ b/scripts/menuSurfaceAudit.mjs @@ -4,7 +4,7 @@ import { fileURLToPath } from 'node:url'; const root = fileURLToPath(new URL('../', import.meta.url)); const pluginRepos = process.env.RUNESTONE_PLUGIN_REPOS || path.resolve(root, '..'); -export const projects = ['RuneStone', 'RuneStone_Project_Management', 'RuneStone_Terminal', 'RuneStone_Background_Slideshow', 'RuneStone_Local_Autocomplete', 'RuneStone_Git', 'RuneStone_PDF_Viewer', 'RuneStone_CSV_Viewer']; +export const projects = ['RuneStone', 'RuneStone_Project_Management', 'RuneStone_Terminal', 'RuneStone_Background_Slideshow', 'RuneStone_Local_Autocomplete', 'RuneStone_PDF_Viewer', 'RuneStone_CSV_Viewer']; const patterns = { action: /\b(?:showActionMenu|actionMenu)\s*\(/g, svelteMenu: / Result<()> { + if ids.len() > LEGACY_PACKAGES.len() { + return Err(Error::new("Too many feature packages.")); + } + match ids.iter().find(|id| !LEGACY_PACKAGES.contains(&id.as_str())) { + Some(id) => Err(Error::new(format!("Unknown feature package: {id}"))), + None => Ok(()), + } +} + +#[tauri::command] +pub async fn features_legacy(app: AppHandle, ids: Vec) -> Result> { + check(&ids)?; + legacy_packages(&app, ids).await +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn only_the_packages_of_native_features_are_read() { + assert!(check(&["runestone.git".into()]).is_ok()); + assert!(check(&[]).is_ok()); + for id in ["runestone.csv-viewer", "../plugin-state", "runestone.git/..", ""] { + assert!(check(&[id.into()]).is_err(), "{id}"); + } + assert!(check(&["runestone.git".into(), "runestone.git".into()]).is_err()); + } +} diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 407384e..6c977b3 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -16,6 +16,7 @@ mod spelling; mod theme; mod backgrounds; mod folders; +mod features; mod window_frame; use pty::PtyState; @@ -51,6 +52,7 @@ pub fn run() { folders::folders_read, folders::folders_read_sidecar, folders::folders_write_sidecar, + features::features_legacy, theme::theme_export, spelling::spelling_menu_install, spelling::spelling_suggestions, diff --git a/src-tauri/src/plugins.rs b/src-tauri/src/plugins.rs index 4a6b129..425a767 100644 --- a/src-tauri/src/plugins.rs +++ b/src-tauri/src/plugins.rs @@ -1466,6 +1466,39 @@ pub async fn plugins_reveal( app.opener().reveal_item_in_dir(path).map_err(Error::from) } } +/// What the feature migration (`features.rs`) reads about an old package. Nothing changes. +#[derive(Serialize, Debug, PartialEq)] +pub struct LegacyPackage { + pub id: String, + pub installed: bool, + pub enabled: bool, + /// The kept plugin settings. Missing, damaged, or linked settings count as none. + pub settings: Option, +} +impl Service { + /// A package that is in removal, or whose removal did not finish, counts as not installed. + fn legacy(&self, id: &str) -> LegacyPackage { + let record = self.catalog.plugins.get(id).filter(|record| record.removal.is_none() && !self.removing.contains_key(id)); + let settings = self.directory("plugin-data").ok().and_then(|parent| { + let dir = parent.join(id); + let path = dir.join("settings.json"); + if !path.exists() || safe_child(&parent, &dir).is_err() { + return None; + } + serde_json::from_slice(&bounded(&path, 1024 * 1024).ok()?).ok() + }); + LegacyPackage { + id: id.to_owned(), + installed: record.is_some(), + enabled: record.is_some_and(|record| record.enabled), + settings, + } + } +} +/// Read the old packages for the feature migration. The caller checks the IDs. +pub async fn legacy_packages(app: &AppHandle, ids: Vec) -> Result> { + PluginState::run(app, move |service| Ok(ids.iter().map(|id| service.legacy(id)).collect())).await +} #[tauri::command] pub async fn plugins_data( app: AppHandle, @@ -1863,6 +1896,31 @@ mod tests { assert!(f.service.inspect("main", f.source.clone()).error.is_none()); } #[test] + fn legacy_packages_report_state_and_kept_settings_without_changes() { + let mut disabled = Fixture::new(); + let missing = disabled.service.legacy("org.test.demo"); + assert_eq!(missing, LegacyPackage { id: "org.test.demo".into(), installed: false, enabled: false, settings: None }); + let id = disabled.install(false); + assert_eq!(disabled.service.legacy(&id), LegacyPackage { id: id.clone(), installed: true, enabled: false, settings: None }); + let mut f = Fixture::new(); + let id = f.install(true); + let data = f.service.directory("plugin-data").unwrap().join(&id); + fs::create_dir(&data).unwrap(); + fs::write(data.join("settings.json"), r#"{"fontSize":15}"#).unwrap(); + let state = fs::read(f.root.join("app/plugin-state.json")).unwrap(); + assert_eq!(f.service.legacy(&id), LegacyPackage { id: id.clone(), installed: true, enabled: true, settings: Some(serde_json::json!({ "fontSize": 15 })) }); + fs::write(data.join("settings.json"), "{damaged").unwrap(); + assert_eq!(f.service.legacy(&id).settings, None); + assert_eq!(fs::read(f.root.join("app/plugin-state.json")).unwrap(), state, "The read must not change the catalog."); + // Settings stay after an uninstall, and the package then counts as not installed. + fs::write(data.join("settings.json"), r#"{"kept":true}"#).unwrap(); + let plan = f.service.prepare("main", &id).unwrap(); + f.service.begin_remove("main", &plan.token).unwrap(); + assert!(!f.service.legacy(&id).installed, "A package in removal is not an installed package."); + f.service.finish_remove(&id).unwrap(); + assert_eq!(f.service.legacy(&id), LegacyPackage { id, installed: false, enabled: false, settings: Some(serde_json::json!({ "kept": true })) }); + } + #[test] fn feature_packages_use_the_standard_install_and_remove_lifecycle() { for id in ["runestone.terminal", "runestone.table-formulas"] { let mut f = Fixture::new(); diff --git a/src-tauri/src/preferences.rs b/src-tauri/src/preferences.rs index 9d83446..a248205 100644 --- a/src-tauri/src/preferences.rs +++ b/src-tauri/src/preferences.rs @@ -20,7 +20,8 @@ use crate::fsutil; pub const FILE_NAME: &str = "settings.json"; pub const SCHEMA: u64 = 1; /// The known sections. `customThemesLegacy` keeps the original version 1 themes from before their conversion. -pub const SECTIONS: [&str; 5] = ["general", "appearance", "customThemes", "customThemesLegacy", "language"]; +/// `features` holds the switches of the native features. +pub const SECTIONS: [&str; 6] = ["general", "appearance", "customThemes", "customThemesLegacy", "language", "features"]; /// The appearance section can hold an image data URL of up to 3,000,000 characters. pub const MAX_FILE_BYTES: usize = 8 * 1024 * 1024; pub const CHANGED_EVENT: &str = "settings-changed"; diff --git a/src/lib/features/catalog.ts b/src/lib/features/catalog.ts new file mode 100644 index 0000000..869a1c6 --- /dev/null +++ b/src/lib/features/catalog.ts @@ -0,0 +1,68 @@ +// The native features of RuneStone. Each feature has an off switch in Settings → Features. +// This file is in the main bundle, so it holds only small static data: names, views, and commands. +// The code of a feature loads with a dynamic import at first need (see `loader.ts`), and never while its switch is off. +import { message, tr } from "../i18n/index.ts"; +import type { PluginView } from "../plugins/sdk.ts"; + +export type FeatureId = "git"; + +/** A view of a feature. The workbench shows it as a tab or in the side pane, as it shows a plugin view. */ +export interface FeatureViewInfo { + id: string; + /** Returns the title in the current language. */ + title: () => string; + placement: "editor" | "sidebar"; + icon?: PluginView["icon"]; + /** Show a navigation button for the view. */ + navigation?: boolean; +} + +/** A command of a feature. The command palette lists it. */ +export interface FeatureCommandInfo { + id: string; + title: () => string; + icon?: PluginView["icon"]; + /** The view that the command opens. */ + view: string; +} + +export interface FeatureEntry { + id: FeatureId; + /** The ID of the old plugin package. Saved tabs and tab transfers keep it as the owner ID. */ + owner: string; + /** Catalog keys for Settings → Features. */ + name: string; + description: string; + /** Extra words for the Settings search. */ + keywords: string; + /** The switch for a user who never installed the old package. */ + defaultOn: boolean; + views: readonly FeatureViewInfo[]; + commands: readonly FeatureCommandInfo[]; +} + +export const FEATURES: readonly FeatureEntry[] = [ + { + id: "git", owner: "runestone.git", name: message("Git"), + description: message("Review changes, stage files, commit, and see the commit graph of the workspace repository."), + keywords: "git source control commit stage diff graph branch push pull blame", + defaultOn: true, + views: [ + { id: "source-control", title: () => tr("Source control"), placement: "sidebar", icon: "git", navigation: true }, + { id: "diff", title: () => tr("Git diff"), placement: "editor", icon: "git" }, + { id: "graph", title: () => tr("Git graph"), placement: "editor", icon: "git" }, + ], + commands: [{ id: "graph", title: () => tr("Show Git graph"), icon: "git", view: "graph" }], + }, +]; + +export function featureEntry(id: FeatureId): FeatureEntry { + const entry = FEATURES.find(item => item.id === id); + if (!entry) throw new Error(`Unknown feature: ${id}`); + return entry; +} + +/** The feature that uses `owner` as its owner ID, if any. */ +export function featureOfOwner(owner: string): FeatureEntry | undefined { + return FEATURES.find(item => item.owner === owner); +} diff --git a/src/lib/features/git/DiffText.svelte b/src/lib/features/git/DiffText.svelte new file mode 100644 index 0000000..7746f5f --- /dev/null +++ b/src/lib/features/git/DiffText.svelte @@ -0,0 +1,20 @@ + + + + +
{#each lines as line, index (index)}{line || " "}{/each}
+ + diff --git a/src/lib/features/git/GitDiff.svelte b/src/lib/features/git/GitDiff.svelte new file mode 100644 index 0000000..2810d3a --- /dev/null +++ b/src/lib/features/git/GitDiff.svelte @@ -0,0 +1,39 @@ + + +
+
+ {title} + +
+ {#if error}{/if} + +
+ + diff --git a/src/lib/features/git/GitGraph.svelte b/src/lib/features/git/GitGraph.svelte new file mode 100644 index 0000000..294dcbf --- /dev/null +++ b/src/lib/features/git/GitGraph.svelte @@ -0,0 +1,244 @@ + + +
+
+ {$t("Commit graph")} + void refresh()} /> +
+

{$t("Latest 100 commits. Select a commit to see its files. Dashed lines continue beyond this history.")}

+
+
+ {#if graphMessage} +

{graphMessage}

+ {:else} +
+ +
    + {#each layout.nodes as commit (commit.id)} + {@const selected = commit.id === git.history.selectedId} +
  1. + +
  2. + {/each} +
+
+ {/if} +
+
+ {#if detail} +
+ {detail.author} + + {detail.id} + {#if detail.parents.length > 1}{$t("Changes against the first parent.")}{/if} +
+

{detail.message}

+ {$t("Changed files: {count}", { count: detail.files.length })} +
+ {#each detail.files as file (file.path)} + + {/each} +
+ {#if diff} + + {:else} +

{detail.files.length ? $t("Select a file to see its diff.") : $t("This commit contains no file changes.")}

+ {/if} + {:else} +

{detailMessage}

+ {/if} +
+
+
+ + diff --git a/src/lib/features/git/SourceControl.svelte b/src/lib/features/git/SourceControl.svelte new file mode 100644 index 0000000..78d31b8 --- /dev/null +++ b/src/lib/features/git/SourceControl.svelte @@ -0,0 +1,201 @@ + + +
+
+ {snapshot?.branch ?? $t("Source control")} + {#if snapshot?.repository} + + + + {/if} + void refresh()} /> +
+ + {#if snapshot?.repository} +
{ event.preventDefault(); commit(); }}> + + + {$t("Only staged files enter the commit. Press {shortcut} to commit.", { shortcut: keys("Mod+Enter") })} +
+
+ {$t("Changes ({count})", { count: snapshot.changes.length })} + {#each [{ staged: true, changes: grouped.staged }, { staged: false, changes: grouped.working }] as group (group.staged)} + {#if group.changes.length} +
+
+

{group.staged ? $t("Staged changes ({count})", { count: group.changes.length }) : $t("Changes ({count})", { count: group.changes.length })}

+ stage(group.changes, group.staged)} /> +
+ {#each group.changes as change (change.path)} +
+ + {changeLabel(change, group.staged)} + stage([change], group.staged)} /> +
+ {/each} +
+ {/if} + {/each} +
+ {/if} +
+ + diff --git a/src/lib/features/git/index.ts b/src/lib/features/git/index.ts new file mode 100644 index 0000000..c706e4d --- /dev/null +++ b/src/lib/features/git/index.ts @@ -0,0 +1,62 @@ +// The Git feature. `loader.ts` imports this module at first need: the Source control pane, a Git tab, or the graph command. +// It uses the host Git service directly. `src-tauri/src/git.rs` runs the `git` program for the workspace of the window. +import { mount, unmount } from "svelte"; +import { tr } from "../../i18n/index.ts"; +import { gitApi } from "../../git/service.ts"; +import type { FeatureContext, FeatureInstance } from "../types.ts"; +import { GitState } from "./state.svelte.ts"; +import SourceControl from "./SourceControl.svelte"; +import GitDiff from "./GitDiff.svelte"; +import GitGraph from "./GitGraph.svelte"; + +export function start(context: FeatureContext): FeatureInstance { + const state = new GitState(); + + async function loadDiff(path: string, staged: boolean) { + const sequence = ++state.sequence; + state.selected = { path, staged, text: tr("Loading diff…"), error: false }; + try { + const text = await gitApi.diff(path, staged); + if (state.disposed || sequence !== state.sequence) return; + state.selected = { path, staged, text: text || tr("No text changes."), error: false }; + } catch (reason) { + if (state.disposed || sequence !== state.sequence) return; + state.selected = { path, staged, text: String(reason), error: true }; + } + } + + const views: Record Record> = { + "source-control": target => mount(SourceControl, { target, props: { + git: state, + showDiff: (path: string, staged: boolean) => { context.openView("diff"); void loadDiff(path, staged); }, + showGraph: () => context.openView("graph"), + onWorkspaceChange: context.onWorkspaceChange, + } }), + diff: target => mount(GitDiff, { target, props: { git: state, openFile: context.openFile } }), + graph: target => mount(GitGraph, { target, props: { git: state } }), + }; + + return { + mount(view, element) { + const create = views[view]; + if (!create) throw new Error(tr("This view is unavailable.")); + const component = create(element); + return () => unmount(component); + }, + saveTabState(view) { + if (view === "diff") return state.selected ? { path: state.selected.path, staged: state.selected.staged } : null; + if (view === "graph") return { selectedId: state.history.selectedId, file: state.history.file }; + return undefined; + }, + async restoreTabState(view, value) { + const saved = value && typeof value === "object" ? value as Record : null; + if (!saved) return; + if (view === "diff" && typeof saved.path === "string" && typeof saved.staged === "boolean") await loadDiff(saved.path, saved.staged); + if (view === "graph") { + state.history.selectedId = typeof saved.selectedId === "string" ? saved.selectedId : null; + state.history.file = typeof saved.file === "string" ? saved.file : null; + } + }, + dispose() { state.disposed = true; state.sequence++; }, + }; +} diff --git a/src/lib/features/git/model.ts b/src/lib/features/git/model.ts new file mode 100644 index 0000000..2fe620f --- /dev/null +++ b/src/lib/features/git/model.ts @@ -0,0 +1,86 @@ +// Pure Git helpers of the Git feature: change groups, labels, and the lanes of the commit graph. +import { tr } from "../../i18n/index.ts"; +import type { GitChange, GitGraph, GitGraphCommit } from "../../git/contracts.ts"; + +export function isConflict(change: GitChange): boolean { + return change.index === "U" || change.worktree === "U" || ["AA", "DD"].includes(change.index + change.worktree); +} + +/** Staged changes and working tree changes. A conflict shows only with the working tree changes. */ +export function groups(changes: GitChange[]): { staged: GitChange[]; working: GitChange[] } { + return { + staged: changes.filter(change => !isConflict(change) && ![" ", "?", "!"].includes(change.index)), + working: changes.filter(change => isConflict(change) || ![" ", "!"].includes(change.worktree)), + }; +} + +/** The paths to stage or unstage. A rename needs both its old and its new path. */ +export function pathsFor(changes: GitChange[]): string[] { + return [...new Set(changes.flatMap(change => change.originalPath ? [change.originalPath, change.path] : [change.path]))]; +} + +export function changeLabel(change: GitChange, staged: boolean): string { + if (isConflict(change)) return tr("Conflict"); + const code = staged ? change.index : change.worktree; + switch (code) { + case "?": return tr("New"); + case "A": return tr("Added"); + case "M": return tr("Modified"); + case "D": return tr("Deleted"); + case "R": return tr("Renamed"); + case "C": return tr("Copied"); + case "T": return tr("Type changed"); + default: return code; + } +} + +export type DiffLineKind = "add" | "remove" | "range" | "context"; + +export function diffLineKind(line: string): DiffLineKind { + if (line.startsWith("+") && !line.startsWith("+++")) return "add"; + if (line.startsWith("-") && !line.startsWith("---")) return "remove"; + return line.startsWith("@@") ? "range" : "context"; +} + +export interface GraphNode extends GitGraphCommit { row: number; lane: number; color: number } +export interface GraphEdge { from: string; to: string; row: number; lane: number; parentLane: number; color: number; outside: boolean; endRow: number } + +/** Lanes and colors for the commit graph. The six colors repeat, and lanes that are in use do not share a color. */ +export function graphLayout(history: GitGraph | null | undefined): { nodes: GraphNode[]; edges: GraphEdge[]; lanes: number } { + const commits = history?.commits ?? []; + const lanes: (string | null)[] = []; + const nodes: GraphNode[] = []; + const edges: Omit[] = []; + const colors = new Map(); + let nextColor = 0; + const ids = new Set(commits.map(commit => commit.id)); + const reserve = (id: string, preferredColor?: number) => { + let lane = lanes.indexOf(id); + if (lane < 0) { + lane = lanes.indexOf(null); + if (lane < 0) lane = lanes.length; + lanes[lane] = id; + if (preferredColor === undefined) { + const activeColors = new Set(lanes.filter(value => value !== id && value !== null).map(value => colors.get(value!))); + preferredColor = nextColor++; + for (let offset = 0; offset < 6 && activeColors.has(preferredColor % 6); offset++) preferredColor = nextColor++; + } + colors.set(id, preferredColor % 6); + } + return lane; + }; + let width = 1; + for (const [row, commit] of commits.entries()) { + const lane = reserve(commit.id); + const color = colors.get(commit.id)!; + nodes.push({ ...commit, row, lane, color }); + lanes[lane] = null; + for (const [index, parent] of commit.parents.entries()) { + const parentLane = reserve(parent, index === 0 ? color : undefined); + edges.push({ from: commit.id, to: parent, row, lane, parentLane, color: index === 0 ? color : colors.get(parent)!, outside: !ids.has(parent) }); + } + width = Math.max(width, lanes.length, lane + 1); + } + const rows = new Map(nodes.map(node => [node.id, node.row])); + return { nodes, edges: edges.map(edge => ({ ...edge, endRow: rows.get(edge.to) ?? nodes.length })), lanes: width }; +} diff --git a/src/lib/features/git/state.svelte.ts b/src/lib/features/git/state.svelte.ts new file mode 100644 index 0000000..52761ec --- /dev/null +++ b/src/lib/features/git/state.svelte.ts @@ -0,0 +1,20 @@ +// The shared state of one Git feature instance. The Source control pane, the diff tab, and the graph tab read it. + +export interface DiffSelection { + path: string; + staged: boolean; + text: string; + error: boolean; +} + +export class GitState { + /** The file of the diff tab. */ + selected = $state(null); + /** The commit and the file of the graph tab. Tab transfers carry them. */ + history = $state<{ selectedId: string | null; file: string | null }>({ selectedId: null, file: null }); + /** Grows after each commit, push, or pull, so that the graph reads the history again. */ + historyVersion = $state(0); + /** The diff request that may write `selected`. */ + sequence = 0; + disposed = false; +} diff --git a/src/lib/features/loader.ts b/src/lib/features/loader.ts new file mode 100644 index 0000000..8627093 --- /dev/null +++ b/src/lib/features/loader.ts @@ -0,0 +1,41 @@ +// Each feature module loads at most one time in each window. The host core never imports a feature module +// statically. `pnpm check:features` makes sure of this in the build output. +import { writable } from "svelte/store"; +import type { FeatureId } from "./catalog.ts"; +import type { FeatureModule } from "./types.ts"; + +const imports: Record Promise> = { + git: () => import("./git/index.ts"), +}; + +const modules = new Map>(); + +/** The last load error of each feature, for Settings → Features. */ +export const featureErrors = writable>>({}); + +function setError(id: FeatureId, message: string | undefined) { + featureErrors.update(errors => { + const next = { ...errors }; + if (message) next[id] = message; else delete next[id]; + return next; + }); +} + +/** Import the module of a feature. After a failure, the next call tries again. */ +export function loadFeature(id: FeatureId, load: () => Promise = imports[id]): Promise { + let pending = modules.get(id); + if (!pending) { + pending = load().then(module => { setError(id, undefined); return module; }, reason => { + modules.delete(id); + setError(id, String(reason)); + throw reason; + }); + modules.set(id, pending); + } + return pending; +} + +/** True after the first load started in this window. Tests use it to prove that an off feature never loads. */ +export function featureRequested(id: FeatureId): boolean { + return modules.has(id); +} diff --git a/src/lib/features/migration.ts b/src/lib/features/migration.ts new file mode 100644 index 0000000..0bc4fc9 --- /dev/null +++ b/src/lib/features/migration.ts @@ -0,0 +1,60 @@ +// The first start of a version with a new native feature. The switch takes the state of the old plugin package. +// `features_legacy` in `src-tauri/src/features.rs` reads the old package state and its kept settings. It changes nothing. +import { invoke, isTauri } from "@tauri-apps/api/core"; +import { readSection, writeSection } from "../settings/store.ts"; +import { FEATURES, type FeatureEntry, type FeatureId } from "./catalog.ts"; +import { storedSwitches } from "./state.ts"; + +/** What the host reports about one old plugin package. */ +export interface LegacyPlugin { + id: string; + installed: boolean; + enabled: boolean; + /** The kept plugin settings, or null. */ + settings: unknown; +} + +/** An installed package gives its enabled state. Without a package, the default of the feature applies. */ +export function legacySwitch(entry: FeatureEntry, legacy: LegacyPlugin | undefined): boolean { + return legacy?.installed ? legacy.enabled : entry.defaultOn; +} + +export interface MigrationHost { + read: () => unknown; + write: (value: unknown) => Promise; + legacy: (ids: string[]) => Promise; +} + +const desktopHost: MigrationHost = { + read: () => readSection("features"), + write: value => writeSection("features", value), + legacy: ids => invoke("features_legacy", { ids }), +}; + +/** + * Give each feature without a stored switch the state of its old package. It runs before the first render. + * When the host cannot report the packages, nothing is written, so the next start tries again. + */ +export async function migrateFeatures(host: MigrationHost = desktopHost): Promise { + const current = host.read(); + const stored = storedSwitches(current); + const missing = FEATURES.filter(entry => stored[entry.id] === undefined); + if (!missing.length) return []; + let legacy: LegacyPlugin[]; + try { legacy = await host.legacy(missing.map(entry => entry.owner)); } + catch (reason) { + console.error("RuneStone could not read the old plugin packages. The feature defaults apply.", reason); + return []; + } + const next: Record = current && typeof current === "object" && !Array.isArray(current) ? { ...current as Record } : {}; + for (const entry of missing) next[entry.id] = legacySwitch(entry, legacy.find(item => item.id === entry.owner)); + await host.write(next); + return missing.map(entry => entry.id); +} + +/** Workbench and Settings windows of the desktop app migrate. Browser windows start no feature, and the browser preview keeps the defaults. */ +export function migrateFeaturesOnStart(): Promise { + const browserWindow = new URLSearchParams(location.search).get("browserWindow") === "true"; + if (!isTauri() || browserWindow) return Promise.resolve(); + return migrateFeatures().catch(reason => console.error("The feature migration failed.", reason)); +} diff --git a/src/lib/features/session.ts b/src/lib/features/session.ts new file mode 100644 index 0000000..f28a29b --- /dev/null +++ b/src/lib/features/session.ts @@ -0,0 +1,81 @@ +// A feature in the workbench of one window. Its views and commands come from the static catalog, so the +// navigation buttons and the command palette show them without the feature code. The first mount, +// restore, or command loads the feature module and starts one instance for this window. +import { tr } from "../i18n/index.ts"; +import type { Dispose, PluginCommand, PluginDocumentType, PluginView } from "../plugins/sdk.ts"; +import type { FeatureEntry } from "./catalog.ts"; +import { loadFeature } from "./loader.ts"; +import type { FeatureContext, FeatureInstance, FeatureModule } from "./types.ts"; + +export class FeatureSession { + readonly controller = new AbortController(); + readonly views = new Map(); + readonly documentTypes = new Map(); + readonly commands = new Map(); + readonly entry: FeatureEntry; + private context: FeatureContext; + private load: () => Promise; + private instance?: Promise; + private ready?: FeatureInstance; + + constructor(entry: FeatureEntry, context: FeatureContext, load: () => Promise = () => loadFeature(entry.id)) { + this.entry = entry; + this.context = context; + this.load = load; + for (const info of entry.views) { + this.views.set(info.id, { + id: info.id, get title() { return info.title(); }, placement: info.placement, icon: info.icon, + navigation: !!info.navigation, launcher: false, + mount: element => this.mountView(info.id, element), + saveTabState: () => this.ready?.saveTabState?.(info.id), + restoreTabState: async state => { await (await this.running()).restoreTabState?.(info.id, state); }, + }); + } + for (const info of entry.commands) { + this.commands.set(info.id, { id: info.id, get title() { return info.title(); }, icon: info.icon, run: () => context.openView(info.view) }); + } + } + + /** The instance of this window. A failed load leaves no instance, so a later call tries again. */ + private running(): Promise { + if (this.controller.signal.aborted) return Promise.reject(new Error(tr("This feature is off."))); + this.instance ??= this.load().then(module => { + if (this.controller.signal.aborted) throw new Error(tr("This feature is off.")); + return this.ready = module.start(this.context); + }).catch(reason => { this.instance = undefined; throw reason; }); + return this.instance; + } + + private async mountView(id: string, element: HTMLElement): Promise { + return (await this.running()).mount(id, element); + } + + async mount(id: string, element: HTMLElement): Promise { + const view = this.views.get(id); + if (!view) throw new Error(tr("This view is unavailable.")); + const dispose = await view.mount(element); + return async () => { + if (typeof dispose === "function") await dispose(); + element.replaceChildren(); + }; + } + + async launch(id: string) { this.context.openView(id); } + + async run(id: string) { + const command = this.commands.get(id); + if (!command) throw new Error(tr("This command is unavailable.")); + await command.run(); + } + + async dropTab(_data: string): Promise { throw new Error(tr("This feature cannot receive this tab.")); } + + /** Stop the instance. The host closes the views of the feature first. */ + async stop() { + this.controller.abort(); + const instance = this.ready ?? await this.instance?.catch(() => undefined); + this.ready = undefined; + this.instance = undefined; + await instance?.dispose(); + } +} diff --git a/src/lib/features/state.ts b/src/lib/features/state.ts new file mode 100644 index 0000000..bf0e5a5 --- /dev/null +++ b/src/lib/features/state.ts @@ -0,0 +1,41 @@ +// The feature switches: the `features` section of the settings file, for example `{ "git": true }`. +// A missing key means that the migration from the old plugin package has not run for that feature yet. +import { readable } from "svelte/store"; +import { onSettingsChange, readSection, writeSection } from "../settings/store.ts"; +import { FEATURES, type FeatureId } from "./catalog.ts"; + +export type FeatureSwitches = Record; + +function record(value: unknown): Record { + return value && typeof value === "object" && !Array.isArray(value) ? value as Record : {}; +} + +/** The stored switches of the known features. Other keys are ignored. */ +export function storedSwitches(value: unknown): Partial { + const stored = record(value); + const result: Partial = {}; + for (const { id } of FEATURES) if (typeof stored[id] === "boolean") result[id] = stored[id]; + return result; +} + +/** The switches with the default of each feature that has no stored value. */ +export function switchesFrom(value: unknown): FeatureSwitches { + const stored = storedSwitches(value); + return Object.fromEntries(FEATURES.map(entry => [entry.id, stored[entry.id] ?? entry.defaultOn])) as FeatureSwitches; +} + +export function readSwitches(): FeatureSwitches { + return switchesFrom(readSection("features")); +} + +/** The switches in this window. Changes from other windows arrive through `settings-changed`. */ +export const featureSwitches = readable(readSwitches(), set => { + // The settings can load after this module, so read them again for the first subscriber. + set(readSwitches()); + return onSettingsChange("features", () => set(readSwitches())); +}); + +/** Turn one feature on or off. Keys of unknown features stay, so a newer version keeps its values. */ +export function setFeature(id: FeatureId, on: boolean): Promise { + return writeSection("features", { ...record(readSection("features")), [id]: on }); +} diff --git a/src/lib/features/types.ts b/src/lib/features/types.ts new file mode 100644 index 0000000..42a3d8b --- /dev/null +++ b/src/lib/features/types.ts @@ -0,0 +1,26 @@ +import type { Dispose } from "../plugins/sdk.ts"; + +/** The host services that a running feature gets. A feature also uses other host modules directly. */ +export interface FeatureContext { + /** Open a view of this feature, as a tab or in the side pane. */ + openView(id: string): void; + /** Open a workspace file in the editor. */ + openFile(path: string): Promise; + /** Run `listener` after each change in the workspace. Returns the function that stops it. */ + onWorkspaceChange(listener: () => void): () => void; +} + +/** One running copy of a feature in one window. */ +export interface FeatureInstance { + mount(view: string, element: HTMLElement): Dispose | Promise; + /** The state of a tab for a transfer to another window. */ + saveTabState?(view: string): unknown; + restoreTabState?(view: string, state: unknown): void | Promise; + /** Stop all work. The host unmounts the views first. */ + dispose(): void | Promise; +} + +/** The module that `loader.ts` imports at first need. */ +export interface FeatureModule { + start(context: FeatureContext): FeatureInstance; +} diff --git a/src/lib/git/contracts.ts b/src/lib/git/contracts.ts index fe9419c..a031f17 100644 --- a/src/lib/git/contracts.ts +++ b/src/lib/git/contracts.ts @@ -1,2 +1,64 @@ -// The Git types are part of the public plugin SDK (packages/plugin-sdk/src/git.ts). -export type { GitApi, GitChange, GitCommitDetails, GitCommitFile, GitGraph, GitGraphCommit, GitLineInfo, GitStatus } from "../plugins/sdk.ts"; +// The Git types of the host. `src-tauri/src/git.rs` runs the `git` program for the workspace of the window. +// The Git feature (`src/lib/features/git/`) and the blame line of the editor use them. +export interface GitChange { + path: string; + originalPath?: string; + index: string; + worktree: string; +} + +export interface GitStatus { + available: boolean; + repository: boolean; + branch: string | null; + changes: GitChange[]; +} + +export interface GitLineInfo { + commit: string; + author: string; + /** The author date in ISO 8601 format. */ + date: string; + summary: string; +} + +export interface GitApi { + status(): Promise; + diff(path: string, staged: boolean): Promise; + stage(paths: string[]): Promise; + unstage(paths: string[]): Promise; + commit(message: string): Promise; + push(): Promise; + pull(): Promise; + graph(): Promise; + commitDetails(commit: string): Promise; + commitDiff(commit: string, path: string): Promise; + blame(path: string, line: number): Promise; +} + +export interface GitGraphCommit { + id: string; + parents: string[]; + refs: string[]; + summary: string; + author: string; + date: string; +} + +export interface GitGraph { + commits: GitGraphCommit[]; +} + +export interface GitCommitFile { + path: string; + originalPath?: string; + status: string; +} +export interface GitCommitDetails { + id: string; + parents: string[]; + author: string; + date: string; + message: string; + files: GitCommitFile[]; +} diff --git a/src/lib/i18n/messages.ts b/src/lib/i18n/messages.ts index de04c5f..2d9ab4d 100644 --- a/src/lib/i18n/messages.ts +++ b/src/lib/i18n/messages.ts @@ -3443,6 +3443,78 @@ export const messageRows: [string, string, string, string][] = [ ["Install the browser engine to see the browser bookmarks.", "Installez le moteur du navigateur pour voir les signets du navigateur.", "ブラウザーのブックマークを表示するには、ブラウザーエンジンをインストールしてください。", "安装浏览器引擎后即可查看浏览器书签。"], ["The other browser settings show after the engine is installed.", "Les autres paramètres du navigateur s’affichent une fois le moteur installé.", "その他のブラウザー設定は、エンジンのインストール後に表示されます。", "安装引擎后将显示其他浏览器设置。"], ["Engine", "Moteur", "エンジン", "引擎"], + ["Features", "Fonctionnalités", "機能", "功能"], + ["Turn off the features that you do not use. A feature that is off does not load, and its controls do not show.", "Désactivez les fonctionnalités que vous n’utilisez pas. Une fonctionnalité désactivée ne se charge pas et ses commandes ne s’affichent pas.", "使わない機能はオフにします。オフの機能は読み込まれず、そのコントロールも表示されません。", "关闭不使用的功能。已关闭的功能不会加载,其控件也不会显示。"], + ["{name} could not load: {error}", "Impossible de charger {name} : {error}", "{name} を読み込めませんでした: {error}", "无法加载 {name}:{error}"], + ["This feature is off.", "Cette fonctionnalité est désactivée.", "この機能はオフです。", "此功能已关闭。"], + ["This view is unavailable.", "Cette vue n’est pas disponible.", "このビューは使用できません。", "此视图不可用。"], + ["This command is unavailable.", "Cette commande n’est pas disponible.", "このコマンドは使用できません。", "此命令不可用。"], + ["This feature cannot receive this tab.", "Cette fonctionnalité ne peut pas recevoir cet onglet.", "この機能はこのタブを受け取れません。", "此功能无法接收此标签页。"], + ["Git", "Git", "Git", "Git"], + ["Review changes, stage files, commit, and see the commit graph of the workspace repository.", "Examinez les modifications, indexez des fichiers, validez et consultez le graphe des commits du dépôt de l’espace de travail.", "ワークスペースのリポジトリで変更の確認、ファイルのステージ、コミット、コミットグラフの表示を行います。", "查看更改、暂存文件、提交,并查看工作区仓库的提交图。"], + ["Source control", "Contrôle de code source", "ソース管理", "源代码管理"], + ["Git source control", "Contrôle de code source Git", "Git ソース管理", "Git 源代码管理"], + ["Git diff", "Diff Git", "Git の差分", "Git 差异"], + ["Git graph", "Graphe Git", "Git グラフ", "Git 图"], + ["Git history", "Historique Git", "Git の履歴", "Git 历史"], + ["Show Git graph", "Afficher le graphe Git", "Git グラフを表示", "显示 Git 图"], + ["Refresh source control", "Actualiser le contrôle de code source", "ソース管理を更新", "刷新源代码管理"], + ["Pull from the upstream branch", "Récupérer depuis la branche amont", "上流ブランチからプル", "从上游分支拉取"], + ["Push to the upstream branch", "Envoyer vers la branche amont", "上流ブランチにプッシュ", "推送到上游分支"], + ["Pull in progress…", "Récupération en cours…", "プル中…", "正在拉取…"], + ["Pull complete. The branch is up to date.", "Récupération terminée. La branche est à jour.", "プルが完了しました。ブランチは最新です。", "拉取完成。分支已是最新。"], + ["Push in progress…", "Envoi en cours…", "プッシュ中…", "正在推送…"], + ["Push complete.", "Envoi terminé.", "プッシュが完了しました。", "推送完成。"], + ["Loading repository…", "Chargement du dépôt…", "リポジトリを読み込み中…", "正在加载仓库…"], + ["Commit message", "Message de commit", "コミットメッセージ", "提交信息"], + ["Commit staged", "Valider les modifications indexées", "ステージ済みをコミット", "提交已暂存的更改"], + ["Only staged files enter the commit. Press {shortcut} to commit.", "Seuls les fichiers indexés entrent dans le commit. Appuyez sur {shortcut} pour valider.", "コミットに含まれるのはステージ済みのファイルだけです。{shortcut} でコミットします。", "只有已暂存的文件会进入提交。按 {shortcut} 提交。"], + ["Commit created.", "Commit créé.", "コミットを作成しました。", "已创建提交。"], + ["Changes ({count})", "Modifications ({count})", "変更 ({count})", "更改 ({count})"], + ["Staged changes ({count})", "Modifications indexées ({count})", "ステージ済みの変更 ({count})", "已暂存的更改 ({count})"], + ["Stage all", "Tout indexer", "すべてステージ", "全部暂存"], + ["Unstage all", "Tout désindexer", "すべてステージ解除", "全部取消暂存"], + ["Stage {path}", "Indexer {path}", "{path} をステージ", "暂存 {path}"], + ["Unstage {path}", "Désindexer {path}", "{path} のステージを解除", "取消暂存 {path}"], + ["{path} — {status}", "{path} — {status}", "{path} — {status}", "{path} — {status}"], + ["{path} — {status}, from {original}", "{path} — {status}, depuis {original}", "{path} — {status}(元: {original})", "{path} — {status},来自 {original}"], + ["Conflict", "Conflit", "競合", "冲突"], + ["New", "Nouveau", "新規", "新文件"], + ["Added", "Ajouté", "追加", "已添加"], + ["Modified", "Modifié", "変更", "已修改"], + ["Deleted", "Supprimé", "削除", "已删除"], + ["Renamed", "Renommé", "名前変更", "已重命名"], + ["Type changed", "Type modifié", "種類の変更", "类型已更改"], + ["Git is not installed. Install Git, then restart RuneStone.", "Git n’est pas installé. Installez Git, puis redémarrez RuneStone.", "Git がインストールされていません。Git をインストールしてから RuneStone を再起動してください。", "未安装 Git。请安装 Git,然后重新启动 RuneStone。"], + ["Open a Git repository root as your workspace. Create repositories with Git outside RuneStone.", "Ouvrez la racine d’un dépôt Git comme espace de travail. Créez les dépôts avec Git en dehors de RuneStone.", "Git リポジトリのルートをワークスペースとして開いてください。リポジトリは RuneStone の外で Git を使って作成します。", "请将 Git 仓库的根目录作为工作区打开。请在 RuneStone 之外使用 Git 创建仓库。"], + ["Resolve the conflicts, then stage the files before you commit.", "Résolvez les conflits, puis indexez les fichiers avant de valider.", "競合を解決してから、コミットの前にファイルをステージしてください。", "请解决冲突,然后在提交前暂存文件。"], + ["No changes. Your working tree is clean.", "Aucune modification. Votre arbre de travail est propre.", "変更はありません。作業ツリーはクリーンです。", "没有更改。工作树是干净的。"], + ["Open file", "Ouvrir le fichier", "ファイルを開く", "打开文件"], + ["{path} · Staged", "{path} · Indexé", "{path} · ステージ済み", "{path} · 已暂存"], + ["{path} · Working tree", "{path} · Arbre de travail", "{path} · 作業ツリー", "{path} · 工作树"], + ["Select a file in Source control to see its diff.", "Sélectionnez un fichier dans Contrôle de code source pour voir son diff.", "差分を表示するには、ソース管理でファイルを選択してください。", "在源代码管理中选择一个文件以查看其差异。"], + ["Loading diff…", "Chargement du diff…", "差分を読み込み中…", "正在加载差异…"], + ["No text changes.", "Aucune modification de texte.", "テキストの変更はありません。", "没有文本更改。"], + ["Commit graph", "Graphe des commits", "コミットグラフ", "提交图"], + ["Refresh commit graph", "Actualiser le graphe des commits", "コミットグラフを更新", "刷新提交图"], + ["Latest 100 commits. Select a commit to see its files. Dashed lines continue beyond this history.", "Les 100 derniers commits. Sélectionnez un commit pour voir ses fichiers. Les lignes en pointillés continuent au-delà de cet historique.", "最新の 100 件のコミットです。コミットを選択するとファイルを表示します。破線はこの履歴の外に続きます。", "最近 100 个提交。选择一个提交以查看其文件。虚线表示延续到此历史之外。"], + ["Loading history…", "Chargement de l’historique…", "履歴を読み込み中…", "正在加载历史…"], + ["Commit graph with branches, authors, and dates", "Graphe des commits avec branches, auteurs et dates", "ブランチ、作成者、日付を含むコミットグラフ", "包含分支、作者和日期的提交图"], + ["Commit details", "Détails du commit", "コミットの詳細", "提交详情"], + ["Commits", "Commits", "コミット", "提交"], + ["Select a commit.", "Sélectionnez un commit.", "コミットを選択してください。", "请选择一个提交。"], + ["Loading commit…", "Chargement du commit…", "コミットを読み込み中…", "正在加载提交…"], + ["Changes against the first parent.", "Modifications par rapport au premier parent.", "最初の親コミットとの差分です。", "与第一个父提交的差异。"], + ["Changed files: {count}", "Fichiers modifiés : {count}", "変更されたファイル: {count}", "已更改的文件:{count}"], + ["Changed files", "Fichiers modifiés", "変更されたファイル", "已更改的文件"], + ["Select a file to see its diff.", "Sélectionnez un fichier pour voir son diff.", "差分を表示するファイルを選択してください。", "选择一个文件以查看其差异。"], + ["This commit contains no file changes.", "Ce commit ne contient aucune modification de fichier.", "このコミットにはファイルの変更がありません。", "此提交不包含文件更改。"], + ["Commit file diff", "Diff du fichier du commit", "コミットのファイル差分", "提交的文件差异"], + ["No commit is selected.", "Aucun commit n’est sélectionné.", "コミットが選択されていません。", "未选择提交。"], + ["Select Refresh to try again.", "Sélectionnez Actualiser pour réessayer.", "もう一度試すには[更新]を選択してください。", "选择“刷新”以重试。"], + ["No commits yet. Create a commit to start the graph.", "Aucun commit pour l’instant. Créez un commit pour commencer le graphe.", "まだコミットがありません。コミットを作成するとグラフが始まります。", "还没有提交。创建一个提交以开始图表。"], + ["Parents: {parents}", "Parents : {parents}", "親: {parents}", "父提交:{parents}"], + ["Root commit", "Commit racine", "ルートコミット", "根提交"], ]; export const catalogs: Record, Record> = { fr: Object.fromEntries(messageRows.map(row => [row[0], row[1]])), diff --git a/src/lib/layout/EditorPane.svelte b/src/lib/layout/EditorPane.svelte index 07c3a08..279e9a5 100644 --- a/src/lib/layout/EditorPane.svelte +++ b/src/lib/layout/EditorPane.svelte @@ -1,7 +1,8 @@