Compare commits
10
Commits
4e5c3cb165
...
d849c3c1b5
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d849c3c1b5 | ||
|
|
c68a1afb6d | ||
|
|
956ead818b | ||
|
|
e66f089176 | ||
|
|
e6deecc092 | ||
|
|
833f793244 | ||
|
|
53b9cea7f0 | ||
|
|
ab868bbe8e | ||
|
|
115c32fa92 | ||
|
|
8c43f598fb |
@@ -2,8 +2,8 @@
|
|||||||
|
|
||||||
RuneStone is a desktop workspace for Markdown notes, code, and project work in ordinary local files.
|
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/`).
|
A Tauri 2 host in Rust (`src-tauri/`) serves a Svelte 5 and TypeScript interface (`src/`).
|
||||||
Git is a native feature with an off switch in Settings → Features (`src/lib/features/`). It does not use the plugin API.
|
Git, Background, Terminal, PDF Viewer, and Project Management are native features with an off switch in Settings → Features (`src/lib/features/`). They do not use the plugin API.
|
||||||
Other optional features are plugins. Each plugin is a separate repository beside this one, for example `../RuneStone_Terminal`.
|
Other optional features are plugins. Each plugin is a separate repository beside this one, for example `../RuneStone_CSV_Viewer`.
|
||||||
The [development guide](docs/development.md#architecture) maps the source folders.
|
The [development guide](docs/development.md#architecture) maps the source folders.
|
||||||
|
|
||||||
## Skills
|
## Skills
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@@ -352,6 +352,7 @@ Keyboard focus now scrolls only the menu panel. It cannot dismiss a menu by scro
|
|||||||
- Evidence: All 11 slideshow unit tests, TypeScript checks, and the settings browser check pass.
|
- Evidence: All 11 slideshow unit tests, TypeScript checks, and the settings browser check pass.
|
||||||
- Limits: Native desktop appearance requires user review.
|
- Limits: Native desktop appearance requires user review.
|
||||||
- Replaces: The 800-millisecond fade rule in the interface guide.
|
- Replaces: The 800-millisecond fade rule in the interface guide.
|
||||||
|
- Update 2026-10-29: The rule stays. The native Background feature implements it ([UI-057](#ui-057--background-replaces-background-image-and-background-slideshow)).
|
||||||
|
|
||||||
### UI-016 — Translucent code blocks
|
### UI-016 — Translucent code blocks
|
||||||
|
|
||||||
@@ -442,6 +443,7 @@ Evidence: RuneStone_Git/.audit/git-tooltip-evidence.json and git-tooltip-*.png.
|
|||||||
- Shared implementation: The image sidecar API, optional blurredUrl frames, and separate foreground and cover layers.
|
- Shared implementation: The image sidecar API, optional blurredUrl frames, and separate foreground and cover layers.
|
||||||
- Evidence: Host frame and sidecar checks cover layout, cleanup, size limits, and external changes. Plugin checks accompany the card review.
|
- Evidence: Host frame and sidecar checks cover layout, cleanup, size limits, and external changes. Plugin checks accompany the card review.
|
||||||
- Limits: Native desktop appearance requires user review.
|
- Limits: Native desktop appearance requires user review.
|
||||||
|
- Update 2026-10-29: The rule stays. The native Background feature implements it ([UI-057](#ui-057--background-replaces-background-image-and-background-slideshow)).
|
||||||
|
|
||||||
### UI-021 — Workspace links in document panes
|
### UI-021 — Workspace links in document panes
|
||||||
|
|
||||||
@@ -589,6 +591,7 @@ The overlay retains the source hue. Selected glyph backgrounds stay transparent,
|
|||||||
Evidence: RuneStone_Terminal/.audit/terminal-selection-evidence.json records source colors, alpha, composites, and contrast.
|
Evidence: RuneStone_Terminal/.audit/terminal-selection-evidence.json records source colors, alpha, composites, and contrast.
|
||||||
Screenshots cover both themes at 620 and 1440 pixels. Measured text contrast is 8.94:1 in dark and 11.80:1 in light.
|
Screenshots cover both themes at 620 and 1440 pixels. Measured text contrast is 8.94:1 in dark and 11.80:1 in light.
|
||||||
Native shell, background image, and desktop acceptance remain open.
|
Native shell, background image, and desktop acceptance remain open.
|
||||||
|
Update 2026-10-29: The native Terminal feature keeps the 65% cap on `--rs-selection` ([UI-058](#ui-058--settings--terminal-and-theme-colors-in-the-terminal)).
|
||||||
|
|
||||||
### UI-030 — Settings installation checkbox theme drift
|
### UI-030 — Settings installation checkbox theme drift
|
||||||
|
|
||||||
@@ -811,6 +814,7 @@ Native shell, background image, and desktop acceptance remain open.
|
|||||||
- Evidence: The applied colors and the Source colors of each tag group are the same as before stage 5a-1, for every built-in theme and a saved schema 2 custom theme. `tests/unit/theme/customThemes.spec.ts` covers schema 3, `base`, and the conversion of old syntax names.
|
- Evidence: The applied colors and the Source colors of each tag group are the same as before stage 5a-1, for every built-in theme and a saved schema 2 custom theme. `tests/unit/theme/customThemes.spec.ts` covers schema 3, `base`, and the conversion of old syntax names.
|
||||||
- Replaces / replaced by: The template format of [UI-028](#ui-028--adjustable-surface-transparency-and-fixed-custom-palettes). Its transparency rule remains.
|
- Replaces / replaced by: The template format of [UI-028](#ui-028--adjustable-surface-transparency-and-fixed-custom-palettes). Its transparency rule remains.
|
||||||
- Limits: Browser checks use desktop service mocks. Native desktop acceptance remains open.
|
- Limits: Browser checks use desktop service mocks. Native desktop acceptance remains open.
|
||||||
|
- Update 2026-10-29: The native Terminal feature uses the terminal roles ([UI-058](#ui-058--settings--terminal-and-theme-colors-in-the-terminal)).
|
||||||
|
|
||||||
### UI-043 — Opaque menus
|
### UI-043 — Opaque menus
|
||||||
|
|
||||||
@@ -923,7 +927,7 @@ Native shell, background image, and desktop acceptance remain open.
|
|||||||
|
|
||||||
- Type: Rule change
|
- Type: Rule change
|
||||||
- Date: 2026-10-28
|
- Date: 2026-10-28
|
||||||
- Status: Implemented for user review
|
- Status: Implemented for user review. The names beside the icons are superseded by [UI-056](#ui-056--icon-only-view-control).
|
||||||
- Decision source: Owner decisions 4 and 5 of 2026-10-27 (interface review issues 5 and 7), stage 5-3.
|
- Decision source: Owner decisions 4 and 5 of 2026-10-27 (interface review issues 5 and 7), stage 5-3.
|
||||||
- Previous rule: Two icon-only switchers, "Document view" (Edit, Read, Split) and "Editor layout" (Writer, IDE), showed only the current choice until hover. Hover widened them, so the target moved. The same views had other names in the tab menu ("Reading view", "Source mode") and in the status bar ("IDE"). The file name showed in the tab, in the breadcrumb as a full path, as a title, and in the status bar.
|
- Previous rule: Two icon-only switchers, "Document view" (Edit, Read, Split) and "Editor layout" (Writer, IDE), showed only the current choice until hover. Hover widened them, so the target moved. The same views had other names in the tab menu ("Reading view", "Source mode") and in the status bar ("IDE"). The file name showed in the tab, in the breadcrumb as a full path, as a title, and in the status bar.
|
||||||
- New rule: One radio group shows Write, Source, and Read at all times, with an icon and a name. Narrow panes show only the icons. The arrow keys move the choice, and the group has one Tab stop. The current choice gets the selection fill and an accent bar. Hover gets only a fill. A separate **Split** toggle shows Read beside Write or Source. Write and Source keep Split, and Read ends it. Ctrl+E switches between Write and Source, and Ctrl+Shift+E switches between Read and the editor. The tab menu, the status bar, the docs, and the code use the same names. "IDE" is not a view name.
|
- New rule: One radio group shows Write, Source, and Read at all times, with an icon and a name. Narrow panes show only the icons. The arrow keys move the choice, and the group has one Tab stop. The current choice gets the selection fill and an accent bar. Hover gets only a fill. A separate **Split** toggle shows Read beside Write or Source. Write and Source keep Split, and Read ends it. Ctrl+E switches between Write and Source, and Ctrl+Shift+E switches between Read and the editor. The tab menu, the status bar, the docs, and the code use the same names. "IDE" is not a view name.
|
||||||
@@ -1027,3 +1031,78 @@ Native shell, background image, and desktop acceptance remain open.
|
|||||||
- 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/`.
|
- 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).
|
- 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.
|
- Limits: Code that a window loaded stays in memory until the window reloads. The old package stays installed until the user removes it.
|
||||||
|
|
||||||
|
### UI-056 — Icon-only view control
|
||||||
|
|
||||||
|
- Type: Rule change
|
||||||
|
- Date: 2026-10-29
|
||||||
|
- Status: Implemented for user review
|
||||||
|
- Decision source: The owner's review of 0.1.50 (2026-10-29): the buttons at the top right of the editor went "from icon only to icon + text".
|
||||||
|
- Previous rule: [UI-049](#ui-049--one-view-control-and-one-file-name). Write, Source, and Read, and the Split toggle, showed an icon and a name. Panes narrower than 560 pixels showed only the icons.
|
||||||
|
- New rule: Write, Source, Read, and Split show icons only, at every width. All choices stay visible, so the targets do not move. Each control keeps its accessible name and a tooltip with the name and the shortcut. The current choice keeps the selection fill and the accent bar.
|
||||||
|
- Reason: The editor header is a compact toolbar of familiar actions, and the other header tools are icon only.
|
||||||
|
- Scope: The view control and the Split toggle of each document pane.
|
||||||
|
- Shared implementation: `src/lib/layout/ViewModes.svelte`.
|
||||||
|
- Evidence: `tests/smoke/layout/viewModes.smoke.mjs`.
|
||||||
|
- Replaces / replaced by: The names of UI-049.
|
||||||
|
- Limits: None.
|
||||||
|
|
||||||
|
### UI-057 — Background replaces Background image and Background Slideshow
|
||||||
|
|
||||||
|
- Type: Rule change
|
||||||
|
- Date: 2026-10-29
|
||||||
|
- Status: Implemented for user review
|
||||||
|
- Decision source: The owner decisions of Phase 7, stage 7-2 (2026-10-29): Background is on for every user, also after an update, and decisions 4A, 5C, 6A, and 11A.
|
||||||
|
- Previous rule: Appearance → **Background image** kept one image for new tabs, and `appearance.ts` drew it. The Background Slideshow plugin (`runestone.bg-slideshow` 0.0.11) showed a folder through `api.backgrounds` and its deprecated folder methods, with its settings in its own settings view.
|
||||||
|
- New rule: Background is a native feature with a switch in Settings → Features. Appearance → **Background** has **Background source** (Folder, Image, or None), the folder and its timing and order, the one image, the layout, the per-image editor, and the targets. With Background off, the section shows one line that names Settings → Features, no image shows, and menus are opaque. With no folder and no image, the feature does not load. **Next background image** and **Pause background** are in the command palette. A blank browser tab, also in a browser window, shows the background.
|
||||||
|
- Reason: The owner chose response time and memory over the plugin API. One section replaces two places for the same background.
|
||||||
|
- Scope: Appearance → Background, the workarea background, browser windows, Project Management board frames, and the command palette.
|
||||||
|
- Shared implementation: `src/lib/features/background/`, `src/lib/features/backgroundSettings.ts`, `src/lib/features/launch.ts`, `src/lib/plugins/backgrounds.ts`, `src/lib/theme/background.css`, and `src-tauri/src/backgrounds.rs`.
|
||||||
|
- Evidence: `tests/smoke/features/background.smoke.mjs` and the updated `tests/smoke/appearance/background*.smoke.mjs`, with screenshots in both themes and at 360 pixels in `output/smoke/features/background/`.
|
||||||
|
- Replaces / replaced by: The Background image section of Appearance and the Background Slideshow plugin. The rules of [UI-015](#ui-015--slower-slideshow-fades) and [UI-020](#ui-020--per-image-slideshow-layout) stay.
|
||||||
|
- Limits: Each window has its own timer, so windows can show different images. The settings window runs no slideshow. The old package stays installed until the user removes it.
|
||||||
|
|
||||||
|
### UI-058 — Settings → Terminal and theme colors in the terminal
|
||||||
|
|
||||||
|
- Type: Rule change
|
||||||
|
- Date: 2026-10-29
|
||||||
|
- Status: Implemented for user review
|
||||||
|
- Decision source: The owner decisions of Phase 7, stage 7-3 (2026-10-29), and decision 5C. The card "Use the host terminal colors".
|
||||||
|
- Previous rule: The Terminal plugin (`runestone.terminal` 0.1.11) kept its settings in a modal dialog with **Save settings** and **Cancel**. It saved them in the `runestone.terminal` key of `localStorage`. Its ANSI colors came from the status and accent tokens. Thus blue was the accent color, and most bright colors were the same as the normal colors.
|
||||||
|
- New rule: Terminal is a native feature with a switch in Settings → Features. **Settings → Terminal** shows only while Terminal is on. It has **Default profile** (a shared action menu without the JavaScript Debug Terminal), **Font size**, **Scrollback lines**, and **Blink cursor**. Each change saves at once to the `terminal` section of `settings.json`. Open terminals take the font, the scrollback, and the cursor. **Terminal settings** in the profile menu opens Settings. The 16 ANSI colors come from the `--rs-ansi-*` tokens. Text is `--rs-text`, the cursor is `--rs-accent` on `--rs-bg`, and the selection is `--rs-selection` with at most 65% alpha. Off asks first when a window runs a shell, with the words of the close guard.
|
||||||
|
- Reason: The owner chose response time and memory over the plugin API. Settings apply at once on one Settings page, as the [Settings](ui-design.md#settings) rules require. Terminal colors keep their ANSI meaning in every theme.
|
||||||
|
- Scope: Settings → Terminal, Settings → Features, the terminal panel, terminal windows, and Help.
|
||||||
|
- Shared implementation: `src/lib/features/terminal/` (`theme.ts` for the colors), `src/lib/features/TerminalSettings.svelte`, `src/lib/features/terminalSettings.ts`, `src/lib/features/terminalKeys.ts`, `src/lib/theme/roles.ts`, and `src-tauri/src/pty.rs`.
|
||||||
|
- Evidence: `tests/smoke/features/terminal.smoke.mjs` and `tests/unit/features/terminal.spec.ts`, with screenshots in both themes and at 360 pixels in `output/smoke/features/terminal/`.
|
||||||
|
- Replaces / replaced by: The settings dialog and the ANSI color map of the Terminal plugin. The terminal roles of [UI-042](#ui-042--theme-file-format-3-and-terminal-colors) and the selection cap of [UI-029](#ui-029--text-selection-transparency) stay.
|
||||||
|
- Limits: The smoke tests use mock shells. Real shells, dictation, and native desktop appearance need user review. The old package stays installed until the user removes it.
|
||||||
|
|
||||||
|
### UI-059 — The PDF toolbar on shared controls
|
||||||
|
|
||||||
|
- Type: Rule change
|
||||||
|
- Date: 2026-10-29
|
||||||
|
- Status: Implemented for user review
|
||||||
|
- Decision source: The owner decisions of Phase 7, stage 7-4 (2026-10-29), and decision 5C.
|
||||||
|
- Previous rule: The PDF Viewer plugin (`runestone.pdf-viewer` 0.0.5) drew its own toolbar buttons, tooltip spans, and `title` tooltips. **Fit width** and **Reload PDF** showed a caption. Disabled buttons faded with opacity. Rotation used an icon that the plugin drew. All strings were English only.
|
||||||
|
- New rule: PDF Viewer is a native feature with a switch in Settings → Features. Each PDF tab has one toolbar of shared `IconButton` controls with the shared tooltip: **Previous page**, the page field, the page count, **Next page**, **Zoom out**, the zoom percent, **Zoom in**, **Fit width**, **Rotate clockwise**, and **Reload PDF**. All buttons are icon only. **Fit width** is a toggle with the selection fill and the accent bar while the page fits the tab. Previous and next page use the `up` and `down` icons of the find panel. The new shared icons are `zoom-in`, `zoom-out`, `fit-width`, and `rotate`. The toolbar wraps in a narrow tab. The page is white paper in both themes. All strings come from the catalog.
|
||||||
|
- Reason: The owner chose response time and memory over the plugin API. The PDF toolbar is a compact toolbar of familiar actions, so it follows the icon rules of [Icons and labels](ui-design.md#icons-and-labels).
|
||||||
|
- Scope: The PDF tab, its toolbar, its password form, its status line, the file tree mark of PDF files, and Settings → Features.
|
||||||
|
- Shared implementation: `src/lib/features/pdf/`, `src/lib/features/pdfDocument.ts`, `src/lib/features/session.ts`, `src/lib/ui/Icon.svelte`, and `src/lib/ui/IconButton.svelte`.
|
||||||
|
- Evidence: `tests/smoke/features/pdf.smoke.mjs` and `tests/unit/features/pdf.spec.ts`, with screenshots in both themes, at 900 pixels, and with keyboard focus in `output/smoke/features/pdf/`.
|
||||||
|
- Replaces / replaced by: The toolbar of the PDF Viewer plugin.
|
||||||
|
- Limits: The tab shows one page at a time. The old package stays installed until the user removes it.
|
||||||
|
|
||||||
|
### UI-060 — Native Project Management
|
||||||
|
|
||||||
|
- Type: Rule change
|
||||||
|
- Date: 2026-10-29
|
||||||
|
- Status: Implemented for user review
|
||||||
|
- Decision source: The owner decisions of Phase 7, stage 7-5 (2026-10-29), and decision 5C.
|
||||||
|
- Previous rule: The Project Management plugin (`runestone.pm` 0.2.49) opened from the **Plug-in views** menu. It bundled the tooltip and icon helpers of the SDK, and its strings were English only. Its settings were a settings view of the plugin. It read boards and cards from visible Markdown notes and from `.runestone/pm/`. It offered the boards service to other plugins, and it read board frames through `api.backgrounds`.
|
||||||
|
- New rule: Project Management is a native feature with a switch in Settings → Features. A ribbon button with the `kanban` icon, after Terminal, opens the default board of the workspace or All tasks. The button is active while a Project Management tab is active. **Plug-in views** does not list Project Management. The board scope, the select choices, and the details pickers use the shared action menu. Icon-only controls use the shared tooltip and the shared action icons. All interface text comes from the catalog. **Settings → Project Management** shows only while the feature is on. It has **Priority levels** and **Default board**, and each change saves at once. **More actions** → **Project Management settings** shows the same component. The feature reads only `.runestone/pm/`. For a workspace with data in visible notes, the **Migrate Project Management data** panel names the data. It offers **Migrate** and **Not now**. The migration keeps exact backups and does not change the original files. **Migration complete** lists the original files for the user to remove.
|
||||||
|
- Reason: The owner chose response time and memory over the plugin API. One ribbon button is easier to find than a menu entry. A migration that the user starts keeps the original notes safe.
|
||||||
|
- Scope: The ribbon button, the board tabs, All tasks, Settings → Project Management, the migration panel, and the Background board list.
|
||||||
|
- Shared implementation: `src/lib/features/pm/`, `src/lib/features/pmSettings.ts`, `src/lib/features/pmBoards.ts`, `src/lib/features/ProjectManagementSettings.svelte`, `src/lib/layout/PluginRibbon.svelte`, and `src/lib/features/session.ts`.
|
||||||
|
- Evidence: `tests/smoke/features/pm*.smoke.mjs` and `tests/unit/features/pm/`, with screenshots in both themes in `output/smoke/features/`. `pmLanguage.smoke.mjs` shows a board in French.
|
||||||
|
- Replaces / replaced by: The Project Management plugin, its settings view, the boards service, and `api.backgrounds`. The rules of [UI-033](#ui-033--list-capacity-and-a-frozen-all-tasks-overview) through [UI-038](#ui-038--fixed-workspace-default-board) stay.
|
||||||
|
- Limits: **More actions**, the card actions, and the list actions stay popup panels of the feature. The old package stays installed until the user removes it.
|
||||||
|
|||||||
+37
-17
@@ -63,10 +63,10 @@ Windows is the primary platform. macOS and Linux builds are experimental.
|
|||||||
| `plugins.rs` | Plugin package review, installation, enable state, removal, and recovery |
|
| `plugins.rs` | Plugin package review, installation, enable state, removal, and recovery |
|
||||||
| `plugin_sources.rs` | Plugin downloads from Gitea releases |
|
| `plugin_sources.rs` | Plugin downloads from Gitea releases |
|
||||||
| `git.rs` | The Git service of the Git feature. 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. |
|
| `features.rs` | Reads the old plugin packages of the native features one time, for the first-start migration. It changes no plugin file. |
|
||||||
| `pty.rs`, `terminal_platform.rs` | Pseudo-terminals for the Terminal plugin |
|
| `pty.rs`, `terminal_platform.rs` | The shell sessions of the Terminal feature, the shell search, and terminal windows. A session belongs to the window and the page that opened it. |
|
||||||
| `browser.rs` | The process of the built-in browser engine |
|
| `browser.rs` | The process of the built-in browser engine |
|
||||||
| `backgrounds.rs` | Background image folders for themes and plugins |
|
| `backgrounds.rs` | The image folder of the Background feature: the folder dialog, the kept folder (`background-folder.json` in the app data folder), the image list and reads, the sidecar file, and the folder migration from the Background Slideshow plugin |
|
||||||
| `spelling.rs` | Spelling suggestions from the operating system (Windows) |
|
| `spelling.rs` | Spelling suggestions from the operating system (Windows) |
|
||||||
| `settings.rs`, `theme.rs` | The Settings window and theme export |
|
| `settings.rs`, `theme.rs` | The Settings window and theme export |
|
||||||
| `preferences.rs` | The settings file of the user. It reads, writes, and migrates the file, and replaces a damaged file. |
|
| `preferences.rs` | The settings file of the user. It reads, writes, and migrates the file, and replaces a damaged file. |
|
||||||
@@ -88,7 +88,7 @@ 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`) |
|
| `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 |
|
| `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 |
|
| `browser/` | The interface of the built-in browser |
|
||||||
| `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). |
|
| `features/` | The native features with an off switch: the catalog (`catalog.ts`), the switches (`state.ts`), the first-start migration, the loader, the launch rules, and the Background settings (`backgroundSettings.ts`). Each feature has a folder: `git/`, `background/`, `terminal/`, `pdf/`, and `pm/`. The main-bundle files of Terminal are `terminalKeys.ts`, `terminalSettings.ts`, `terminalHost.ts`, `TerminalHost.svelte`, and `TerminalSettings.svelte`. The main-bundle files of Project Management are `pmSettings.ts`, `pmBoards.ts`, and `ProjectManagementSettings.svelte`. See [Native features](#native-features). |
|
||||||
| `completion/` | Contracts and services that plugins use |
|
| `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 |
|
| `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`) |
|
| `theme/` | Appearance settings, palettes, and the theme tokens (`tokens.css`) |
|
||||||
@@ -114,11 +114,12 @@ A new command needs an entry in `generate_handler!` in `lib.rs`, in the command
|
|||||||
| Data | Location |
|
| Data | Location |
|
||||||
| --- | --- |
|
| --- | --- |
|
||||||
| Documents | Ordinary files in the workspace folder |
|
| Documents | Ordinary files in the workspace folder |
|
||||||
| Workspace state: tab order, pins, bookmarks, templates, Project Management boards | `.runestone/` in the workspace |
|
| Workspace state: tab order, pins, bookmarks, templates, and the boards, cards, labels, and images of Project Management (`.runestone/pm/`) | `.runestone/` in the workspace |
|
||||||
| Installed plugins and their settings | The app data folder. See [plugin storage](plugin-host.md#storage-and-recovery). |
|
| Installed plugins and their settings | The app data folder. See [plugin storage](plugin-host.md#storage-and-recovery). |
|
||||||
| Preferences: general settings, appearance, custom themes, display language | `settings.json` in the app config folder |
|
| Preferences: general settings, appearance, custom themes, display language, feature switches, Background, Terminal, Project Management | `settings.json` in the app config folder |
|
||||||
|
| The image folder of Background | `background-folder.json` in the app data folder. The image of the image source stays in the WebView storage (IndexedDB). |
|
||||||
| Browser profiles, bookmarks, history, browser settings, and Chromium caches | `browser/` in the local app data folder. On Windows, this is `%LOCALAPPDATA%\com.runestone.app\browser\`. See [Built-in browser runtime](#built-in-browser-runtime). |
|
| Browser profiles, bookmarks, history, browser settings, and Chromium caches | `browser/` in the local app data folder. On Windows, this is `%LOCALAPPDATA%\com.runestone.app\browser\`. See [Built-in browser runtime](#built-in-browser-runtime). |
|
||||||
| Window layout and the open tabs of each workspace | The WebView storage (`localStorage`) of the app. RuneStone can lose these values without harm. |
|
| Window layout, the open tabs of each workspace, and the view state of each Project Management tab (`runestone.pm.viewStates`) | The WebView storage (`localStorage`) of the app. RuneStone can lose these values without harm. |
|
||||||
|
|
||||||
#### The settings file
|
#### The settings file
|
||||||
|
|
||||||
@@ -135,13 +136,16 @@ On macOS, it is `~/Library/Application Support/<identifier>/`. On Linux, it is `
|
|||||||
"customThemes": [],
|
"customThemes": [],
|
||||||
"customThemesLegacy": [],
|
"customThemesLegacy": [],
|
||||||
"language": "en",
|
"language": "en",
|
||||||
"features": { "git": true }
|
"features": { "git": true, "background": true, "terminal": true, "pdf": true, "pm": true },
|
||||||
|
"background": { "source": "folder", "seconds": 60, "order": "name", "paused": false, "targets": ["app"], "overlay": 0, "position": "center", "size": "cover" },
|
||||||
|
"terminal": { "defaultProfile": "", "fontSize": 13, "scrollback": 10000, "cursorBlink": true },
|
||||||
|
"projectManagement": { "priorityLevels": 3 }
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
| Rule | Detail |
|
| Rule | Detail |
|
||||||
| --- | --- |
|
| --- | --- |
|
||||||
| 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. |
|
| Sections | `general`, `appearance`, `customThemes`, `customThemesLegacy` (the original version 1 themes), `language`, `features` (the switches of the native features), `background` (the source, the timing, the targets, and the folder layout of Background), and `terminal` (the default profile, the font size, the scrollback, and the cursor of Terminal). `projectManagement` holds the priority levels of Project Management. 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. |
|
| 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. |
|
| 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-<seconds>.json` and writes a new file with the defaults. The first window that reads the settings shows a message one time. |
|
| Damaged file | The host moves the file to `settings.corrupt-<seconds>.json` and writes a new file with the defaults. The first window that reads the settings shows a message one time. |
|
||||||
@@ -206,22 +210,39 @@ Errors of the plugin API stay in English, because they are for plugin developers
|
|||||||
|
|
||||||
## Native features
|
## Native features
|
||||||
|
|
||||||
Git is a native feature: host code with an off switch in **Settings → Features**. It does not use the plugin API.
|
Git, Background, Terminal, PDF Viewer, and Project Management are native features: host code with an off switch in **Settings → Features**. They do not use the plugin API.
|
||||||
|
|
||||||
| Part | File |
|
| Part | File |
|
||||||
| --- | --- |
|
| --- | --- |
|
||||||
| The catalog: ID, old plugin ID, name, views, and commands | `src/lib/features/catalog.ts` |
|
| The catalog: ID, old plugin ID, name, views, commands, and document types | `src/lib/features/catalog.ts` |
|
||||||
| The switches: the `features` settings section | `src/lib/features/state.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` |
|
| The first start: each switch takes the state of the old plugin package, or the default of the feature when `followsPackage` is false | `src/lib/features/migration.ts` and `src-tauri/src/features.rs` |
|
||||||
| One import at first need in each window | `src/lib/features/loader.ts` |
|
| 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` |
|
| A start without a view: the launch rules, also the rule for browser windows | `src/lib/features/launch.ts` |
|
||||||
|
| Views, commands, and document tabs in the workbench | `src/lib/features/session.ts` and `src/lib/plugins/external.ts` |
|
||||||
| The feature code | `src/lib/features/<feature>/index.ts` and its components |
|
| The feature code | `src/lib/features/<feature>/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.
|
- 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.
|
||||||
|
- A command without a view loads the feature and calls `FeatureInstance.run`. A launch rule starts the instance at once when it wants it, and again after each change of its settings.
|
||||||
|
- Background has a launch rule: it loads when the `background` section selects a folder, or an image that exists. Its settings section and its "has a source" test are in `src/lib/features/backgroundSettings.ts`, in the main bundle. It also runs in browser windows. In the settings window, only its settings component loads (`mountSettings`).
|
||||||
|
- The first start makes the `background` section from the kept settings of the Background Slideshow plugin and from the old background image. `background_migrate` copies the folder of the old plugin grant to the host only when the host has no folder.
|
||||||
|
- Terminal has no view and no launch rule. `TerminalHost.svelte` puts the panel in the workbench and in the terminal window, and the first use loads the module. `terminalKeys.ts` holds the shortcuts and the Help rows. Settings → Terminal (`TerminalSettings.svelte`) loads no xterm.
|
||||||
|
- `@xterm/xterm` and `@xterm/addon-fit` are host dependencies. `pnpm check:features` keeps them out of the start chunks.
|
||||||
|
- PDF Viewer has a document type and no view. The file tree marks PDF files through `identifyPdf` in `src/lib/features/pdfDocument.ts`, in the main bundle. The first PDF tab loads the module and calls `FeatureInstance.mountDocument`. Each tab reads its file with `workspace_read_bytes` and starts its own PDF.js worker. Closing the tab, or Off, stops the worker.
|
||||||
|
- `pdfjs-dist` is a host dependency. `src/lib/features/pdf/engine.ts` loads the minified build. The worker, the character maps, the standard fonts, and the image decoders are Vite assets of the app, so PDF.js makes no network request. `build.assetsInlineLimit` in `vite.config.js` keeps these files out of the code.
|
||||||
|
- Project Management has one editor view, `planning`, with `launch: true`. The view pattern `board-<hex of the board ID>` gives each board its own tab. Its ribbon button in `PluginRibbon.svelte` calls the launch, which opens the default board of the workspace or All tasks. It has no command.
|
||||||
|
- Project Management reads and writes only `.runestone/pm/`. `storage/legacy.ts` finds data in the old format of visible notes. The interface then offers the migration, with backups in `.runestone/pm/backups/`. It migrates only after the user chooses it.
|
||||||
|
- `pm/storage/` and `pm/model/` stay pure TypeScript without host modules, so the `runestone-project-management` skill can bundle them. They mark their user-visible text with `message()` from `storage/message.ts` and keep it in English. The interface translates that text with `localize()` in `pm/ui/text.ts`.
|
||||||
|
- The `projectManagement` section holds the priority levels (`pmSettings.ts`). The default board is `defaultBoardId` in `.runestone/pm/workspace.json`, so each workspace has its own. Appearance → Background reads the board list from the same file through `pmBoards.ts`, without the feature code.
|
||||||
|
- The first start makes the `projectManagement` section from the kept settings of the Project Management plugin. When `localStorage` has no view states, it also copies the view states of the plugin.
|
||||||
|
- `yaml` is a host dependency of Project Management. The card descriptions use the markdown-it of the host.
|
||||||
|
- [THIRD_PARTY_NOTICES.md](../THIRD_PARTY_NOTICES.md) gives the version, license, and source of each third-party package that a feature includes. Update it when you add or update such a package.
|
||||||
|
- The first start makes the `terminal` section from the `runestone.terminal` key of `localStorage`, which the Terminal plugin wrote. The old key stays.
|
||||||
|
- Before Terminal goes off, Settings asks `pty_running` for the shells of all windows. Off closes the sessions of each window.
|
||||||
- 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.
|
- 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.
|
- 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.
|
- 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`.
|
- 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`. Add a launch rule only when the feature must run without a view.
|
||||||
|
|
||||||
## Plugin SDK
|
## Plugin SDK
|
||||||
|
|
||||||
@@ -264,7 +285,6 @@ A test states what it needs near its top. The runner skips the test, with the re
|
|||||||
|
|
||||||
| Line | Requirement |
|
| Line | Requirement |
|
||||||
| --- | --- |
|
| --- | --- |
|
||||||
| `// @requires plugin:terminal` | The compiled Terminal plugin |
|
|
||||||
| `// @requires repo:RuneStone_Local_Autocomplete/src` | 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`. |
|
| `// @requires electron` | The browser engine dependencies. Run `npm ci --prefix browser-runtime`. |
|
||||||
| `// @known-issue <defect>` | 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. |
|
| `// @known-issue <defect>` | 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. |
|
||||||
@@ -273,14 +293,14 @@ A test states what it needs near its top. The runner skips the test, with the re
|
|||||||
| --- | --- |
|
| --- | --- |
|
||||||
| `SMOKE_URL` | The frontend address. The default is `http://127.0.0.1:1420`. When the runner starts Vite, it uses the port of this address, so two checkouts can run tests at the same time. |
|
| `SMOKE_URL` | The frontend address. The default is `http://127.0.0.1:1420`. When the runner starts Vite, it uses the port of this address, so two checkouts can run tests at the same time. |
|
||||||
| `RUNESTONE_PLUGIN_REPOS` | The folder of the sibling plugin checkouts. The default is the parent folder of this repository. |
|
| `RUNESTONE_PLUGIN_REPOS` | The folder of the sibling plugin checkouts. The default is the parent folder of this repository. |
|
||||||
| `RUNESTONE_TERMINAL_DIST` | The compiled Terminal plugin. The default is `RuneStone_Terminal/dist` in that folder. |
|
|
||||||
| `RUNESTONE_CSP` | `1` sends and checks the content security policy. `--csp` sets it. |
|
| `RUNESTONE_CSP` | `1` sends and checks the content security policy. `--csp` sets it. |
|
||||||
| `CHROME_PATH` | A Chromium browser for Playwright |
|
| `CHROME_PATH` | A Chromium browser for Playwright |
|
||||||
| `PLAYWRIGHT_MODULE` | A different Playwright package |
|
| `PLAYWRIGHT_MODULE` | A different Playwright package |
|
||||||
|
|
||||||
To write a smoke test, start from an existing test in the same area. The harness in `tests/smoke/_harness/index.mjs` starts the browser, mocks the Tauri commands, and gives an in-memory workspace.
|
To write a smoke test, start from an existing test in the same area. The harness in `tests/smoke/_harness/index.mjs` starts the browser, mocks the Tauri commands, and gives an in-memory workspace.
|
||||||
|
|
||||||
The harness also has default handlers for the settings file and for tab transfers. All pages of one browser context share them.
|
The harness also has default handlers for the settings file, for tab transfers, and for the `pty_*` shells of Terminal. All pages of one browser context share them.
|
||||||
|
The mock shell sends its output through the channel of `pty_open`. To send more, use `window.__TEST__.pty.output(id, text)` and `window.__TEST__.pty.exit(id, code)`.
|
||||||
To seed preferences, set the old `localStorage` keys before the first load. The app then migrates them.
|
To seed preferences, set the old `localStorage` keys before the first load. The app then migrates them.
|
||||||
To read or change a section later, use `window.__TEST__.settings(section)` and `window.__TEST__.writeSettings(section, value)`.
|
To read or change a section later, use `window.__TEST__.settings(section)` and `window.__TEST__.writeSettings(section, value)`.
|
||||||
A failed test saves `failure.png` in its output folder and prints the page console errors and warnings.
|
A failed test saves `failure.png` in its output folder and prints the page console errors and warnings.
|
||||||
|
|||||||
@@ -0,0 +1,168 @@
|
|||||||
|
# Project Management guide
|
||||||
|
|
||||||
|
[RuneStone](../../README.md) · [User guide](../user-guide.md)
|
||||||
|
|
||||||
|
This guide explains how to plan work with boards, lists, and cards in RuneStone. It also explains the timeline and calendar views of the same cards.
|
||||||
|
|
||||||
|
Project Management is part of RuneStone and is on by default. To turn it off, see [Turn Project Management off](#turn-project-management-off).
|
||||||
|
|
||||||
|
## Open Project Management
|
||||||
|
|
||||||
|
Select **Project Management** (the board icon) in the left ribbon. It opens the default board of the workspace, or **All tasks** when the workspace has no default board. See [Choose the default board](#choose-the-default-board).
|
||||||
|
|
||||||
|
Each board opens in its own tab. To open another board in the same tab, select the board name in the toolbar. Then select a board or **All tasks**.
|
||||||
|
|
||||||
|
A workspace without boards shows **Create your first board**. Select it and enter a name.
|
||||||
|
|
||||||
|
## Boards and lists
|
||||||
|
|
||||||
|
A board holds lists, and a list holds cards. A new board starts with the lists **To do**, **In progress**, and **Done**.
|
||||||
|
|
||||||
|
| Action | How |
|
||||||
|
| --- | --- |
|
||||||
|
| Create a board | **More actions** (the three dots) → **New board** |
|
||||||
|
| Rename a board | **Rename board** beside the board name, or **More actions** → **Rename board** |
|
||||||
|
| Archive or restore a board | **More actions** → **Archive board** or **Restore board** |
|
||||||
|
| Delete a board | **More actions** → **Delete board**. The cards stay in All tasks. You cannot undo this action. |
|
||||||
|
| Add a list | **Add a list** in the toolbar of a board |
|
||||||
|
| Rename a list, or set its status | List actions (the button in the list header) → **Edit list** |
|
||||||
|
| Move a list | Drag its header, or use **Move left** and **Move right** in the list actions |
|
||||||
|
| Set a card limit | List actions → **Set list limit**. A warning shows at the limit. Cards can still go into the list. |
|
||||||
|
| Archive all cards of a list | List actions → **Archive all cards** |
|
||||||
|
| Delete a list | List actions → **Delete list**. Its cards go to **Unlisted**. Their status does not change. |
|
||||||
|
| Collapse or expand a list | The collapse button in the list header. A collapsed list is a narrow strip with its name and card count. |
|
||||||
|
|
||||||
|
**Status when a card enters this list** sets the status of each card that you move into the list. Choose **Do not change status** to keep the status of the card.
|
||||||
|
|
||||||
|
## Cards
|
||||||
|
|
||||||
|
| Action | How |
|
||||||
|
| --- | --- |
|
||||||
|
| Create a card | **Add a card** at the bottom of a list, or **More actions** → **New card** |
|
||||||
|
| Open the card details | Select the card |
|
||||||
|
| Move a card on the board | Drag the card, or use **Move to list**, **Move up**, and **Move down** in the card actions |
|
||||||
|
| Put a card on another board | Card actions → **Move to board** |
|
||||||
|
| Take a card off this board | Card actions → **Remove from board**. The card stays in All tasks and on its other boards. |
|
||||||
|
| Archive or restore a card | Card actions → **Archive** or **Restore**. **More actions** → **Show archived** shows the archived cards. |
|
||||||
|
| Delete a card | Card actions → **Delete card**. It removes the card from all boards. You cannot undo this action. |
|
||||||
|
| Work with more than one card | **Select cards** in the toolbar. Then move the selected cards to a list or a board, or delete them. |
|
||||||
|
| Find a card | **Search tasks** in the toolbar. The search looks in titles, descriptions, tags, labels, assignments, and custom fields. |
|
||||||
|
|
||||||
|
A card can be on more than one board, with a different list on each board.
|
||||||
|
|
||||||
|
The card details have the title, the labels, and the description in Markdown.
|
||||||
|
A change to the description stays a draft until you select **Save**. **Cancel** restores the saved text. When you close the card with a draft, the card shows an unsaved marker.
|
||||||
|
Board and list changes save at once. Other fields save when you close the card details.
|
||||||
|
|
||||||
|
### Card details
|
||||||
|
|
||||||
|
Select **Add details** in the card details to add one of these fields:
|
||||||
|
|
||||||
|
| Field | Use |
|
||||||
|
| --- | --- |
|
||||||
|
| **Priority** | The urgency of the card, apart from its labels |
|
||||||
|
| **Labels** | Colored labels that all boards of the workspace share |
|
||||||
|
| **Tags** | Plain words for the search |
|
||||||
|
| **Planned dates** | The first and the last day of the work. The Gantt view shows them as a bar. |
|
||||||
|
| **Deadline** | The due date. Gantt and Calendar show it with ◆. |
|
||||||
|
| **Work session** | A start time and an end time. The Calendar view shows the session. |
|
||||||
|
| **Assignments** | People, teams, or customers |
|
||||||
|
| **Color** | The color of the card |
|
||||||
|
| **Custom field** | A name and a value of your choice |
|
||||||
|
| **Subtasks and linked cards** | Smaller tasks of the card, and other cards that block it, that it blocks, or that relate to it |
|
||||||
|
| **Card cover** | An image of the card that shows on the board |
|
||||||
|
|
||||||
|
**More actions** → **Add existing note** makes a new card from a Markdown note of the workspace. The card gets the file name as its title and the note text as its description.
|
||||||
|
The note does not change. Later edits to the note do not change the card.
|
||||||
|
|
||||||
|
## Labels and priority
|
||||||
|
|
||||||
|
Select **Manage labels** (the tag icon) in the toolbar to add, rename, recolor, or delete labels.
|
||||||
|
All boards of the workspace share the labels. A change of name or color applies to each card with the label. When you delete a label, RuneStone removes it from all cards.
|
||||||
|
|
||||||
|
Priority has two, three, or five levels. To change the number of levels, see [Change the Project Management settings](#change-the-project-management-settings).
|
||||||
|
|
||||||
|
## Views
|
||||||
|
|
||||||
|
The buttons at the left of the toolbar change the view of the board.
|
||||||
|
|
||||||
|
| View | Shows |
|
||||||
|
| --- | --- |
|
||||||
|
| **Kanban** | The lists and their cards |
|
||||||
|
| **Gantt** | Each card with its planned dates as a bar and its deadline as ◆, for 28 days from the visible date |
|
||||||
|
| **Calendar** | Deadlines and work sessions by **Day**, **Week**, or **Month**, in the time zone of your computer |
|
||||||
|
|
||||||
|
**Previous**, **Today**, **Next**, and the date field change the visible dates of Gantt and Calendar.
|
||||||
|
|
||||||
|
In Calendar, you can create a card from a date:
|
||||||
|
|
||||||
|
- In **Month**, select the number of a day to create a card with that deadline.
|
||||||
|
- In **Day** or **Week**, select an hour to create a card with a one-hour work session.
|
||||||
|
|
||||||
|
Gantt and Calendar do not move a card when you drag it. To change dates, open the card and edit **Planned dates**, **Deadline**, or **Work session**.
|
||||||
|
|
||||||
|
## All tasks
|
||||||
|
|
||||||
|
**All tasks** shows the cards of all boards of the workspace in one view.
|
||||||
|
|
||||||
|
- Lists with the same name on different boards share one column. The match ignores uppercase and lowercase letters.
|
||||||
|
- In each column, the cards show below the name of their board. Cards without an active board show below **No active board**.
|
||||||
|
- You cannot drag cards between columns. To move a card, open it and change **Board** or **List**, or open its board.
|
||||||
|
- A new card in All tasks needs a board. Choose the board and the list in the card details.
|
||||||
|
|
||||||
|
## Images
|
||||||
|
|
||||||
|
To add an image to a card, paste it or drop it into the description, or select **Add image**.
|
||||||
|
Use a PNG, JPEG, GIF, or WebP image of at most 50 MiB.
|
||||||
|
To show an image on the board, add **Card cover** and choose one of the images of the card.
|
||||||
|
|
||||||
|
**More actions** → **Customize background** sets an image behind the open board, or behind All tasks.
|
||||||
|
To show the Background slideshow on the boards, see [Choose where the background shows](themes.md#choose-where-the-background-shows).
|
||||||
|
|
||||||
|
## Choose the default board
|
||||||
|
|
||||||
|
1. Open **Settings → Project Management**, or select **More actions** → **Project Management settings**.
|
||||||
|
2. Select **Default board**.
|
||||||
|
3. Select a board, or **All tasks**.
|
||||||
|
|
||||||
|
Each workspace has its own default board. The ribbon button then opens that board. Restored tabs keep their board.
|
||||||
|
An archived or deleted default board opens All tasks.
|
||||||
|
|
||||||
|
## Change the Project Management settings
|
||||||
|
|
||||||
|
Open **Settings → Project Management**. The page shows only while Project Management is on. Each change saves at once.
|
||||||
|
|
||||||
|
| Setting | Values |
|
||||||
|
| --- | --- |
|
||||||
|
| **Priority levels** | **2** (High and Low), **3** (High, Medium, and Low), or **5** (Highest through Lowest). The default is 3. The priorities of existing cards do not change. |
|
||||||
|
| **Default board** | **All tasks** or one board of the current workspace. See [Choose the default board](#choose-the-default-board). |
|
||||||
|
|
||||||
|
After an update, the first start copies the priority levels of the old Project Management plugin.
|
||||||
|
|
||||||
|
## Where the boards are
|
||||||
|
|
||||||
|
The boards, cards, labels, and images of a workspace are in `.runestone/pm/` in the workspace folder.
|
||||||
|
To see this folder in the file tree, turn on **Show .runestone folder** in Settings → General.
|
||||||
|
|
||||||
|
Git ignores `.runestone/pm/`, because RuneStone puts a `.gitignore` file there. To keep a copy of your boards, back up this folder separately.
|
||||||
|
|
||||||
|
## Move old Project Management notes
|
||||||
|
|
||||||
|
Early versions of the Project Management plugin kept boards and cards in visible Markdown notes, and labels in `runestone-pm-labels.json`.
|
||||||
|
RuneStone reads only `.runestone/pm/`. When a workspace has data in the old format, Project Management shows **Migrate Project Management data**.
|
||||||
|
|
||||||
|
1. Read the list of boards, task notes, and label files.
|
||||||
|
2. If the offer names notes with invalid properties, repair these notes first.
|
||||||
|
3. Select **Migrate**. RuneStone copies the data to `.runestone/pm/` and keeps exact backups in `.runestone/pm/backups/`.
|
||||||
|
4. Examine the boards.
|
||||||
|
5. Remove the original files that **Migration complete** lists, then select **Done**.
|
||||||
|
|
||||||
|
The migration does not change or remove the original files. **Not now** hides the offer in this tab.
|
||||||
|
|
||||||
|
## Turn Project Management off
|
||||||
|
|
||||||
|
1. Open **Settings → Features**.
|
||||||
|
2. Clear **Project Management**.
|
||||||
|
|
||||||
|
Off closes the Project Management tabs and removes the ribbon button and the settings page in all windows.
|
||||||
|
Your boards stay in `.runestone/pm/`, and your settings stay. Turn Project Management on again in the same place.
|
||||||
+47
-20
@@ -1,29 +1,30 @@
|
|||||||
# Terminal guide
|
# Terminal guide
|
||||||
|
|
||||||
[RuneStone](../../README.md) · [User guide](../user-guide.md) · [Install a plugin](../plugins.md#install-a-plugin)
|
[RuneStone](../../README.md) · [User guide](../user-guide.md)
|
||||||
|
|
||||||
This guide explains how to use shells, scripts, and workspace tasks with the optional Terminal plugin.
|
This guide explains how to use shells, scripts, and workspace tasks in the terminal of RuneStone.
|
||||||
|
|
||||||
Install and enable the Terminal plugin first. The shells and script runtimes that you use must be installed on your computer.
|
Terminal is part of RuneStone and is on by default. The shells and script runtimes that you use must be installed on your computer. To turn Terminal off, see [Turn Terminal off](#turn-terminal-off).
|
||||||
|
|
||||||
## Open and arrange terminals
|
## Open and arrange terminals
|
||||||
|
|
||||||
| Action | How |
|
| Action | How |
|
||||||
| --- | --- |
|
| --- | --- |
|
||||||
| Show or hide the terminal panel | Ctrl+` or Ctrl+J. Sessions and scrollback stay. |
|
| Show or hide the terminal panel | **Terminal** in the left ribbon, Ctrl+`, or Ctrl+J. Sessions and scrollback stay. |
|
||||||
| New terminal | Ctrl+Shift+` or the + button |
|
| New terminal | Ctrl+Shift+` or the + button |
|
||||||
| Split the active terminal | Ctrl+Shift+5. The new pane uses the same folder and profile. |
|
| Split the active terminal | Ctrl+Shift+5 or **Split terminal**. The new pane uses the same folder and profile. |
|
||||||
| New terminal window | Ctrl+Shift+Alt+` |
|
| New terminal window | Ctrl+Shift+Alt+`, or **New terminal window** in the profile menu |
|
||||||
| End the active session | **Kill terminal**, or Delete while an entry in the terminal list has focus |
|
| End the active session | **Kill terminal**, or Delete while an entry in the terminal list has focus |
|
||||||
| Change the panel size | **Maximize panel** or **Restore panel**. Shells do not restart. |
|
| Change the panel size | **Maximize panel** or **Restore panel**. Shells do not restart. |
|
||||||
| End all sessions in the panel | **Close terminal (end all sessions)** |
|
| End all sessions in the panel | **Close terminal (end all sessions)** |
|
||||||
|
|
||||||
The terminal list shows only when more than one session is open.
|
The terminal list shows only when more than one session is open.
|
||||||
Closing a separate terminal window ends its sessions.
|
Closing a terminal window ends its sessions. When you close a workspace window with running sessions, RuneStone asks first.
|
||||||
|
You can type before a shell starts. RuneStone sends the text when the shell is ready.
|
||||||
|
|
||||||
## Choose a shell
|
## Choose a shell
|
||||||
|
|
||||||
Open the menu beside the + button to start a terminal with a specific profile.
|
Open **Terminal profiles and tasks** (the arrow beside the + button) to start a terminal with a specific profile.
|
||||||
|
|
||||||
| System | Profiles |
|
| System | Profiles |
|
||||||
| --- | --- |
|
| --- | --- |
|
||||||
@@ -31,10 +32,26 @@ Open the menu beside the + button to start a terminal with a specific profile.
|
|||||||
| macOS and Linux | Bash and PowerShell |
|
| macOS and Linux | Bash and PowerShell |
|
||||||
|
|
||||||
The menu shows only the shells that RuneStone finds on your computer.
|
The menu shows only the shells that RuneStone finds on your computer.
|
||||||
The same menu has **Split Terminal with Profile**, **Select Default Profile**, **Configure Terminal Settings**, and the task commands.
|
The same menu has **Split terminal with profile**, **Terminal settings**, **Select the default profile**, and the task commands.
|
||||||
Terminal settings set the font size, scrollback lines, cursor blink, and default profile. RuneStone keeps them on this computer.
|
|
||||||
New terminals get the RuneStone environment, including `PATH`.
|
New terminals get the RuneStone environment, including `PATH`.
|
||||||
|
|
||||||
|
## Change the terminal settings
|
||||||
|
|
||||||
|
Open **Settings → Terminal**, or choose **Terminal settings** in the profile menu. The page shows only while Terminal is on.
|
||||||
|
|
||||||
|
| Setting | Values |
|
||||||
|
| --- | --- |
|
||||||
|
| **Default profile** | The shell of a new terminal. The JavaScript Debug Terminal is not a choice. |
|
||||||
|
| **Font size** | 9 to 28 pixels. The default is 13. |
|
||||||
|
| **Scrollback lines** | 100 to 100,000 lines. The default is 10,000. |
|
||||||
|
| **Blink cursor** | The cursor blinks in the focused terminal. On by default. |
|
||||||
|
|
||||||
|
A change saves at once and applies to all windows. Open terminals take the new font size, scrollback, and cursor. The default profile applies to new terminals.
|
||||||
|
After an update, the first start copies the settings of the old Terminal plugin.
|
||||||
|
|
||||||
|
The terminal colors come from the color theme. The text, the cursor, and the selection use the theme colors. The 16 ANSI colors use the `ansi-*` keys of the theme.
|
||||||
|
To change them, see [Edit a theme](themes.md#edit-a-theme) and [Color keys](themes.md#color-keys).
|
||||||
|
|
||||||
## Copy and paste
|
## Copy and paste
|
||||||
|
|
||||||
- Drag across terminal text to select it.
|
- Drag across terminal text to select it.
|
||||||
@@ -48,24 +65,25 @@ Open **More terminal actions** for these commands:
|
|||||||
|
|
||||||
| Command | Result |
|
| Command | Result |
|
||||||
| --- | --- |
|
| --- | --- |
|
||||||
| **Run Active File** | Saves and runs the active file in the terminal. |
|
| **Scroll to the previous command** / **Scroll to the next command** (Ctrl+Up / Ctrl+Down) | Moves between command prompts. |
|
||||||
| **Run Selected Text** | Sends the text that is selected in the editor to the terminal. |
|
| **Clear the terminal** | Clears the scrollback. |
|
||||||
| **Clear Terminal** | Clears the scrollback. |
|
| **Run the active file** | Saves and runs the active file in the terminal. |
|
||||||
| **Run Recent Command…** (Ctrl+Alt+R) | Runs a command from this session again. |
|
| **Run selected text** | Sends the text that is selected in the editor to the terminal. |
|
||||||
| **Go to Recent Directory…** (Ctrl+G) | Changes to a recent folder. |
|
| **Start dictation** | Starts Windows voice typing. See [Debug JavaScript and use dictation](#debug-javascript-and-use-dictation). |
|
||||||
| **Scroll to Previous Command** / **Next Command** (Ctrl+Up / Ctrl+Down) | Moves between command prompts. |
|
| **Go to a recent folder…** (Ctrl+G) | Changes to a recent folder. |
|
||||||
|
| **Run a recent command…** (Ctrl+Alt+R) | Runs a command from this session again. |
|
||||||
|
|
||||||
**Run Active File** supports Python, JavaScript, PowerShell, Bash, Ruby, Windows batch files, and executables.
|
**Run the active file** supports Python, JavaScript, PowerShell, Bash, Ruby, Windows batch files, and executables.
|
||||||
The terminal keeps command history in memory only. PowerShell and Bash record a command after it finishes. Command Prompt records the text that you submit.
|
The terminal keeps command history in memory only. PowerShell and Bash record a command after it finishes. Command Prompt records the text that you submit.
|
||||||
|
|
||||||
## Configure workspace tasks
|
## Configure workspace tasks
|
||||||
|
|
||||||
A task is a named command that you can start from a menu.
|
A task is a named command that you can start from a menu.
|
||||||
|
|
||||||
1. Choose **Configure Tasks…**. RuneStone creates or opens `.runestone/tasks.json`.
|
1. Choose **Configure tasks…**. RuneStone creates or opens `.runestone/tasks.json`.
|
||||||
2. Add an object to the `tasks` array with `label` and `command`.
|
2. Add an object to the `tasks` array with `label` and `command`.
|
||||||
3. Optionally, add `profile` with one of these IDs: `powershell`, `pwsh`, `git-bash`, `cmd`, or `bash`.
|
3. Optionally, add `profile` with one of these IDs: `powershell`, `pwsh`, `git-bash`, `cmd`, or `bash`.
|
||||||
4. Choose **Run Task…** and select the task.
|
4. Choose **Run a task…** and select the task.
|
||||||
|
|
||||||
Example (`.runestone/tasks.json`):
|
Example (`.runestone/tasks.json`):
|
||||||
|
|
||||||
@@ -84,5 +102,14 @@ Each task runs in its own terminal at the workspace root. Tasks run only when yo
|
|||||||
**JavaScript Debug Terminal** in the profile menu starts a Node.js REPL with a local inspector on a free port.
|
**JavaScript Debug Terminal** in the profile menu starts a Node.js REPL with a local inspector on a free port.
|
||||||
Attach an external debugger to the address that the terminal shows. RuneStone does not include a debugger.
|
Attach an external debugger to the address that the terminal shows. RuneStone does not include a debugger.
|
||||||
|
|
||||||
**Start Dictation** starts Windows voice typing (Win+H) in the focused terminal. Set up the microphone and voice typing in Windows first.
|
**Start dictation** starts Windows voice typing (Win+H) in the focused terminal. Set up the microphone and voice typing in Windows first.
|
||||||
On other systems, use the dictation shortcut of the operating system.
|
On other systems, use the dictation shortcut of the operating system.
|
||||||
|
|
||||||
|
## Turn Terminal off
|
||||||
|
|
||||||
|
1. Open **Settings → Features**.
|
||||||
|
2. Clear **Terminal**.
|
||||||
|
3. If a window runs a shell, RuneStone asks "Terminal sessions will end. Turn off Terminal?". Confirm to continue.
|
||||||
|
|
||||||
|
Off ends the terminal sessions of every window. The Terminal buttons, shortcuts, and Help rows do not show. A terminal window shows "Terminal is off. Turn it on in Settings → Features."
|
||||||
|
Your terminal settings and `.runestone/tasks.json` stay. Turn Terminal on again in the same place.
|
||||||
|
|||||||
+61
-9
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
[RuneStone](../../README.md) · [User guide](../user-guide.md)
|
[RuneStone](../../README.md) · [User guide](../user-guide.md)
|
||||||
|
|
||||||
This guide explains how to choose colors, set a background image, and edit, create, or share a custom theme.
|
This guide explains how to choose colors, show a background, and edit, create, or share a custom theme.
|
||||||
|
|
||||||
Open **Settings → Appearance**. Appearance settings apply to all workspaces on this computer and to all open windows.
|
Open **Settings → Appearance**. Appearance settings apply to all workspaces on this computer and to all open windows.
|
||||||
|
|
||||||
@@ -21,20 +21,72 @@ Each named theme has its own fonts and syntax colors. Fonts come from your compu
|
|||||||
|
|
||||||
## Adjust transparency
|
## Adjust transparency
|
||||||
|
|
||||||
**Transparent surfaces** tints work areas with a background image and compatible plugin surfaces.
|
**Transparent surfaces** tints work areas with a [background](#show-a-background) and compatible plugin surfaces.
|
||||||
Menus stay opaque. With a background image, menus are at least 92% opaque and blur the image.
|
Menus stay opaque. With a background image, menus are at least 92% opaque and blur the image.
|
||||||
Set **Transparency amount** from 0% to 100%. The default is 18%.
|
Set **Transparency amount** from 0% to 100%. The default is 18%.
|
||||||
Turn off **Transparent surfaces** for opaque surfaces. Text and icons stay opaque in both cases.
|
Turn off **Transparent surfaces** for opaque surfaces. Text and icons stay opaque in both cases.
|
||||||
|
|
||||||
## Set a background image
|
## Show a background
|
||||||
|
|
||||||
1. Choose **Choose image…** and select a PNG, JPEG, WebP, or GIF file up to 50 MiB.
|
The **Background** section shows a folder of images as a slideshow, or one image, behind the workspace.
|
||||||
2. Set **Image size** to **Fill**, **Fit**, or **Actual size**.
|
Set **Background source** to **Folder**, **Image**, or **None**.
|
||||||
3. Set **Image position**.
|
|
||||||
4. Set **Image overlay** from -100% to 100%. Negative values lighten the image, and positive values darken it.
|
|
||||||
|
|
||||||
The image shows in new tabs. RuneStone keeps it on this computer.
|
### Show a folder as a slideshow
|
||||||
The Project Management plugin can keep a separate image for a board. The Background Slideshow plugin can replace the image for a time.
|
|
||||||
|
1. Set **Background source** to **Folder**, or choose **Choose folder…**.
|
||||||
|
2. Select a folder with PNG, JPEG, GIF, or WebP images. Each image can be up to 64 MiB.
|
||||||
|
3. Set **Seconds per image** from 1 to 86,400.
|
||||||
|
4. Set **Image order** to **File name** or **Random**.
|
||||||
|
|
||||||
|
**File name** uses natural order, so `2.png` comes before `10.png`. **Random** does not repeat the current image when the folder has other images.
|
||||||
|
Images fade over two seconds. When your system reduces motion, the images change without a fade.
|
||||||
|
RuneStone reads the folder again when a window gets the focus, after a settings change, and after every 10 images.
|
||||||
|
Subfolders, links, and unreadable files do not show. When no image loads, the background goes away, and RuneStone tries again after the image time, at least 5 seconds.
|
||||||
|
**Remove folder** forgets the folder. It changes no file.
|
||||||
|
|
||||||
|
### Show one image
|
||||||
|
|
||||||
|
1. Set **Background source** to **Image**, or choose **Choose image…**.
|
||||||
|
2. Select a PNG, JPEG, WebP, or GIF file up to 50 MiB.
|
||||||
|
|
||||||
|
RuneStone keeps the image on this computer. **Remove image** deletes the saved copy. It does not change your file.
|
||||||
|
|
||||||
|
### Set the layout
|
||||||
|
|
||||||
|
- **Image size**: **Fill**, **Fit**, or **Actual size**.
|
||||||
|
- **Image position**: one of nine positions.
|
||||||
|
- **Image overlay**: from -100% to 100%. Negative values lighten the image, and positive values darken it.
|
||||||
|
|
||||||
|
The folder and the image keep separate layouts.
|
||||||
|
|
||||||
|
### Change one image of the folder
|
||||||
|
|
||||||
|
Portrait images show in full over a blurred fill by default. To change one image:
|
||||||
|
|
||||||
|
1. Open **Per-image appearance**.
|
||||||
|
2. Choose the image in **Image**. Type part of its name to find it.
|
||||||
|
3. Set **Fit**, **Position**, and **Overlay**. The preview shows the result.
|
||||||
|
4. Choose **Save image appearance**.
|
||||||
|
|
||||||
|
**Reset image appearance** returns the image to the folder layout.
|
||||||
|
RuneStone keeps these settings in `.runestone-backgrounds.json` in the image folder. When another program changed the file, choose **Reload image settings** and make the change again.
|
||||||
|
|
||||||
|
### Choose where the background shows
|
||||||
|
|
||||||
|
Under **Show the background in**, select **The workspace and new tabs**, **All Project Management boards**, or one board.
|
||||||
|
The board list shows the Project Management boards of the current workspace. A saved board that is not available shows as **Unavailable board**, so that you can clear it.
|
||||||
|
A blank tab of a browser window also shows the background.
|
||||||
|
|
||||||
|
### Next and Pause
|
||||||
|
|
||||||
|
- **Next background image** in the command palette (Ctrl+Shift+P) or **Next image** in the settings shows the next image in every window.
|
||||||
|
- **Pause background** in the command palette or **Pause slideshow** in the settings keeps the current image. Use the same command to resume.
|
||||||
|
|
||||||
|
### Turn Background off
|
||||||
|
|
||||||
|
Background is on by default. To turn it off, open **Settings → Features** and clear **Background**.
|
||||||
|
Off removes the background at once in all windows, and menus become opaque again. Your folder, image, and settings stay.
|
||||||
|
With **None** or without a folder or an image, Background does not load.
|
||||||
|
|
||||||
## Edit a theme
|
## Edit a theme
|
||||||
|
|
||||||
|
|||||||
+2
-2
@@ -70,10 +70,10 @@ Voice typing is not part of the Linux checks.
|
|||||||
| Editors | Edit Markdown, source code, tables, images, and diagrams. Check undo, keyboard shortcuts, and both themes. |
|
| Editors | Edit Markdown, source code, tables, images, and diagrams. Check undo, keyboard shortcuts, and both themes. |
|
||||||
| Clipboard and dialogs | Copy and paste text, tables, and images. Check folder selection, external links, and file reveal. |
|
| Clipboard and dialogs | Copy and paste text, tables, and images. Check folder selection, external links, and file reveal. |
|
||||||
| Plugins | Install plugin ZIPs through Settings, enable them, restart, disable them, and remove them. Check that plugin data stays. |
|
| Plugins | Install plugin ZIPs through Settings, enable them, restart, disable them, and remove them. Check that plugin data stays. |
|
||||||
| Terminal plugin | Install the Terminal ZIP. Bash starts in the workspace, accepts Unicode, resizes, and exits when its session closes. |
|
| Terminal | Open the terminal panel. Bash starts in the workspace, accepts Unicode, resizes, and exits when its session closes. |
|
||||||
| Settings | Change preferences, restart, and make sure that they stay. Check separate workspace windows. |
|
| Settings | Change preferences, restart, and make sure that they stay. Check separate workspace windows. |
|
||||||
|
|
||||||
For the Terminal ZIP, see [Build examples](plugin-development.md#build-examples) and the [plugin installation guide](plugins.md).
|
For the use of Terminal, see the [Terminal guide](guides/terminal.md).
|
||||||
Check terminal profiles after a desktop launch too. A desktop launcher can have a different `PATH` from an interactive shell.
|
Check terminal profiles after a desktop launch too. A desktop launcher can have a different `PATH` from an interactive shell.
|
||||||
|
|
||||||
Known Linux limits:
|
Known Linux limits:
|
||||||
|
|||||||
+110
-131
@@ -1,12 +1,8 @@
|
|||||||
{
|
{
|
||||||
"date": "2026-10-15",
|
"date": "2026-10-29",
|
||||||
"scope": [
|
"scope": [
|
||||||
"RuneStone",
|
"RuneStone",
|
||||||
"RuneStone_Project_Management",
|
|
||||||
"RuneStone_Terminal",
|
|
||||||
"RuneStone_Background_Slideshow",
|
|
||||||
"RuneStone_Local_Autocomplete",
|
"RuneStone_Local_Autocomplete",
|
||||||
"RuneStone_PDF_Viewer",
|
|
||||||
"RuneStone_CSV_Viewer"
|
"RuneStone_CSV_Viewer"
|
||||||
],
|
],
|
||||||
"limits": [
|
"limits": [
|
||||||
@@ -159,14 +155,6 @@
|
|||||||
"design": "API type declaration, no renderer",
|
"design": "API type declaration, no renderer",
|
||||||
"check": "pnpm check"
|
"check": "pnpm check"
|
||||||
},
|
},
|
||||||
"RuneStone/src/lib/theme/AppearanceSettings.svelte": {
|
|
||||||
"counts": {
|
|
||||||
"action": 1,
|
|
||||||
"localPopup": 2
|
|
||||||
},
|
|
||||||
"design": "Shared action menu for image position and size. Theme choice uses preview cards (UI-047).",
|
|
||||||
"check": "tests/smoke/appearance/backgroundImages.smoke.mjs"
|
|
||||||
},
|
|
||||||
"RuneStone/src/lib/ui/actionMenu.ts": {
|
"RuneStone/src/lib/ui/actionMenu.ts": {
|
||||||
"counts": {
|
"counts": {
|
||||||
"action": 1,
|
"action": 1,
|
||||||
@@ -182,120 +170,6 @@
|
|||||||
"design": "Shared action menu",
|
"design": "Shared action menu",
|
||||||
"check": "tests/smoke/menus/consistency.smoke.mjs"
|
"check": "tests/smoke/menus/consistency.smoke.mjs"
|
||||||
},
|
},
|
||||||
"RuneStone_Project_Management/src/choices-ui.ts": {
|
|
||||||
"counts": {
|
|
||||||
"action": 1
|
|
||||||
},
|
|
||||||
"design": "Shared action menus and searchable picker classes; older-host fallback retained",
|
|
||||||
"check": "RuneStone_Project_Management/tests/menu-audit.spec.ts; tests/shared-menu.spec.ts; tests/relations-menu.spec.ts"
|
|
||||||
},
|
|
||||||
"RuneStone_Project_Management/src/details-ui.ts": {
|
|
||||||
"counts": {
|
|
||||||
"picker": 1,
|
|
||||||
"localPopup": 4
|
|
||||||
},
|
|
||||||
"design": "Shared action menus and searchable picker classes; older-host fallback retained",
|
|
||||||
"check": "RuneStone_Project_Management/tests/menu-audit.spec.ts; tests/shared-menu.spec.ts; tests/relations-menu.spec.ts"
|
|
||||||
},
|
|
||||||
"RuneStone_Project_Management/src/labels-ui.ts": {
|
|
||||||
"counts": {
|
|
||||||
"picker": 1,
|
|
||||||
"localPopup": 3
|
|
||||||
},
|
|
||||||
"design": "Shared action menus and searchable picker classes; older-host fallback retained",
|
|
||||||
"check": "RuneStone_Project_Management/tests/menu-audit.spec.ts; tests/shared-menu.spec.ts; tests/relations-menu.spec.ts"
|
|
||||||
},
|
|
||||||
"RuneStone_Project_Management/src/preferences.ts": {
|
|
||||||
"counts": {
|
|
||||||
"action": 1,
|
|
||||||
"nativeChoice": 1
|
|
||||||
},
|
|
||||||
"design": "Shared choice adapter; native selects hidden on current host, older-host fallback retained",
|
|
||||||
"check": "RuneStone_Project_Management/tests/menu-audit.spec.ts; tests/shared-menu.spec.ts; tests/relations-menu.spec.ts"
|
|
||||||
},
|
|
||||||
"RuneStone_Project_Management/src/priority-ui.ts": {
|
|
||||||
"counts": {
|
|
||||||
"action": 1,
|
|
||||||
"picker": 1,
|
|
||||||
"localPopup": 3
|
|
||||||
},
|
|
||||||
"design": "Shared action menus and searchable picker classes; older-host fallback retained",
|
|
||||||
"check": "RuneStone_Project_Management/tests/menu-audit.spec.ts; tests/shared-menu.spec.ts; tests/relations-menu.spec.ts"
|
|
||||||
},
|
|
||||||
"RuneStone_Project_Management/src/relations-ui.ts": {
|
|
||||||
"counts": {
|
|
||||||
"nativeChoice": 1,
|
|
||||||
"picker": 1,
|
|
||||||
"localPopup": 5
|
|
||||||
},
|
|
||||||
"design": "Shared relationship choice and direct searchable picker rows; older-host choice fallback retained",
|
|
||||||
"check": "RuneStone_Project_Management/tests/relations-menu.spec.ts; tests/menu-audit.spec.ts; tests/related-cards.spec.ts"
|
|
||||||
},
|
|
||||||
"RuneStone_Project_Management/src/tags.ts": {
|
|
||||||
"counts": {
|
|
||||||
"picker": 2,
|
|
||||||
"localPopup": 2
|
|
||||||
},
|
|
||||||
"design": "Shared action menus and searchable picker classes; older-host fallback retained",
|
|
||||||
"check": "RuneStone_Project_Management/tests/menu-audit.spec.ts; tests/shared-menu.spec.ts; tests/relations-menu.spec.ts"
|
|
||||||
},
|
|
||||||
"RuneStone_Project_Management/src/ui.ts": {
|
|
||||||
"counts": {
|
|
||||||
"action": 4,
|
|
||||||
"nativeChoice": 13,
|
|
||||||
"picker": 1,
|
|
||||||
"localPopup": 1
|
|
||||||
},
|
|
||||||
"design": "Shared choice adapter; native selects hidden on current host, older-host fallback retained",
|
|
||||||
"check": "RuneStone_Project_Management/tests/menu-audit.spec.ts; tests/shared-menu.spec.ts; tests/relations-menu.spec.ts; tests/list-limits.spec.ts; tests/all-tasks.spec.ts; tests/card-board-details.spec.ts"
|
|
||||||
},
|
|
||||||
"RuneStone_Terminal/src/TerminalDock.svelte": {
|
|
||||||
"counts": {
|
|
||||||
"action": 1
|
|
||||||
},
|
|
||||||
"design": "Synchronized shared action menu snapshot",
|
|
||||||
"check": "RuneStone_Terminal/scripts/terminal.smoke.mjs"
|
|
||||||
},
|
|
||||||
"RuneStone_Terminal/src/TerminalPicker.svelte": {
|
|
||||||
"counts": {
|
|
||||||
"picker": 2,
|
|
||||||
"localPopup": 3
|
|
||||||
},
|
|
||||||
"design": "Shared searchable picker",
|
|
||||||
"check": "RuneStone_Terminal/scripts/terminal.smoke.mjs"
|
|
||||||
},
|
|
||||||
"RuneStone_Terminal/src/TerminalSettings.svelte": {
|
|
||||||
"counts": {
|
|
||||||
"action": 1,
|
|
||||||
"localPopup": 1
|
|
||||||
},
|
|
||||||
"design": "Synchronized shared action menu snapshot",
|
|
||||||
"check": "RuneStone_Terminal/scripts/terminal.smoke.mjs"
|
|
||||||
},
|
|
||||||
"RuneStone_Background_Slideshow/src/contracts.ts": {
|
|
||||||
"counts": {
|
|
||||||
"action": 1
|
|
||||||
},
|
|
||||||
"design": "API type declaration, no renderer",
|
|
||||||
"check": "pnpm check"
|
|
||||||
},
|
|
||||||
"RuneStone_Background_Slideshow/src/image-settings-ui.ts": {
|
|
||||||
"counts": {
|
|
||||||
"action": 1,
|
|
||||||
"nativeChoice": 1,
|
|
||||||
"picker": 2,
|
|
||||||
"localPopup": 3
|
|
||||||
},
|
|
||||||
"design": "Host action menus and shared searchable image picker; native image select only on older hosts",
|
|
||||||
"check": "RuneStone_Background_Slideshow/tests/settings.smoke.mjs"
|
|
||||||
},
|
|
||||||
"RuneStone_Background_Slideshow/src/settings.ts": {
|
|
||||||
"counts": {
|
|
||||||
"action": 1
|
|
||||||
},
|
|
||||||
"design": "Host action menus and shared searchable image picker; native image select only on older hosts",
|
|
||||||
"check": "RuneStone_Background_Slideshow/tests/settings.smoke.mjs"
|
|
||||||
},
|
|
||||||
"RuneStone_Local_Autocomplete/src/main.mjs": {
|
"RuneStone_Local_Autocomplete/src/main.mjs": {
|
||||||
"counts": {
|
"counts": {
|
||||||
"action": 1,
|
"action": 1,
|
||||||
@@ -321,12 +195,117 @@
|
|||||||
"design": "Shared action menu for interface language; settings retain ordinary controls",
|
"design": "Shared action menu for interface language; settings retain ordinary controls",
|
||||||
"check": "tests/smoke/settings/displayLanguage.smoke.mjs; tests/smoke/menus/consistency.smoke.mjs"
|
"check": "tests/smoke/settings/displayLanguage.smoke.mjs; tests/smoke/menus/consistency.smoke.mjs"
|
||||||
},
|
},
|
||||||
"RuneStone_Project_Management/src/workspace-default.ts": {
|
"RuneStone/src/lib/features/background/BackgroundSettings.svelte": {
|
||||||
"counts": {
|
"counts": {
|
||||||
"nativeChoice": 1
|
"action": 1,
|
||||||
|
"localPopup": 4
|
||||||
},
|
},
|
||||||
"design": "Uses the host menu. Keeps a native selector for older hosts.",
|
"design": "Shared action menu for the source, the order, the image position, and the image size. Theme choice stays on preview cards (UI-047).",
|
||||||
"check": "RuneStone_Project_Management/tests/october-cards.spec.ts with PM_HOST_URL; both themes, narrow layout, keyboard focus"
|
"check": "tests/smoke/features/background.smoke.mjs"
|
||||||
|
},
|
||||||
|
"RuneStone/src/lib/features/background/ImageEditor.svelte": {
|
||||||
|
"counts": {
|
||||||
|
"action": 1,
|
||||||
|
"picker": 2,
|
||||||
|
"localPopup": 2
|
||||||
|
},
|
||||||
|
"design": "Shared action menu for the fit and the position of one image. The image list is the shared searchable picker (rs-picker).",
|
||||||
|
"check": "tests/smoke/features/background.smoke.mjs"
|
||||||
|
},
|
||||||
|
"RuneStone/src/lib/features/terminal/TerminalDock.svelte": {
|
||||||
|
"counts": {
|
||||||
|
"action": 1
|
||||||
|
},
|
||||||
|
"design": "Shared action menu through showActionMenu",
|
||||||
|
"check": "tests/smoke/features/terminal.smoke.mjs"
|
||||||
|
},
|
||||||
|
"RuneStone/src/lib/features/terminal/TerminalPicker.svelte": {
|
||||||
|
"counts": {
|
||||||
|
"picker": 2,
|
||||||
|
"localPopup": 3
|
||||||
|
},
|
||||||
|
"design": "Shared searchable picker",
|
||||||
|
"check": "tests/smoke/features/terminal.smoke.mjs"
|
||||||
|
},
|
||||||
|
"RuneStone/src/lib/features/TerminalSettings.svelte": {
|
||||||
|
"counts": {
|
||||||
|
"action": 1,
|
||||||
|
"localPopup": 1
|
||||||
|
},
|
||||||
|
"design": "Shared action menu for the default profile in Settings → Terminal",
|
||||||
|
"check": "tests/smoke/features/terminal.smoke.mjs"
|
||||||
|
},
|
||||||
|
"RuneStone/src/lib/features/pm/ui/host.ts": {
|
||||||
|
"counts": {
|
||||||
|
"action": 2
|
||||||
|
},
|
||||||
|
"design": "The host layer of Project Management: showActionMenu of managedActionMenu.ts and the shared tooltip",
|
||||||
|
"check": "tests/smoke/features/pm.smoke.mjs; tests/smoke/find/pluginViews.smoke.mjs"
|
||||||
|
},
|
||||||
|
"RuneStone/src/lib/features/pm/ui/choices-ui.ts": {
|
||||||
|
"counts": {
|
||||||
|
"action": 1
|
||||||
|
},
|
||||||
|
"design": "Shared choice adapter: the native selects stay hidden for their values, and the host action menu shows the choices",
|
||||||
|
"check": "tests/smoke/features/pm.smoke.mjs; tests/smoke/find/pluginViews.smoke.mjs"
|
||||||
|
},
|
||||||
|
"RuneStone/src/lib/features/pm/ui/priority-ui.ts": {
|
||||||
|
"counts": {
|
||||||
|
"action": 1
|
||||||
|
},
|
||||||
|
"design": "Shared action menu for the card priority",
|
||||||
|
"check": "tests/smoke/features/pm.smoke.mjs; tests/smoke/find/pluginViews.smoke.mjs"
|
||||||
|
},
|
||||||
|
"RuneStone/src/lib/features/pm/ui/details-ui.ts": {
|
||||||
|
"counts": {
|
||||||
|
"picker": 1,
|
||||||
|
"localPopup": 4
|
||||||
|
},
|
||||||
|
"design": "Shared searchable picker classes (rs-picker) for the optional card details",
|
||||||
|
"check": "tests/smoke/features/pm.smoke.mjs; tests/smoke/find/pluginViews.smoke.mjs"
|
||||||
|
},
|
||||||
|
"RuneStone/src/lib/features/pm/ui/labels-ui.ts": {
|
||||||
|
"counts": {
|
||||||
|
"picker": 1,
|
||||||
|
"localPopup": 3
|
||||||
|
},
|
||||||
|
"design": "Shared searchable picker classes (rs-picker) for labels",
|
||||||
|
"check": "tests/smoke/features/pm.smoke.mjs; tests/smoke/find/pluginViews.smoke.mjs"
|
||||||
|
},
|
||||||
|
"RuneStone/src/lib/features/pm/ui/relations-ui.ts": {
|
||||||
|
"counts": {
|
||||||
|
"nativeChoice": 1,
|
||||||
|
"picker": 1,
|
||||||
|
"localPopup": 5
|
||||||
|
},
|
||||||
|
"design": "Shared relationship choice through the choice adapter and direct searchable picker rows",
|
||||||
|
"check": "tests/smoke/features/pm.smoke.mjs; tests/smoke/find/pluginViews.smoke.mjs"
|
||||||
|
},
|
||||||
|
"RuneStone/src/lib/features/pm/ui/tags.ts": {
|
||||||
|
"counts": {
|
||||||
|
"picker": 2,
|
||||||
|
"localPopup": 2
|
||||||
|
},
|
||||||
|
"design": "Shared searchable picker classes (rs-picker) for tag suggestions",
|
||||||
|
"check": "tests/smoke/features/pm.smoke.mjs; tests/smoke/find/pluginViews.smoke.mjs"
|
||||||
|
},
|
||||||
|
"RuneStone/src/lib/features/pm/ui/ui.ts": {
|
||||||
|
"counts": {
|
||||||
|
"action": 3,
|
||||||
|
"nativeChoice": 12,
|
||||||
|
"picker": 1,
|
||||||
|
"localPopup": 1
|
||||||
|
},
|
||||||
|
"design": "Board, list, card, scope, and background menus use the host action menu. Native selects stay hidden behind the shared choice adapter",
|
||||||
|
"check": "tests/smoke/features/pm.smoke.mjs; tests/smoke/find/pluginViews.smoke.mjs"
|
||||||
|
},
|
||||||
|
"RuneStone/src/lib/features/ProjectManagementSettings.svelte": {
|
||||||
|
"counts": {
|
||||||
|
"action": 1,
|
||||||
|
"localPopup": 2
|
||||||
|
},
|
||||||
|
"design": "Shared action menu for the priority levels and the default board in Settings → Project Management",
|
||||||
|
"check": "tests/smoke/features/pm.smoke.mjs; tests/smoke/find/pluginViews.smoke.mjs"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+25
-119
@@ -11,10 +11,8 @@ This reference gives the package contract, the build procedure, and the API for
|
|||||||
- [Versions and releases](#versions-and-releases)
|
- [Versions and releases](#versions-and-releases)
|
||||||
- [Plugin API](#plugin-api)
|
- [Plugin API](#plugin-api)
|
||||||
- [Use the SDK instead of native calls](#use-the-sdk-instead-of-native-calls)
|
- [Use the SDK instead of native calls](#use-the-sdk-instead-of-native-calls)
|
||||||
- [Terminal API](#terminal-api)
|
|
||||||
- [Folder grants](#folder-grants)
|
- [Folder grants](#folder-grants)
|
||||||
- [Plugin services](#plugin-services)
|
- [Plugin services](#plugin-services)
|
||||||
- [Background API](#background-api)
|
|
||||||
|
|
||||||
## Install the SDK
|
## Install the SDK
|
||||||
|
|
||||||
@@ -146,22 +144,21 @@ In user instructions, do not tell users to load JSON, select a build folder, ren
|
|||||||
Each example is specific to one plugin. Read the package scripts of a plugin before you build it.
|
Each example is specific to one plugin. Read the package scripts of a plugin before you build it.
|
||||||
For the RuneStone source setup, see [Run from source](development.md#run-from-source).
|
For the RuneStone source setup, see [Run from source](development.md#run-from-source).
|
||||||
|
|
||||||
### Example: Terminal
|
### Example: CSV Viewer
|
||||||
|
|
||||||
Source: [Terminal repository](https://git.knottywyvern.com/kwyvern/RuneStone_Terminal), its `package.json`, and its `scripts/build.mjs`.
|
Source: [CSV Viewer repository](https://git.knottywyvern.com/kwyvern/RuneStone_CSV_Viewer), its `package.json`, `plugin.json`, `scripts/build.mjs`, and `README.md`.
|
||||||
|
|
||||||
| Item | Value |
|
| Item | Value |
|
||||||
| --- | --- |
|
| --- | --- |
|
||||||
| Prerequisites | Node.js 24 and pnpm 10. Run `pnpm install --frozen-lockfile` in the Terminal folder. |
|
| Prerequisites | Node.js 24 or later and pnpm. Run `pnpm install --frozen-lockfile` in the CSV Viewer folder. Put the RuneStone source checkout beside it, in a folder with the name `RuneStone`. The source imports shared interface files from `../../RuneStone/src/lib/ui/`. |
|
||||||
| Working folder | The Terminal repository root |
|
| Working folder | The CSV Viewer repository root |
|
||||||
| Command | `pnpm build` |
|
| Command | `pnpm build` |
|
||||||
| Output | `releases/runestone.terminal-<version>.zip` in the Terminal folder |
|
| Output | `releases/runestone.csv-viewer-<version>.zip` in the CSV Viewer folder. `<version>` is the `version` of `plugin.json`, for example `0.1.3`. |
|
||||||
|
|
||||||
The build compiles the Svelte interface and its dependencies into `dist/` (`main.js`, `style.css`, `plugin.json`, and `README.md`). Then it makes the ZIP.
|
The build compiles `src/index.js` with esbuild into a readable `dist/main.js`. It copies `plugin.json` and `README.md` into `dist/` and writes `dist/build.json`.
|
||||||
The build stops when the versions in `package.json` and `plugin.json` are different.
|
Then it runs `scripts/packagePlugin.mjs` of the RuneStone checkout on `dist/`. Set `RUNESTONE_ROOT` to use another RuneStone checkout for this step.
|
||||||
To compile into `dist/` without a ZIP, run `node scripts/build.mjs --no-package`.
|
The build stops when the versions in `package.json` and `plugin.json` are different. It also stops when the release ZIP of the version exists. Set the next version in both files first.
|
||||||
RuneStone supplies the native terminal sessions. The plugin supplies the interface, shortcuts, and session controls.
|
To compile into `dist/` without a ZIP, run `pnpm compile`.
|
||||||
For use of the terminal, see the [Terminal guide](guides/terminal.md).
|
|
||||||
|
|
||||||
### Example: Workspace overview
|
### Example: Workspace overview
|
||||||
|
|
||||||
@@ -216,8 +213,8 @@ The SDK feature checks do this. Their error names each missing feature and tells
|
|||||||
```ts
|
```ts
|
||||||
import { hasFeature, requireFeature, requireFeatures } from "@runestone/plugin-sdk";
|
import { hasFeature, requireFeature, requireFeatures } from "@runestone/plugin-sdk";
|
||||||
|
|
||||||
requireFeatures(api, ["pty", "workspace.readBytes"]);
|
requireFeatures(api, ["files", "workspace.readBytes"]);
|
||||||
const pty = requireFeature(api, "pty");
|
const files = requireFeature(api, "files");
|
||||||
if (hasFeature(api, "settings.subscribe")) watchSettings();
|
if (hasFeature(api, "settings.subscribe")) watchSettings();
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -225,6 +222,8 @@ Without the SDK, examine the member directly: `if (!api.workspace.readBytes) thr
|
|||||||
|
|
||||||
Older hosts ignore unknown fields in objects that you pass to the host, such as a view `icon` or `launch` handler.
|
Older hosts ignore unknown fields in objects that you pass to the host, such as a view `icon` or `launch` handler.
|
||||||
|
|
||||||
|
The host has no `api.backgrounds`. Only the native Background feature shows images behind the interface, and plugins cannot set or read its frames.
|
||||||
|
|
||||||
### Activation and cleanup
|
### Activation and cleanup
|
||||||
|
|
||||||
- The host limits activation, each view mount, and each cleanup callback to five seconds. A timeout reports an error.
|
- The host limits activation, each view mount, and each cleanup callback to five seconds. A timeout reports an error.
|
||||||
@@ -232,7 +231,7 @@ Older hosts ignore unknown fields in objects that you pass to the host, such as
|
|||||||
- Plugins activate in every RuneStone window except browser windows.
|
- Plugins activate in every RuneStone window except browser windows.
|
||||||
- `api.signal` aborts when shutdown starts. Use it to stop pending work.
|
- `api.signal` aborts when shutdown starts. Use it to stop pending work.
|
||||||
- After shutdown starts, every API call throws an error. Ignore results that arrive after shutdown.
|
- After shutdown starts, every API call throws an error. Ignore results that arrive after shutdown.
|
||||||
- On disable, the host removes contributions, commands, views, and background frames first. Then it runs view cleanups and `onDispose` callbacks in reverse order.
|
- On disable, the host removes contributions, commands, and views first. Then it runs view cleanups and `onDispose` callbacks in reverse order.
|
||||||
- Remove timers, listeners, and other resources in cleanup. Closing a view and disabling the plugin share the same cleanup promise.
|
- Remove timers, listeners, and other resources in cleanup. Closing a view and disabling the plugin share the same cleanup promise.
|
||||||
- Plugins have full application access. The SDK does not isolate plugin JavaScript.
|
- Plugins have full application access. The SDK does not isolate plugin JavaScript.
|
||||||
|
|
||||||
@@ -264,10 +263,8 @@ 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`. |
|
| `assets.read(path)` | | Read a package file as a `Uint8Array`. |
|
||||||
| `ui.showActionMenu(options)` | yes | Open the shared RuneStone action menu. See [Menus](#menus). |
|
| `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). |
|
| `completion` | yes | Autocomplete fields and providers. See the [completion API](completion.md). |
|
||||||
| `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). |
|
| `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). |
|
| `services` | yes | Data that one plugin offers to other plugins. See [Plugin services](#plugin-services). |
|
||||||
| `backgrounds` | yes | Background image frames. See [Background API](#background-api). |
|
|
||||||
|
|
||||||
### Commands
|
### Commands
|
||||||
|
|
||||||
@@ -309,7 +306,6 @@ Closing an editor tab or disabling the plugin disposes the view.
|
|||||||
|
|
||||||
A `launch()` handler can select a default target and call `api.openView(id)`.
|
A `launch()` handler can select a default target and call `api.openView(id)`.
|
||||||
Explicit `api.openView` calls and restored tabs do not call `launch()`.
|
Explicit `api.openView` calls and restored tabs do not call `launch()`.
|
||||||
Example: [Project Management](https://git.knottywyvern.com/kwyvern/RuneStone_PM/src/branch/main/development.md#workspace-default-board) uses `launch()` to open the default board of the workspace.
|
|
||||||
|
|
||||||
### Navigation buttons
|
### Navigation buttons
|
||||||
|
|
||||||
@@ -385,10 +381,9 @@ Only one enabled plugin can own each key. The host removes contributions before
|
|||||||
|
|
||||||
| Key | Purpose | Owner |
|
| Key | Purpose | Owner |
|
||||||
| --- | --- | --- |
|
| --- | --- | --- |
|
||||||
| `terminal` | Mounts terminal controls in a host element. Returns update, command, and dispose functions. | Terminal 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 |
|
| `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.
|
Earlier hosts also had `api.pty` and a `terminal` key for the Terminal plugin. They are gone, because RuneStone now includes Terminal as a native feature.
|
||||||
|
|
||||||
### Theme tokens
|
### Theme tokens
|
||||||
|
|
||||||
@@ -423,49 +418,12 @@ The window sends a `runestone-theme-changed` event after each theme change. A pl
|
|||||||
## Use the SDK instead of native calls
|
## Use the SDK instead of native calls
|
||||||
|
|
||||||
Do not call `invoke`, `listen`, or other `@tauri-apps/api` functions from a plugin. Do not read the private files of other plugins.
|
Do not call `invoke`, `listen`, or other `@tauri-apps/api` functions from a plugin. Do not read the private files of other plugins.
|
||||||
Use the `api` members below. They check plugin shutdown, and they will stay available when a later host runs each plugin in its own isolated context.
|
Use the `api` members of the [API reference](#api-reference). They check plugin shutdown, and they will stay available when a later host runs each plugin in its own isolated context.
|
||||||
Make sure that an optional member exists before you use it. Keep the native call only as a fallback for older hosts.
|
Make sure that an optional member exists before you use it.
|
||||||
|
|
||||||
The host still accepts the native calls of released plugins. A later host can remove them.
|
The Local Autocomplete and CSV Viewer plugins make no native calls.
|
||||||
|
|
||||||
| Plugin | Current call | Purpose | Use instead |
|
|
||||||
| --- | --- | --- | --- |
|
|
||||||
| Terminal | `invoke("pty_open")`, `listen("pty-data")`, `listen("pty-exit")` | Start a shell and receive its output and exit code | `api.pty.open({ ..., onData, onExit })` |
|
|
||||||
| Terminal | `invoke("pty_write")`, `invoke("pty_resize")`, `invoke("pty_close")` | Send input, change the size, stop the shell | `write`, `resize`, and `close` of the session from `api.pty.open` |
|
|
||||||
| Terminal | `invoke("pty_profiles")` | List the installed shells | `api.pty.profiles()` |
|
|
||||||
| Terminal | `invoke("pty_new_window")` | Open a terminal window | `api.pty.openWindow()` |
|
|
||||||
| Terminal | `invoke("pty_dictation")` | Start Windows voice typing | `api.pty.dictation()` |
|
|
||||||
| Terminal | `invoke("workspace_read", { rel: ".runestone/tasks.json" })` | Read the task list of the workspace | `api.workspace.read(path)` |
|
|
||||||
| 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 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.
|
Their test scripts replace `window.__TAURI_INTERNALS__` with a test double. That is test code and does not go into the package.
|
||||||
|
|
||||||
## Terminal API
|
|
||||||
|
|
||||||
`api.pty` (`version: 1`) starts shells in pseudo terminals. The SDK types are `PtyApi` and `PtySession`.
|
|
||||||
|
|
||||||
| Member | Contract |
|
|
||||||
| --- | --- |
|
|
||||||
| `profiles()` | Returns the installed shells as `{ id, title, kind }`. |
|
|
||||||
| `open(options)` | Starts a shell and returns a session. See the options below. |
|
|
||||||
| `openWindow()` | Opens a terminal window for the workspace of the current window. |
|
|
||||||
| `dictation()` | Starts Windows voice typing. Focus the terminal first. Fails on other systems. |
|
|
||||||
|
|
||||||
| Option | Rule |
|
|
||||||
| --- | --- |
|
|
||||||
| `cwd` | Required. The workspace root of the window. The start fails when the workspace changed. |
|
|
||||||
| `cols`, `rows` | Required. Positive integers. |
|
|
||||||
| `profile` | A profile `id` from `profiles()`. Without it, the host uses the first installed shell. |
|
|
||||||
| `directory` | A start folder other than the workspace root. |
|
|
||||||
| `onData(data)` | Required. Receives the output as a `Uint8Array`. A UTF-8 character can be split between two calls. |
|
|
||||||
| `onExit(code)` | Receives the exit code, or `null`. |
|
|
||||||
|
|
||||||
A session has `id`, `write(text)`, `resize(cols, rows)`, and `close()`. `close()` stops the shell, and more calls return the same promise.
|
|
||||||
Output goes only to the session that started the shell, as raw bytes.
|
|
||||||
When the plugin stops, the host stops the output, runs the plugin cleanup, and then closes the sessions that are still open.
|
|
||||||
|
|
||||||
## Folder grants
|
## Folder grants
|
||||||
|
|
||||||
`api.files` (`version: 1`) gives access to folders outside the workspace. The user selects each folder. The plugin cannot supply a path.
|
`api.files` (`version: 1`) gives access to folders outside the workspace. The user selects each folder. The plugin cannot supply a path.
|
||||||
@@ -491,6 +449,13 @@ A sidecar holds valid JSON of at most 1 MiB. The host writes no other files in a
|
|||||||
|
|
||||||
Store the grant `id` in the plugin settings. Before you use a saved grant, look for it in `grants()`.
|
Store the grant `id` in the plugin settings. Before you use a saved grant, look for it in `grants()`.
|
||||||
|
|
||||||
|
### Example: the per-image settings of Background
|
||||||
|
|
||||||
|
The per-image settings file of the Background feature is `.runestone-backgrounds.json` in the image folder.
|
||||||
|
It is JSON with `"schema": 1` and an `images` object, at most 1 MiB. Each key is a file name. Each value can have `fit` (`cover`, `contain`, `auto`, or `blurred`), `position`, and `overlay`.
|
||||||
|
A plugin with a folder grant can read and write the same file with `files.readSidecar` and `files.writeSidecar`. `writeSidecar` compares the current file to `expected` (`null` when the file does not exist). It fails when the file changed, so external edits are not lost. The host checks only that the text is JSON. The plugin checks the schema.
|
||||||
|
Example: `src/lib/features/background/imageSettings.ts` reads the file and applies it.
|
||||||
|
|
||||||
## Plugin services
|
## Plugin services
|
||||||
|
|
||||||
`api.services` (`version: 1`) lets a plugin offer data to other plugins in the same window. The host passes the calls, so no plugin reads the private files of another plugin.
|
`api.services` (`version: 1`) lets a plugin offer data to other plugins in the same window. The host passes the calls, so no plugin reads the private files of another plugin.
|
||||||
@@ -505,62 +470,3 @@ A service name uses lowercase letters, digits, dots, and hyphens, and starts wit
|
|||||||
Each method call returns a promise. The host copies the arguments and the result with `structuredClone`. Use only data that this function can copy, not functions or DOM nodes.
|
Each method call returns a promise. The host copies the arguments and the result with `structuredClone`. Use only data that this function can copy, not functions or DOM nodes.
|
||||||
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.
|
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.
|
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.
|
||||||
|
|
||||||
## Background API
|
|
||||||
|
|
||||||
`api.backgrounds` (`version: 1`) lets a plugin show image frames behind the RuneStone interface.
|
|
||||||
Frames stay in the current window and do not change the saved appearance settings.
|
|
||||||
|
|
||||||
The folder methods are deprecated. They accept a folder path from the plugin. Use [folder grants](#folder-grants) in new code.
|
|
||||||
The host keeps them for released versions of Background Slideshow.
|
|
||||||
|
|
||||||
| Method | Optional | Contract |
|
|
||||||
| --- | --- | --- |
|
|
||||||
| `chooseFolder()` | | Deprecated. Use `files.chooseFolder()`. Open the folder picker. Returns an absolute path, or `null` on cancel. |
|
|
||||||
| `defaultFolder()` | yes | Deprecated. Use `files.pictureFolder("Backgrounds")`. Create `RuneStone Backgrounds` in the Pictures folder of the user and return its path. |
|
|
||||||
| `list(folder)` | | Deprecated. Use `files.list(grant)`. Return `{ name }` for PNG, JPEG, GIF, and WebP files directly in the folder. |
|
|
||||||
| `read(folder, name)` | | Deprecated. Use `files.readBytes(grant, name)`. Read one image as bytes, at most 50 MiB. |
|
|
||||||
| `readImageSettings(folder)` | yes | Deprecated. Use `files.readSidecar(grant, ".runestone-backgrounds.json")`. Read the per-image settings file text, or `null`. |
|
|
||||||
| `writeImageSettings(folder, contents, expected)` | yes | Deprecated. Use `files.writeSidecar`. Save the per-image settings file. See [Per-image settings](#per-image-settings). |
|
|
||||||
| `set(target, frame)` | | Show a frame for a target. `null` removes the frame of this plugin. |
|
|
||||||
| `get(target)` | | Return the active frame for a target, or `null`. |
|
|
||||||
| `subscribe(listener)` | | Receive the target name when a frame changes. Returns a cleanup function. |
|
|
||||||
|
|
||||||
Folders must be absolute paths without `..` segments.
|
|
||||||
The host rejects links, files with other extensions, files that are not raster images, and files over the size limit.
|
|
||||||
File access needs an enabled plugin in the current window. Pending reads fail after the plugin stops.
|
|
||||||
|
|
||||||
### Targets and frames
|
|
||||||
|
|
||||||
| Target | Use |
|
|
||||||
| --- | --- |
|
|
||||||
| `app` | The host shows this frame behind the app. |
|
|
||||||
| `pm-all` | Read by Project Management for all boards. |
|
|
||||||
| `pm-board:<board UUID>` | Read by Project Management for one board. |
|
|
||||||
|
|
||||||
| Frame field | Rule |
|
|
||||||
| --- | --- |
|
|
||||||
| `url` | Required `blob:` URL. |
|
|
||||||
| `blurredUrl` | Optional `blob:` URL for a blurred layer. Each target scales it separately from the foreground. |
|
|
||||||
| `overlay` | From -1 to 1. Negative values make the image lighter. Positive values make it darker. |
|
|
||||||
| `position` | `center`, `top left`, `top`, `top right`, `left`, `right`, `bottom left`, `bottom`, or `bottom right`. |
|
|
||||||
| `size` | `cover`, `contain`, or `auto`. |
|
|
||||||
| `previous` | Optional earlier frame with the same fields, without `previous` or `transitionMs`. |
|
|
||||||
| `transitionMs` | Optional fade time from 0 to 5,000 milliseconds. |
|
|
||||||
|
|
||||||
The host fades from `previous` to the new frame, unless the user turns on reduced motion.
|
|
||||||
The plugin owns all frame URLs. Keep them valid until a new frame replaces them or the plugin stops, then release them.
|
|
||||||
When more than one plugin sets a frame for a target, the most recent frame is shown. When it is removed, the host shows the earlier frame or the saved background.
|
|
||||||
Disable removes the frames and subscriptions of the plugin before cleanup.
|
|
||||||
To share saved configuration across windows, use the plugin settings API.
|
|
||||||
|
|
||||||
Example: [Background Slideshow](https://git.knottywyvern.com/kwyvern/RuneStone_BG_Slideshow/src/branch/main/docs/development.md#integration) sets frames from local image folders.
|
|
||||||
Example: [Project Management](https://git.knottywyvern.com/kwyvern/RuneStone_PM/src/branch/main/development.md#pm-0229-slideshow-backgrounds) reads frames for board backgrounds.
|
|
||||||
|
|
||||||
### Per-image settings
|
|
||||||
|
|
||||||
The per-image settings file is `.runestone-backgrounds.json` in the image folder.
|
|
||||||
It must be JSON with `"schema": 1` and an `images` object, at most 1 MiB.
|
|
||||||
`writeImageSettings` compares the current file to `expected` (`null` when the file does not exist). It fails when the file changed, so external edits are not lost.
|
|
||||||
`files.writeSidecar` does the same comparison on the same file, but the host checks only that the text is JSON. The plugin checks the schema.
|
|
||||||
Example: the [Background Slideshow image settings](https://git.knottywyvern.com/kwyvern/RuneStone_BG_Slideshow/src/branch/main/docs/development.md#per-image-settings) give the storage format and the rendering behavior.
|
|
||||||
|
|||||||
+19
-21
@@ -33,7 +33,7 @@ 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.
|
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.
|
`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).
|
Native features, such as Git, Terminal, and Project Management, 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 and document types share the tab model of plugin views. A view pattern in the catalog gives a feature many editor views, for example one for each board (`board-<hex>`). A tab transfer of such a view works before the feature loads. The file tree identifies the files of a feature document type, such as PDF files, without the feature code. A launch rule (`src/lib/features/launch.ts`) can start a feature at once: Background starts when a folder or an image is selected. Browser windows start only the features with a browser window rule, which is Background. See [Native features](development.md#native-features).
|
||||||
`features_legacy` (`src-tauri/src/features.rs`) reads the catalog row and the kept `plugin-data/<id>/settings.json` of an old package. It accepts only the IDs of native features and changes no file.
|
`features_legacy` (`src-tauri/src/features.rs`) reads the catalog row and the kept `plugin-data/<id>/settings.json` of an old package. It accepts only the IDs of native features and changes no file.
|
||||||
|
|
||||||
### Scans
|
### Scans
|
||||||
@@ -108,7 +108,7 @@ The uninstall dialog puts focus on **Cancel**. Escape cancels.
|
|||||||
|
|
||||||
`plugins_load` returns the entry module and records a lease for the window. `plugins_release` ends the lease and records any cleanup error.
|
`plugins_load` returns the entry module and records a lease for the window. `plugins_release` ends the lease and records any cleanup error.
|
||||||
Updates and removals wait for all leases to end. A recorded cleanup error blocks enable, update, and removal until RuneStone restarts.
|
Updates and removals wait for all leases to end. A recorded cleanup error blocks enable, update, and removal until RuneStone restarts.
|
||||||
Native services for plugins, such as the background file commands, need a lease for the calling window.
|
Native services for plugins, such as the folder grant commands (`folders_*`), need a lease for the calling window.
|
||||||
|
|
||||||
## Gitea downloads
|
## Gitea downloads
|
||||||
|
|
||||||
@@ -159,12 +159,12 @@ The policy stops a script that comes in through rendered content, for example a
|
|||||||
| Directive | Sources | Reason |
|
| Directive | Sources | Reason |
|
||||||
| --- | --- | --- |
|
| --- | --- | --- |
|
||||||
| `default-src` | `'self'` | All other types come only from the app. |
|
| `default-src` | `'self'` | All other types come only from the app. |
|
||||||
| `script-src` | `'self' blob: 'wasm-unsafe-eval'` | `blob:`: plugin entry modules, which `external.ts` loads from Blob URLs. `'wasm-unsafe-eval'`: the PDF Viewer decodes JPEG 2000 and JBIG2 images and color profiles with WebAssembly in its worker. It does not permit `eval`. |
|
| `script-src` | `'self' blob: 'wasm-unsafe-eval'` | `blob:`: plugin entry modules, which `external.ts` loads from Blob URLs. `'wasm-unsafe-eval'`: PDF.js in the PDF Viewer feature decodes JPEG 2000 and JBIG2 images and compiles PostScript functions with WebAssembly. Its worker is a file of the app and gets no policy, so this source applies only to PDF.js code on the page. It does not permit `eval`. |
|
||||||
| `style-src` | `'self' 'unsafe-inline'` | Svelte `style` attributes, the `style` attribute in `src/app.html`, Mermaid SVG styles, and the `<style>` elements of CodeMirror, the Vite dev server, and plugins (Terminal, CSV Viewer, PDF Viewer, Background Slideshow). |
|
| `style-src` | `'self' 'unsafe-inline'` | Svelte `style` attributes, the `style` attribute in `src/app.html`, Mermaid SVG styles, and the `<style>` elements of CodeMirror, xterm in the Terminal feature, the Vite dev server, and plugins (CSV Viewer). |
|
||||||
| `img-src` | `'self' data: blob: https: http:` | `data:`: workspace images, browser frames, tab and site icons, and icons in CSS. `blob:`: background images. `https:` and `http:`: remote images in Markdown previews. |
|
| `img-src` | `'self' data: blob: https: http:` | `data:`: workspace images, browser frames, tab and site icons, and icons in CSS. `blob:`: background images. `https:` and `http:`: remote images in Markdown previews. |
|
||||||
| `font-src` | `'self' data:` | `'self'`: fonts that the app serves. The app serves no font now. `data:`: fonts that the PDF Viewer embeds. |
|
| `font-src` | `'self' data:` | `'self'`: fonts that the app serves. The app serves no font now. `data:`: PDF.js can load the embedded fonts of a PDF from data addresses. |
|
||||||
| `connect-src` | `'self' ipc: http://ipc.localhost blob:` | `ipc:` and `http://ipc.localhost`: Tauri commands. `blob:`: the Background Slideshow worker reads its image from a Blob URL. |
|
| `connect-src` | `'self' ipc: http://ipc.localhost blob:` | `ipc:` and `http://ipc.localhost`: Tauri commands. `blob:`: the blur worker of the Background feature reads its image from a Blob URL. |
|
||||||
| `worker-src` | `'self' blob:` | `'self'`: workers that the app serves. The app starts no worker now. `blob:`: the PDF Viewer and Background Slideshow workers. |
|
| `worker-src` | `'self' blob:` | `'self'`: workers that the app serves, such as the PDF.js worker of each PDF tab. `blob:`: the blur worker of the Background feature. |
|
||||||
| `object-src` | `'none'` | RuneStone uses no plugins of the web view. |
|
| `object-src` | `'none'` | RuneStone uses no plugins of the web view. |
|
||||||
| `base-uri` | `'self'` | |
|
| `base-uri` | `'self'` | |
|
||||||
| `form-action` | `'none'` | No form sends data to an address. |
|
| `form-action` | `'none'` | No form sends data to an address. |
|
||||||
@@ -186,18 +186,19 @@ Workers that the app loads from its own files get no policy. Workers from Blob U
|
|||||||
| Capability | Windows | Plugins | Commands |
|
| Capability | Windows | Plugins | Commands |
|
||||||
| --- | --- | --- | --- |
|
| --- | --- | --- | --- |
|
||||||
| `default.json` | `main`, `workspace-*`, `terminal-*` | All enabled plugins | All app commands |
|
| `default.json` | `main`, `workspace-*`, `terminal-*` | All enabled plugins | All app commands |
|
||||||
| `settings.json` | `settings-main`, `settings-workspace-*` | All enabled plugins | Settings, plugins, backgrounds, completion, browser |
|
| `settings.json` | `settings-main`, `settings-workspace-*` | All enabled plugins | Settings, plugins, the Background folder, folder grants, completion, browser, `pty_profiles`, and `pty_running` |
|
||||||
| `browser.json` | `browser-*` | Only the built-in browser (`builtInModules` in `src/lib/plugins/external.ts`) | Browser, `plugins_snapshot`, settings, spelling, and window controls |
|
| `browser.json` | `browser-*` | Only the built-in browser (`builtInModules` in `src/lib/plugins/external.ts`) | Browser, `plugins_snapshot`, settings, spelling, window controls, and the read commands of the Background folder (`background_folder`, `background_list`, `background_read`, `background_read_sidecar`) |
|
||||||
|
|
||||||
A browser window loads no installed plugin, so its capability has no workspace, file, Git, terminal, or plugin package commands. `tests/unit/plugins/windowCapabilities.spec.ts` and `tests/smoke/browser/window.smoke.mjs` check this.
|
A browser window loads no installed plugin, so its capability has no workspace, file, Git, terminal, or plugin package commands. The Background feature runs there to show the background behind a blank tab, so the window can read the Background folder. `tests/unit/plugins/windowCapabilities.spec.ts` and `tests/smoke/browser/window.smoke.mjs` check this.
|
||||||
|
|
||||||
The other windows load every enabled plugin. A smaller command set for them would limit only the app code, not the plugins. That split belongs to the plugin isolation work. Findings for that work:
|
The other windows load every enabled plugin. A smaller command set for them would limit only the app code, not the plugins. That split belongs to the plugin isolation work. Findings for that work:
|
||||||
|
|
||||||
- Terminal windows use the plugin host commands, `pty_*` through the Terminal plugin, and `core:window:allow-destroy`. Other plugins in the same window expect the full host API.
|
- Terminal windows use the `pty_*` commands of the Terminal feature, the plugin host commands, and `core:window:allow-destroy`. Other plugins in the same window expect the full host API.
|
||||||
- Settings windows use no `workspace_*`, `git_*`, or `pty_*` commands, but plugin settings views run there.
|
- Settings windows use no `workspace_*` or `git_*` commands, but plugin settings views run there. Of the `pty_*` commands, they use only `pty_profiles` for Settings → Terminal and `pty_running` before Terminal goes off.
|
||||||
- Commands that need a workspace (`workspace_*`, `git_*`, `pty_open`, `pty_new_window`) fail in a window without a bound workspace.
|
- Commands that need a workspace (`workspace_*`, `git_*`, `pty_open`, `pty_new_window`) fail in a window without a bound workspace.
|
||||||
- `pty_write`, `pty_resize`, and `pty_close` do not check the window that opened the terminal.
|
- `pty_write`, `pty_resize`, and `pty_close` act only on the sessions of the calling window. A session of another window counts as a missing session.
|
||||||
- `backgrounds_*` need a plugin lease of the calling window.
|
- `pty_open` needs an output channel and a page ID. The first open of a new page in a window, after a reload, closes the sessions of the earlier page. The host refuses a late open from an old page.
|
||||||
|
- `folders_*` need a plugin lease of the calling window. The `background_*` commands of the Background feature need no lease. They take no path: the host keeps the folder that the folder dialog gave.
|
||||||
- `browser_request` needs the session token that `browser_connect` gives the window. A plugin lease does not replace it.
|
- `browser_request` needs the session token that `browser_connect` gives the window. A plugin lease does not replace it.
|
||||||
- A new command for plugins goes in `default.json` and, if settings views need it, in `settings.json`. Add it to `browser.json` only when the built-in browser needs it.
|
- A new command for plugins goes in `default.json` and, if settings views need it, in `settings.json`. Add it to `browser.json` only when the built-in browser needs it.
|
||||||
|
|
||||||
@@ -207,9 +208,9 @@ The other windows load every enabled plugin. A smaller command set for them woul
|
|||||||
| --- | --- |
|
| --- | --- |
|
||||||
| `src-tauri/src/plugins.rs` | Package checks, discovery, installation, updates, persistence, removal, leases, settings, and assets |
|
| `src-tauri/src/plugins.rs` | Package checks, discovery, installation, updates, persistence, removal, leases, settings, and assets |
|
||||||
| `src-tauri/src/plugin_sources.rs` | Gitea link parsing and release downloads |
|
| `src-tauri/src/plugin_sources.rs` | Gitea link parsing and release downloads |
|
||||||
| `src-tauri/src/backgrounds.rs` | Background folder and image commands. Deprecated for plugins: use folder grants |
|
| `src-tauri/src/backgrounds.rs` | The image folder of the native Background feature. Plugins use folder grants |
|
||||||
| `src-tauri/src/folders.rs` | Folder grants for `api.files`: the picker, stored grants, listing, reads, and settings files beside the images |
|
| `src-tauri/src/folders.rs` | Folder grants for `api.files`: the picker, stored grants, listing, reads, and settings files beside the images |
|
||||||
| `src-tauri/src/pty.rs` | Terminal sessions for `api.pty`. A session with an IPC channel gets raw output bytes; a session without one gets the older window events |
|
| `src-tauri/src/pty.rs` | The shell sessions of the Terminal feature. Output goes as raw bytes through the channel of `pty_open`, in messages of up to 64 KiB or 8 ms. `pty_running` counts the sessions of all windows |
|
||||||
| `src/lib/plugins/sdk.ts` | The public package API types |
|
| `src/lib/plugins/sdk.ts` | The public package API types |
|
||||||
| `src/lib/plugins/externalSession.ts` | Activation, API checks, contributions, mounts, and shutdown |
|
| `src/lib/plugins/externalSession.ts` | Activation, API checks, contributions, mounts, and shutdown |
|
||||||
| `src/lib/plugins/external.ts` | Native state sync, module loading, scans, views, tabs, and document types |
|
| `src/lib/plugins/external.ts` | Native state sync, module loading, scans, views, tabs, and document types |
|
||||||
@@ -218,8 +219,8 @@ The other windows load every enabled plugin. A smaller command set for them woul
|
|||||||
| `src/lib/plugins/PluginManager.svelte` | Settings → Plug-ins: review, switches, Gitea form, and uninstall dialog |
|
| `src/lib/plugins/PluginManager.svelte` | Settings → Plug-ins: review, switches, Gitea form, and uninstall dialog |
|
||||||
| `src/lib/plugins/PluginSettings.svelte` | Plugin configuration pages in Settings |
|
| `src/lib/plugins/PluginSettings.svelte` | Plugin configuration pages in Settings |
|
||||||
| `src/lib/plugins/PluginTools.svelte` / `PluginEditor.svelte` | Dialog views and editor views |
|
| `src/lib/plugins/PluginTools.svelte` / `PluginEditor.svelte` | Dialog views and editor views |
|
||||||
| `src/lib/plugins/backgrounds.ts` | Background frames |
|
| `src/lib/plugins/backgrounds.ts` | The background frames of one window. The Background feature sets them, and Project Management reads the board targets. Plugins have no access. |
|
||||||
| `src/lib/plugins/nativeServices.ts` | The host side of `api.pty` and `api.files`. It binds the plugin ID; the plugin never sends it |
|
| `src/lib/plugins/nativeServices.ts` | The host side of `api.files`. It binds the plugin ID. The plugin never sends it |
|
||||||
| `src/lib/plugins/services.ts` | `api.services`: services that one plugin offers to another in the same window |
|
| `src/lib/plugins/services.ts` | `api.services`: services that one plugin offers to another in the same window |
|
||||||
| `src/lib/completion/` | The [completion API](completion.md) |
|
| `src/lib/completion/` | The [completion API](completion.md) |
|
||||||
| `scripts/packagePlugin.mjs` | The packager for plugin authors |
|
| `scripts/packagePlugin.mjs` | The packager for plugin authors |
|
||||||
@@ -229,9 +230,6 @@ The other windows load every enabled plugin. A smaller command set for them woul
|
|||||||
Run these commands from the RuneStone repository root.
|
Run these commands from the RuneStone repository root.
|
||||||
For the general checks, see [Checks](development.md#checks). For the browser setup, see [Browser smoke tests](development.md#browser-smoke-tests).
|
For the general checks, see [Checks](development.md#checks). For the browser setup, see [Browser smoke tests](development.md#browser-smoke-tests).
|
||||||
|
|
||||||
The feature smoke tests read the compiled Terminal plugin from `../RuneStone_Terminal/dist/`.
|
|
||||||
To make it without a release ZIP, run `node scripts/build.mjs --no-package` in the Terminal folder. Set `RUNESTONE_TERMINAL_DIST` to use another folder.
|
|
||||||
|
|
||||||
Unit tests:
|
Unit tests:
|
||||||
|
|
||||||
```powershell
|
```powershell
|
||||||
|
|||||||
+7
-7
@@ -2,15 +2,15 @@
|
|||||||
|
|
||||||
[RuneStone](../README.md) · [User guide](user-guide.md)
|
[RuneStone](../README.md) · [User guide](user-guide.md)
|
||||||
|
|
||||||
This guide explains how to install, enable, update, and remove optional plugins such as Terminal, PDF Viewer, and CSV Viewer.
|
This guide explains how to install, enable, update, and remove optional plugins such as CSV Viewer and Local Autocomplete.
|
||||||
|
|
||||||
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).
|
Manage all plugins in **Settings → Plug-ins**. The built-in browser, table formulas, Git, Background, Terminal, PDF Viewer, and Project Management are not plugins. To turn Git, Background, Terminal, PDF Viewer, or Project Management 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.
|
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.
|
||||||
|
|
||||||
## Install a plugin
|
## Install a plugin
|
||||||
|
|
||||||
Get the release ZIP of the plugin, such as `runestone.terminal-<version>.zip`. Do not extract it.
|
Get the release ZIP of the plugin, such as `runestone.csv-viewer-<version>.zip`. Do not extract it.
|
||||||
|
|
||||||
1. Open **Settings → Plug-ins**.
|
1. Open **Settings → Plug-ins**.
|
||||||
2. Choose **Install plugin ZIP**.
|
2. Choose **Install plugin ZIP**.
|
||||||
@@ -75,11 +75,7 @@ RuneStone uses the token for this request only and does not save it.
|
|||||||
|
|
||||||
| Plugin | Guide |
|
| Plugin | Guide |
|
||||||
| --- | --- |
|
| --- | --- |
|
||||||
| Terminal | [Terminal guide](guides/terminal.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) |
|
| Local Autocomplete | [Local Autocomplete trial guide](https://git.knottywyvern.com/kwyvern/RuneStone_LocalModel/src/branch/main/docs/trial-guide.md) |
|
||||||
| PDF Viewer | [PDF Viewer README](https://git.knottywyvern.com/kwyvern/RuneStone_PDFViewer/src/branch/master/README.md) |
|
|
||||||
| CSV Viewer | [CSV Viewer README](https://git.knottywyvern.com/kwyvern/RuneStone_CSV_Viewer/src/branch/main/README.md) |
|
| CSV Viewer | [CSV Viewer README](https://git.knottywyvern.com/kwyvern/RuneStone_CSV_Viewer/src/branch/main/README.md) |
|
||||||
|
|
||||||
## Plugin help
|
## Plugin help
|
||||||
@@ -95,6 +91,10 @@ RuneStone uses the token for this request only and does not save it.
|
|||||||
| A Gitea release has no usable package | Check the release tag. Ask the publisher for a release with one attached plugin ZIP. |
|
| 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 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 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 Background Slideshow plugin shows in the list | Uninstall it. RuneStone includes Background, and the first start after the update took the folder and the settings of the plugin. See [Show a background](guides/themes.md#show-a-background). |
|
||||||
|
| An old Terminal plugin shows in the list | RuneStone includes Terminal. The plugin stays inactive and shows **Included with RuneStone**. Uninstall it. The first start after the update kept the plugin state and its terminal settings. See the [Terminal guide](guides/terminal.md). |
|
||||||
|
| An old PDF Viewer plugin shows in the list | RuneStone includes PDF Viewer. The plugin stays inactive and shows **Included with RuneStone**. Uninstall it. The first start after the update kept the plugin state. See [Read PDF files](user-guide.md#read-pdf-files). |
|
||||||
|
| An old Project Management plugin shows in the list | RuneStone includes Project Management. The plugin stays inactive and shows **Included with RuneStone**. Uninstall it. The first start after the update kept the plugin state and its priority levels. Your boards in `.runestone/pm/` stay. If the workspace has boards in old visible notes, Project Management offers a migration. See [Move old Project Management notes](guides/project-management.md#move-old-project-management-notes). |
|
||||||
| 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). |
|
| 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.
|
To see the installed files of a plugin, choose **Show files** beside it. **Open plugins folder** opens the folder for all plugins.
|
||||||
|
|||||||
+3
-1
@@ -27,7 +27,7 @@ Correct a wrong color in the theme data or in the derivation rule. Do not add lo
|
|||||||
| --- | --- | --- |
|
| --- | --- | --- |
|
||||||
| Theme identity | `--rs-accent`, `--rs-accent-2` | Keep the characteristic hues of the reference at their strength. |
|
| Theme identity | `--rs-accent`, `--rs-accent-2` | Keep the characteristic hues of the reference at their strength. |
|
||||||
| Status | `--rs-error`, `--rs-warn`, `--rs-warn-hot`, `--rs-ok` | Use clear, assertive colors. Pair color with a shape or text. |
|
| Status | `--rs-error`, `--rs-warn`, `--rs-warn-hot`, `--rs-ok` | Use clear, assertive colors. Pair color with a shape or text. |
|
||||||
| Priority (Project Management) | `--pm-priority-color` in the plugin `src/style.css` | Full saturation and value, with opaque symbols and readable text. |
|
| Priority (Project Management) | `--pm-priority-color` in `src/lib/features/pm/ui/style.css` | Full saturation and value, with opaque symbols and readable text. |
|
||||||
| Links and actions | `--rs-link` (from `--rs-accent` unless the theme sets it) | Keep actionable text distinct and readable on its actual surface. |
|
| Links and actions | `--rs-link` (from `--rs-accent` unless the theme sets it) | Keep actionable text distinct and readable on its actual surface. |
|
||||||
| Text on an accent fill | `--rs-on-accent` (black or white, whichever is more readable) | Readable text and icons on accent buttons and badges. |
|
| Text on an accent fill | `--rs-on-accent` (black or white, whichever is more readable) | Readable text and icons on accent buttons and badges. |
|
||||||
| Focus | `--rs-focus` (from `--rs-accent` unless the theme sets it) | A visible outline on every surface. |
|
| Focus | `--rs-focus` (from `--rs-accent` unless the theme sets it) | A visible outline on every surface. |
|
||||||
@@ -38,6 +38,8 @@ Correct a wrong color in the theme data or in the derivation rule. Do not add lo
|
|||||||
| Surfaces and dividers | `--rs-bg`, `--rs-bg-elevated`, `--rs-bg-active`, `--rs-border`, `--rs-line-highlight`, `--rs-scrim`, `--rs-image-*` tints | Support the content. Choose their strength by function. |
|
| Surfaces and dividers | `--rs-bg`, `--rs-bg-elevated`, `--rs-bg-active`, `--rs-border`, `--rs-line-highlight`, `--rs-scrim`, `--rs-image-*` tints | Support the content. Choose their strength by function. |
|
||||||
| Disabled states | Role tokens of the control | Keep labels readable. Do not apply disabled opacity to enabled content. |
|
| Disabled states | Role tokens of the control | Keep labels readable. Do not apply disabled opacity to enabled content. |
|
||||||
|
|
||||||
|
The Terminal feature uses these tokens directly (`src/lib/features/terminal/theme.ts`). Text is `--rs-text`, the cursor is `--rs-accent` on `--rs-bg`, and the selection is `--rs-selection` with at most 65% alpha. The 16 ANSI colors are the `--rs-ansi-*` tokens. The terminal reads them again after each theme change.
|
||||||
|
|
||||||
Do not fade a whole badge, row, or container when only its background needs transparency.
|
Do not fade a whole badge, row, or container when only its background needs transparency.
|
||||||
Plugins use the same tokens. [Theme tokens](plugin-development.md#theme-tokens) lists them for plugin authors.
|
Plugins use the same tokens. [Theme tokens](plugin-development.md#theme-tokens) lists them for plugin authors.
|
||||||
|
|
||||||
|
|||||||
+22
-14
@@ -148,12 +148,12 @@ Decisions: [UI-002](design-decisions.md#ui-002--share-the-requested-dropdown-des
|
|||||||
|
|
||||||
- The main header holds navigation, document tabs, Save, the outline toggle, and window controls. The other tools are in the left ribbon, so the tabs keep their room. A detached tab window has no ribbon, so its header keeps those tools.
|
- The main header holds navigation, document tabs, Save, the outline toggle, and window controls. The other tools are in the left ribbon, so the tabs keep their room. A detached tab window has no ribbon, so its header keeps those tools.
|
||||||
- A bar at the bottom of the side pane holds the workspace switcher, Help, and Settings, as in Obsidian. The switcher names the workspace and opens the workspace list above it.
|
- A bar at the bottom of the side pane holds the workspace switcher, Help, and Settings, as in Obsidian. The switcher names the workspace and opens the workspace list above it.
|
||||||
- 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.
|
- The left ribbon is always present. It holds the tools, then a line, then the plugin view shortcuts. The tools are New browser tab, Terminal, Project Management, Plug-in views, and Commands. A tool of an off feature does not show. 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.
|
- 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.
|
- 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, 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.
|
- 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.
|
- 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.
|
- The built-in browser and Project Management open from their own ribbon buttons. The Project Management button is active while a board tab or All tasks is the active tab. Plug-in views lists only plugin 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.
|
- 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.
|
||||||
- The main window keeps an empty New tab after its last tab closes. A secondary window closes with its last tab. The unsaved-edit and active-terminal confirmations still apply, and Cancel keeps the tab open.
|
- The main window keeps an empty New tab after its last tab closes. A secondary window closes with its last tab. The unsaved-edit and active-terminal confirmations still apply, and Cancel keeps the tab open.
|
||||||
- Sidebar widths and visibility persist across window sessions. A different editor does not restore a hidden outline.
|
- Sidebar widths and visibility persist across window sessions. A different editor does not restore a hidden outline.
|
||||||
@@ -173,18 +173,20 @@ Decisions: [UI-004](design-decisions.md#ui-004--detached-tab-work-area), [UI-039
|
|||||||
- Controls wrap at narrow widths, and the content area scrolls. Long navigation must leave room for the selected page.
|
- 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.
|
- 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.
|
- **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.
|
- A feature that is off shows no controls: no navigation button, ribbon button, command, or tab. A settings section of an off feature shows one line that names Settings → Features.
|
||||||
|
- **Terminal** is a Settings page with the `terminal` icon, after Plug-ins and Browser. It shows only while Terminal is on. **Terminal settings** in the profile menu of the terminal panel opens it. No dialog of the panel holds terminal settings.
|
||||||
|
- **Project Management** is a Settings page with the `kanban` icon, after Terminal. It shows only while Project Management is on. It holds **Priority levels** and **Default board**, with pickers on the shared action menu. **More actions** → **Project Management settings** on a board shows the same component in a popup.
|
||||||
- The transparency slider covers 0% to 100% and uses the accent and surface tokens of the current theme.
|
- 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.
|
- 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.
|
- **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.
|
- 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), [UI-055](design-decisions.md#ui-055--settings--features-and-native-git).
|
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), [UI-057](design-decisions.md#ui-057--background-replaces-background-image-and-background-slideshow), [UI-058](design-decisions.md#ui-058--settings--terminal-and-theme-colors-in-the-terminal), [UI-060](design-decisions.md#ui-060--native-project-management).
|
||||||
|
|
||||||
## Typography and tables
|
## Typography and tables
|
||||||
|
|
||||||
- The interface uses `--rs-font-ui`. Prose uses `--rs-font-prose`. Headings use `--rs-font-heading`.
|
- The interface uses `--rs-font-ui`. Prose uses `--rs-font-prose`. Headings use `--rs-font-heading`.
|
||||||
- Source and Terminal share `--rs-font-mono` and `--rs-code-font-weight` (default 300). The monospace stack starts with Cascadia Mono, then Cascadia Code, JetBrains Mono, Fira Code, and Consolas. Terminal font size is a separate setting.
|
- Source and Terminal share `--rs-font-mono` and `--rs-code-font-weight` (default 300). The monospace stack starts with Cascadia Mono, then Cascadia Code, JetBrains Mono, Fira Code, and Consolas. Terminal font size is a separate setting in Settings → Terminal.
|
||||||
- Document headings use space between sections, not separator lines. Heading fold controls use the shared chevron and take keyboard focus.
|
- Document headings use space between sections, not separator lines. Heading fold controls use the shared chevron and take keyboard focus.
|
||||||
- Tables use shared cell padding and line height. Entering a cell does not change its row height.
|
- Tables use shared cell padding and line height. Entering a cell does not change its row height.
|
||||||
- A table row needs an unescaped pipe. Write and Read use the same row rule. A paragraph after a table stays a paragraph when the separator line is removed.
|
- A table row needs an unescaped pipe. Write and Read use the same row rule. A paragraph after a table stays a paragraph when the separator line is removed.
|
||||||
@@ -194,6 +196,8 @@ Decisions: [UI-005](design-decisions.md#ui-005--heading-spacing).
|
|||||||
|
|
||||||
## Themes and background images
|
## Themes and background images
|
||||||
|
|
||||||
|
Background images come from the native Background feature (`src/lib/features/background/`). Appearance → Background holds its settings: the source (a folder, one image, or none), the layout, the per-image editor, and the targets.
|
||||||
|
|
||||||
### Palettes
|
### Palettes
|
||||||
|
|
||||||
- Color choices obey [Functional color](ui-color.md).
|
- Color choices obey [Functional color](ui-color.md).
|
||||||
@@ -221,15 +225,16 @@ Decisions: [UI-009](design-decisions.md#ui-009--character-theme-appearances), [U
|
|||||||
- Code blocks in Write and Read use `--rs-code-block-bg`.
|
- Code blocks in Write and Read use `--rs-code-block-bg`.
|
||||||
- New-tab buttons use `--rs-image-control-bg` and `--rs-image-control-hover-bg`. Their tint keeps labels readable while the image stays visible. The new-tab screen shows only its action buttons, with icons, labels, and shortcuts.
|
- New-tab buttons use `--rs-image-control-bg` and `--rs-image-control-hover-bg`. Their tint keeps labels readable while the image stays visible. The new-tab screen shows only its action buttons, with icons, labels, and shortcuts.
|
||||||
- Headers and dialogs keep their own surfaces.
|
- Headers and dialogs keep their own surfaces.
|
||||||
- The app work area and Project Management keep separate images and settings in every theme. An image can be up to 50 MiB. Image bytes stay in IndexedDB, and settings keep a small reference.
|
- The app work area and Project Management keep separate images and settings in every theme. The one image of Background can be up to 50 MiB. Its bytes stay in IndexedDB, and the appearance settings keep a small reference.
|
||||||
- Each image has a size, nine alignment positions, and an overlay from -100% (darker) to 100% (lighter), set with a slider or a typed value.
|
- The folder and the one image each have a size, nine alignment positions, and an overlay from -100% (lighter) to 100% (darker), set with a slider or a typed value.
|
||||||
|
- Without a background frame, every surface and menu is opaque. With Background off, no image shows.
|
||||||
|
|
||||||
Decisions: [UI-010](design-decisions.md#ui-010--background-surface-visibility), [UI-011](design-decisions.md#ui-011--backgrounds-across-the-work-area), [UI-016](design-decisions.md#ui-016--translucent-code-blocks).
|
Decisions: [UI-010](design-decisions.md#ui-010--background-surface-visibility), [UI-011](design-decisions.md#ui-011--backgrounds-across-the-work-area), [UI-016](design-decisions.md#ui-016--translucent-code-blocks).
|
||||||
|
|
||||||
### Project Management surfaces
|
### Project Management surfaces
|
||||||
|
|
||||||
- Without its own image, Project Management shows the host image through a transparent root. A saved or temporary board image keeps its own area.
|
- Without its own image, Project Management shows the host image through a transparent root. A saved or temporary board image keeps its own area.
|
||||||
- The host gives `--rs-workarea-plugin-bg` and `--rs-workarea-surface-opacity` for saved images and slideshow frames.
|
- The host gives `--rs-workarea-plugin-bg` and `--rs-workarea-surface-opacity` for saved board images and slideshow frames.
|
||||||
- With an image, lists, cards, card details, and search fields share the 82% tint. Gantt and calendar views use one tinted panel, and their date cells show the image.
|
- With an image, lists, cards, card details, and search fields share the 82% tint. Gantt and calendar views use one tinted panel, and their date cells show the image.
|
||||||
- Selected cards use the shared selection treatment. Nested surfaces keep their own tint.
|
- Selected cards use the shared selection treatment. Nested surfaces keep their own tint.
|
||||||
- Card detail buttons have a transparent resting background. Hover, pressed, and focus states stay visible.
|
- Card detail buttons have a transparent resting background. Hover, pressed, and focus states stay visible.
|
||||||
@@ -238,13 +243,15 @@ Decisions: [UI-014](design-decisions.md#ui-014--readable-project-management-surf
|
|||||||
|
|
||||||
### Slideshow
|
### Slideshow
|
||||||
|
|
||||||
- A slideshow frame overrides the saved board image while it is active. A temporary board frame comes before the all-board frame. Removal restores the saved image.
|
- A folder of the Background feature is a slideshow. Its frame overrides the saved board image while it is active. A temporary board frame comes before the all-board frame. Removal restores the saved image.
|
||||||
- When the app and Project Management show the same frame, the host draws it once across both sidebars and the board. Distinct board frames keep their own area.
|
- When the app and Project Management show the same frame, the host draws it once across both sidebars and the board. Distinct board frames keep their own area.
|
||||||
- Images fade over two seconds. Reduced motion removes the fade. Short intervals and manual Next can interrupt it.
|
- Images fade over two seconds. Reduced motion removes the fade. Short intervals and manual Next can interrupt it.
|
||||||
- Portrait images show in full over a blurred cover layer by default. The image editor previews a per-image fit, position, and overlay, and saves or resets the override. Global settings apply to other images. The [plugin API](plugin-development.md#plugin-api) defines the storage.
|
- The next image loads and decodes before its fade starts. A new frame changes only the custom properties with a new value.
|
||||||
- A new browser tab on `about:blank` shows the host background. A loaded page keeps its own rendering, even when it is empty.
|
- Portrait images show in full over a blurred cover layer by default. The image editor previews a per-image fit, position, and overlay, and saves or resets the override. The folder layout applies to other images. The sidecar file `.runestone-backgrounds.json` in the folder keeps the overrides.
|
||||||
|
- **Next background image** and **Pause background** are in the command palette. Next reaches every window. Pause keeps the current image and stops the timer.
|
||||||
|
- A new browser tab on `about:blank` shows the host background, also in a browser window. A loaded page keeps its own rendering, even when it is empty.
|
||||||
|
|
||||||
Decisions: [UI-015](design-decisions.md#ui-015--slower-slideshow-fades), [UI-020](design-decisions.md#ui-020--per-image-slideshow-layout).
|
Decisions: [UI-015](design-decisions.md#ui-015--slower-slideshow-fades), [UI-020](design-decisions.md#ui-020--per-image-slideshow-layout), [UI-057](design-decisions.md#ui-057--background-replaces-background-image-and-background-slideshow).
|
||||||
|
|
||||||
## Tooltips and text selection
|
## Tooltips and text selection
|
||||||
|
|
||||||
@@ -286,10 +293,11 @@ Decisions: [UI-021](design-decisions.md#ui-021--workspace-links-in-document-pane
|
|||||||
|
|
||||||
- A description edit stays a draft until Save. Cancel restores the saved text. Closing card details keeps the draft, and the card then shows an unsaved marker. Edit opens the draft. Use the labels Save and Cancel, and leave readable space below long descriptions.
|
- A description edit stays a draft until Save. Cancel restores the saved text. Closing card details keeps the draft, and the card then shows an unsaved marker. Edit opens the draft. Use the labels Save and Cancel, and leave readable space below long descriptions.
|
||||||
- Board and list changes save at once. Close and an outside click use the same save path for other fields.
|
- Board and list changes save at once. Close and an outside click use the same save path for other fields.
|
||||||
- Each workspace can set a fixed default view: All tasks or one board. Restored tabs and explicit links keep their targets. An unavailable default returns to All tasks. A workspace without boards shows a New board action.
|
- Each workspace can set a fixed default view: All tasks or one board. Restored tabs and explicit links keep their targets. An unavailable default returns to All tasks. A workspace without boards shows **Create your first board**.
|
||||||
|
- Project Management is host code (`src/lib/features/pm/ui/`). The board scope, the select choices, and the details pickers use the shared action menu. Icon-only controls use the shared tooltip and the shared action icons. All interface text comes from the catalog.
|
||||||
- New cards record their creation time, and card details show it. Existing cards show Unknown when no reliable time exists. Moves and edits do not change it. Board cards do not show timestamps.
|
- New cards record their creation time, and card details show it. Existing cards show Unknown when no reliable time exists. Moves and edits do not change it. Board cards do not show timestamps.
|
||||||
|
|
||||||
Decisions: [UI-033](design-decisions.md#ui-033--list-capacity-and-a-frozen-all-tasks-overview), [UI-034](design-decisions.md#ui-034--find-scope-and-shared-list-names), [UI-035](design-decisions.md#ui-035--board-dividers-in-all-tasks), [UI-036](design-decisions.md#ui-036--compact-list-collapse-and-assigned-creation), [UI-037](design-decisions.md#ui-037--saved-metadata-and-explicit-description-drafts), [UI-038](design-decisions.md#ui-038--fixed-workspace-default-board).
|
Decisions: [UI-033](design-decisions.md#ui-033--list-capacity-and-a-frozen-all-tasks-overview), [UI-034](design-decisions.md#ui-034--find-scope-and-shared-list-names), [UI-035](design-decisions.md#ui-035--board-dividers-in-all-tasks), [UI-036](design-decisions.md#ui-036--compact-list-collapse-and-assigned-creation), [UI-037](design-decisions.md#ui-037--saved-metadata-and-explicit-description-drafts), [UI-038](design-decisions.md#ui-038--fixed-workspace-default-board), [UI-060](design-decisions.md#ui-060--native-project-management).
|
||||||
|
|
||||||
## Review checklist
|
## Review checklist
|
||||||
|
|
||||||
|
|||||||
+37
-9
@@ -10,13 +10,15 @@ This guide explains how to work with files, documents, tabs, settings, and the b
|
|||||||
| Create, find, or organize files | [Create and find files](#create-and-find-files) |
|
| Create, find, or organize files | [Create and find files](#create-and-find-files) |
|
||||||
| Write, read, or follow a link | [Edit documents](#edit-documents) |
|
| Write, read, or follow a link | [Edit documents](#edit-documents) |
|
||||||
| Work with images, diagrams, or tables | [Images, diagrams, and tables](guides/document-tools.md) |
|
| Work with images, diagrams, or tables | [Images, diagrams, and tables](guides/document-tools.md) |
|
||||||
|
| Read a PDF file | [Read PDF files](#read-pdf-files) |
|
||||||
| Start a note from a template | [Use note templates](#use-note-templates) |
|
| Start a note from a template | [Use note templates](#use-note-templates) |
|
||||||
| Arrange tabs and windows | [Manage tabs](#manage-tabs) |
|
| 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) |
|
| 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) |
|
| Change the language or colors | [Change settings](#change-settings) and [Appearance](guides/themes.md) |
|
||||||
| Review changes and commit with Git | [Git guide](guides/git.md) |
|
| Review changes and commit with Git | [Git guide](guides/git.md) |
|
||||||
|
| Plan work on boards, a timeline, and a calendar | [Project Management guide](guides/project-management.md) |
|
||||||
| Turn a built-in feature on or off | [Turn features on or off](#turn-features-on-or-off) |
|
| 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) |
|
| Add plugins | [Install and manage plugins](plugins.md) |
|
||||||
| Browse websites | [Use the built-in browser](#use-the-built-in-browser) |
|
| Browse websites | [Use the built-in browser](#use-the-built-in-browser) |
|
||||||
| Run commands or scripts | [Terminal guide](guides/terminal.md) |
|
| Run commands or scripts | [Terminal guide](guides/terminal.md) |
|
||||||
|
|
||||||
@@ -83,7 +85,7 @@ Each document pane has one view control with three choices, and a **Split** butt
|
|||||||
| **Split** | Read beside Write or Source. Narrow panes stack the two views. Select **Split** again to close it. Markdown files only. |
|
| **Split** | Read beside Write or Source. Narrow panes stack the two views. Select **Split** again to close it. Markdown files only. |
|
||||||
|
|
||||||
Press Ctrl+E to switch between Write and Source. Press Ctrl+Shift+E to switch between Read and the editor. The tab menu has the same choices under **View**.
|
Press Ctrl+E to switch between Write and Source. Press Ctrl+Shift+E to switch between Read and the editor. The tab menu has the same choices under **View**.
|
||||||
In a narrow pane, the control shows only icons. Hover over an icon, or focus it with the keyboard, to see its name. The arrow keys move the choice.
|
The control shows icons only. Hover over an icon, or focus it with the keyboard, to see its name and shortcut. The arrow keys move the choice.
|
||||||
The status bar shows the save state, the line and column of the cursor, the word count, the line endings (LF or CRLF), and the current view. For a folder on a network drive, it also shows **Polling for changes**. A tab without a document, such as the theme editor, has no outline and no document facts. The bar above the document shows the folder of the file, and the tab shows the file name.
|
The status bar shows the save state, the line and column of the cursor, the word count, the line endings (LF or CRLF), and the current view. For a folder on a network drive, it also shows **Polling for changes**. A tab without a document, such as the theme editor, has no outline and no document facts. The bar above the document shows the folder of the file, and the tab shows the file name.
|
||||||
Write keeps your Markdown source, frontmatter, and Windows line endings. Read shows frontmatter in a collapsed **Properties** section.
|
Write keeps your Markdown source, frontmatter, and Windows line endings. Read shows frontmatter in a collapsed **Properties** section.
|
||||||
Select a checkbox to complete a task. Copy code blocks without their Markdown fences with the **Copy code** button.
|
Select a checkbox to complete a task. Copy code blocks without their Markdown fences with the **Copy code** button.
|
||||||
@@ -128,6 +130,26 @@ In Write, these shortcuts format the selected text:
|
|||||||
The menu also has link, search, extraction, and clipboard actions. RuneStone has no formatting toolbar.
|
The menu also has link, search, extraction, and clipboard actions. RuneStone has no formatting toolbar.
|
||||||
Right-click a misspelled word to see spelling suggestions from the operating system.
|
Right-click a misspelled word to see spelling suggestions from the operating system.
|
||||||
|
|
||||||
|
## Read PDF files
|
||||||
|
|
||||||
|
Select a PDF file in the file tree. It opens in its own tab. The file tree marks PDF files with a document icon.
|
||||||
|
|
||||||
|
| Action | How |
|
||||||
|
| --- | --- |
|
||||||
|
| Change the page | Select **Previous page** or **Next page**. Or type a number in the page field and press Enter. With the page area focused, press Page Up or Page Down. |
|
||||||
|
| Zoom | Select **Zoom in** or **Zoom out**, from 25% to 400%. **Fit width** fits the page to the tab again. |
|
||||||
|
| Rotate | Select **Rotate clockwise**. Each click turns the page by 90 degrees. |
|
||||||
|
| Copy text | Select text on the page with the pointer, then press Ctrl+C. |
|
||||||
|
| Show changes from another program | Select **Reload PDF**. The tab stays on the same page. |
|
||||||
|
| Open a protected PDF | Type the password, then select **Unlock**. RuneStone does not save the password. |
|
||||||
|
|
||||||
|
- A PDF file must be in the workspace and at most 64 MiB.
|
||||||
|
- The tab shows one page at a time. It does not edit PDF files, fill forms, open links, run scripts in a PDF, or print.
|
||||||
|
- Scanned pages show as images, so you cannot select their text.
|
||||||
|
- If a PDF does not open, the tab shows the error. Select **Reload PDF**, or try another copy of the file.
|
||||||
|
|
||||||
|
PDF Viewer is a built-in feature. To turn it off, see [Turn features on or off](#turn-features-on-or-off).
|
||||||
|
|
||||||
## Use note templates
|
## Use note templates
|
||||||
|
|
||||||
A template is a Markdown file in the workspace folder `.runestone/templates/`.
|
A template is a Markdown file in the workspace folder `.runestone/templates/`.
|
||||||
@@ -158,7 +180,7 @@ RuneStone moves the current text of the tab, also unsaved text. It closes the so
|
|||||||
If the move fails, the source tab stays open.
|
If the move fails, the source tab stays open.
|
||||||
|
|
||||||
When you start RuneStone again, it opens the document tabs of the workspace. It keeps their order, pins, and active tab.
|
When you start RuneStone again, it opens the document tabs of the workspace. It keeps their order, pins, and active tab.
|
||||||
This includes plugin tabs that show a file, such as a PDF. RuneStone reads the contents again from disk. Missing files do not stop the other tabs from opening.
|
This includes PDF tabs and plugin tabs that show a file. RuneStone reads the contents again from disk. Missing files do not stop the other tabs from opening.
|
||||||
|
|
||||||
## Save your work
|
## Save your work
|
||||||
|
|
||||||
@@ -199,21 +221,27 @@ Settings apply at once to all workspaces on this computer and update all open wi
|
|||||||
| Category | Settings |
|
| Category | Settings |
|
||||||
| --- | --- |
|
| --- | --- |
|
||||||
| General | Display language, **File name title**, **Keep line breaks**, **Table formulas**, **Show .runestone folder**, and auto-save |
|
| 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). |
|
| Appearance | Color theme, transparency, background (a folder slideshow or one 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). |
|
| Features | Turn Git, Background, Terminal, PDF Viewer, and Project Management 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). |
|
| 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 |
|
| Browser | Homepage, search engine, profiles, ad blocking, and web data |
|
||||||
|
| Terminal | Default profile, font size, scrollback lines, and cursor blink. The page shows only while Terminal is on. See [Change the terminal settings](guides/terminal.md#change-the-terminal-settings). |
|
||||||
|
| Project Management | Priority levels and the default board of the workspace. The page shows only while Project Management is on. See [Change the Project Management settings](guides/project-management.md#change-the-project-management-settings). |
|
||||||
|
|
||||||
### Turn features on or off
|
### 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.
|
Git, Background, Terminal, PDF Viewer, and Project Management are built-in features 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 on uses no extra memory until you first use it. Examples are Source control, a terminal, a PDF file, or a board. Background loads at the start only when you selected a folder or an image.
|
||||||
- A feature that is off does not load. Its buttons, commands, and tabs do not show.
|
- A feature that is off does not load. Its buttons, commands, and tabs do not show.
|
||||||
|
- Terminal off ends the terminal sessions of every window. When a window runs a shell, RuneStone asks first.
|
||||||
- A change applies at once in all windows. The code that a window loaded stays in memory until you restart RuneStone.
|
- 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.
|
After an update, Git takes the state of its old plugin package: on when the package was enabled, off when it was disabled. Without an old package, Git starts on.
|
||||||
Without an old package, the feature starts on. Settings → Plug-ins shows an old package as **Included with RuneStone**. You can uninstall it.
|
Terminal does the same with the old Terminal plugin, and it copies the terminal settings of that plugin. PDF Viewer does the same with the old PDF Viewer plugin.
|
||||||
|
Project Management does the same with the old Project Management plugin, and it copies the priority levels of that plugin.
|
||||||
|
Background starts on for every user. It takes the folder, the timing, and the targets of the Background Slideshow plugin when that plugin was on. Otherwise it shows your old background image, if you had one. See [Show a background](guides/themes.md#show-a-background).
|
||||||
|
Settings → Plug-ins shows an old package as **Included with RuneStone**. You can uninstall it.
|
||||||
|
|
||||||
### Display language
|
### Display language
|
||||||
|
|
||||||
|
|||||||
+6
-2
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "runestone",
|
"name": "runestone",
|
||||||
"version": "0.1.49",
|
"version": "0.1.51",
|
||||||
"description": "Desktop editor for a local workspace",
|
"description": "Desktop editor for a local workspace",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
@@ -54,8 +54,12 @@
|
|||||||
"@tiptap/extension-link": "^3.31.3",
|
"@tiptap/extension-link": "^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",
|
||||||
|
"pdfjs-dist": "6.4.299",
|
||||||
|
"yaml": "2.9.1"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@sveltejs/adapter-static": "^3.0.10",
|
"@sveltejs/adapter-static": "^3.0.10",
|
||||||
|
|||||||
@@ -66,7 +66,7 @@ A type-only import, such as `import type { PluginApi }`, adds no code to the bun
|
|||||||
|
|
||||||
## Check for features
|
## Check for features
|
||||||
|
|
||||||
Members marked optional in `PluginApi` can be absent on older RuneStone versions. Examples are `api.pty`, `api.files`, and `api.workspace.readBytes`.
|
Members marked optional in `PluginApi` can be absent on older RuneStone versions. Examples are `api.files`, `api.services`, and `api.workspace.readBytes`.
|
||||||
Make sure that a member exists before you use it.
|
Make sure that a member exists before you use it.
|
||||||
|
|
||||||
```ts
|
```ts
|
||||||
@@ -74,8 +74,8 @@ import { hasFeature, requireFeature, requireFeatures, type PluginApi } from "@ru
|
|||||||
|
|
||||||
export function activate(api: PluginApi) {
|
export function activate(api: PluginApi) {
|
||||||
// Stop the activation with one message that names each missing feature.
|
// Stop the activation with one message that names each missing feature.
|
||||||
requireFeatures(api, ["pty", "workspace.readOptional"]);
|
requireFeatures(api, ["files", "workspace.readOptional"]);
|
||||||
const pty = requireFeature(api, "pty");
|
const files = requireFeature(api, "files");
|
||||||
|
|
||||||
// Hide a control when the feature is absent.
|
// Hide a control when the feature is absent.
|
||||||
if (hasFeature(api, "ui.showActionMenu")) showMenuButton();
|
if (hasFeature(api, "ui.showActionMenu")) showMenuButton();
|
||||||
@@ -91,7 +91,7 @@ export function activate(api: PluginApi) {
|
|||||||
|
|
||||||
When a feature is missing, `requireFeature` and `requireFeatures` throw a `MissingFeatureError`. Its `features` property lists the feature names.
|
When a feature is missing, `requireFeature` and `requireFeatures` throw a `MissingFeatureError`. Its `features` property lists the feature names.
|
||||||
Its message names each feature and its API path, and tells the user to update RuneStone. For example:
|
Its message names each feature and its API path, and tells the user to update RuneStone. For example:
|
||||||
`This plugin needs the terminal API (api.pty). Update RuneStone to a version that has this feature.`
|
`This plugin needs the folder grant API (api.files). Update RuneStone to a version that has this feature.`
|
||||||
|
|
||||||
`pluginFeatures` lists all the feature names. The checks examine only whether the member exists.
|
`pluginFeatures` lists all the feature names. The checks examine only whether the member exists.
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,3 @@
|
|||||||
import type { BackgroundApi } from "./backgrounds.ts";
|
|
||||||
import type { CompletionApi } from "./completion.ts";
|
import type { CompletionApi } from "./completion.ts";
|
||||||
import type { Contributions } from "./contributions.ts";
|
import type { Contributions } from "./contributions.ts";
|
||||||
import type { ActionIcon } from "./icons.ts";
|
import type { ActionIcon } from "./icons.ts";
|
||||||
@@ -20,34 +19,6 @@ export interface PluginDocumentType {
|
|||||||
create?: { label: string; defaultName: string; extension: string; contents(): string };
|
create?: { label: string; defaultName: string; extension: string; contents(): string };
|
||||||
mount(container: HTMLElement, document: PluginDocumentContext): void | Dispose | Promise<void | Dispose>;
|
mount(container: HTMLElement, document: PluginDocumentContext): void | Dispose | Promise<void | Dispose>;
|
||||||
}
|
}
|
||||||
export interface PtyProfile { id: string; title: string; kind: string }
|
|
||||||
export interface PtyOpenOptions {
|
|
||||||
/** The workspace root of the window. The host rejects the request when the workspace changed. */
|
|
||||||
cwd: string;
|
|
||||||
cols: number;
|
|
||||||
rows: number;
|
|
||||||
profile?: string;
|
|
||||||
/** A start folder other than the workspace root. */
|
|
||||||
directory?: string;
|
|
||||||
/** Receives raw terminal output. UTF-8 characters can be split between two calls. */
|
|
||||||
onData(data: Uint8Array): void;
|
|
||||||
onExit?(code: number | null): void;
|
|
||||||
}
|
|
||||||
export interface PtySession {
|
|
||||||
readonly id: string;
|
|
||||||
write(data: string): Promise<void>;
|
|
||||||
resize(cols: number, rows: number): Promise<void>;
|
|
||||||
/** Stops the shell. Repeated calls return the same promise. */
|
|
||||||
close(): Promise<void>;
|
|
||||||
}
|
|
||||||
/** Terminal sessions. The host closes the sessions of a plugin when the plugin stops. */
|
|
||||||
export interface PtyApi {
|
|
||||||
readonly version: 1;
|
|
||||||
profiles(): Promise<PtyProfile[]>;
|
|
||||||
open(options: PtyOpenOptions): Promise<PtySession>;
|
|
||||||
openWindow(): Promise<void>;
|
|
||||||
dictation(): Promise<void>;
|
|
||||||
}
|
|
||||||
export interface FolderGrant { id: string; path: string; name: string }
|
export interface FolderGrant { id: string; path: string; name: string }
|
||||||
export interface FolderEntry { name: string; size: number }
|
export interface FolderEntry { name: string; size: number }
|
||||||
/** Folders outside the workspace that the user granted to this plugin. */
|
/** Folders outside the workspace that the user granted to this plugin. */
|
||||||
@@ -89,10 +60,8 @@ export interface AssetsApi { read(path: string): Promise<Uint8Array> }
|
|||||||
/** Interface parts that the host draws. */
|
/** Interface parts that the host draws. */
|
||||||
export interface UiApi { showActionMenu(options: ActionMenuOptions): { close(): void } }
|
export interface UiApi { showActionMenu(options: ActionMenuOptions): { close(): void } }
|
||||||
export interface PluginApi {
|
export interface PluginApi {
|
||||||
pty?: PtyApi;
|
|
||||||
files?: FilesApi;
|
files?: FilesApi;
|
||||||
services?: ServicesApi;
|
services?: ServicesApi;
|
||||||
backgrounds?: BackgroundApi;
|
|
||||||
ui?: UiApi;
|
ui?: UiApi;
|
||||||
completion?: CompletionApi;
|
completion?: CompletionApi;
|
||||||
readonly id: string;
|
readonly id: string;
|
||||||
|
|||||||
@@ -1,24 +0,0 @@
|
|||||||
/** Background image frames behind the RuneStone interface. */
|
|
||||||
export interface BackgroundFrame {
|
|
||||||
url: string;
|
|
||||||
blurredUrl?: string;
|
|
||||||
overlay: number;
|
|
||||||
position: 'center' | 'top left' | 'top' | 'top right' | 'left' | 'right' | 'bottom left' | 'bottom' | 'bottom right';
|
|
||||||
size: 'cover' | 'contain' | 'auto';
|
|
||||||
previous?: Omit<BackgroundFrame, 'previous' | 'transitionMs'>;
|
|
||||||
transitionMs?: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** The folder methods are deprecated. Use `FilesApi` folder grants in new code. */
|
|
||||||
export interface BackgroundApi {
|
|
||||||
readonly version: 1;
|
|
||||||
chooseFolder(): Promise<string | null>;
|
|
||||||
defaultFolder?(): Promise<string>;
|
|
||||||
list(folder: string): Promise<{ name: string }[]>;
|
|
||||||
read(folder: string, name: string): Promise<Uint8Array>;
|
|
||||||
readImageSettings?(folder: string): Promise<string | null>;
|
|
||||||
writeImageSettings?(folder: string, contents: string, expected: string | null): Promise<void>;
|
|
||||||
set(target: string, frame: BackgroundFrame | null): void;
|
|
||||||
get(target: string): BackgroundFrame | null;
|
|
||||||
subscribe(listener: (target: string) => void): () => void;
|
|
||||||
}
|
|
||||||
@@ -1,16 +1,5 @@
|
|||||||
import type { Dispose } from "./api.ts";
|
import type { Dispose } from "./api.ts";
|
||||||
|
|
||||||
export type TerminalAction = "toggle" | "new" | "window" | "split" | "previous" | "next" | "commands" | "directories";
|
|
||||||
export interface TerminalProps {
|
|
||||||
cwd: string; visible: boolean; maximized?: boolean; standalone?: boolean;
|
|
||||||
onClose: () => void; onMaximize?: () => void; activeFile?: boolean;
|
|
||||||
onRunFile?: () => Promise<string | null>; getSelection?: () => string; onConfigureTasks?: () => Promise<void>;
|
|
||||||
}
|
|
||||||
export interface TerminalMount {
|
|
||||||
update(props: TerminalProps): void;
|
|
||||||
command(action: Exclude<TerminalAction, "toggle">): void | Promise<void>;
|
|
||||||
dispose: Dispose;
|
|
||||||
}
|
|
||||||
/** Host features that `api.contribute(key, value)` registers. Only one enabled plugin can own each key. */
|
/** Host features that `api.contribute(key, value)` registers. Only one enabled plugin can own each key. */
|
||||||
export interface Contributions {
|
export interface Contributions {
|
||||||
browser: {
|
browser: {
|
||||||
@@ -21,8 +10,4 @@ export interface Contributions {
|
|||||||
/** Opens a web link from a document. False means that the system browser opens it. */
|
/** Opens a web link from a document. False means that the system browser opens it. */
|
||||||
open(url: string): Promise<boolean>;
|
open(url: string): Promise<boolean>;
|
||||||
};
|
};
|
||||||
terminal: {
|
|
||||||
mount(container: HTMLElement, props: TerminalProps): TerminalMount;
|
|
||||||
shortcut(event: Pick<KeyboardEvent, "ctrlKey" | "metaKey" | "altKey" | "shiftKey" | "code" | "key">): TerminalAction | null;
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,4 @@
|
|||||||
import type { FilesApi, PluginApi, PtyApi, ServicesApi, SettingsApi, UiApi, WorkspaceApi } from "./api.ts";
|
import type { FilesApi, PluginApi, ServicesApi, SettingsApi, UiApi, WorkspaceApi } from "./api.ts";
|
||||||
import type { BackgroundApi } from "./backgrounds.ts";
|
|
||||||
import type { CompletionApi } from "./completion.ts";
|
import type { CompletionApi } from "./completion.ts";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -7,10 +6,8 @@ import type { CompletionApi } from "./completion.ts";
|
|||||||
* Older RuneStone hosts can omit these members. Required members, such as `workspace.read`, are not listed.
|
* Older RuneStone hosts can omit these members. Required members, such as `workspace.read`, are not listed.
|
||||||
*/
|
*/
|
||||||
export interface PluginFeatures {
|
export interface PluginFeatures {
|
||||||
pty: PtyApi;
|
|
||||||
files: FilesApi;
|
files: FilesApi;
|
||||||
services: ServicesApi;
|
services: ServicesApi;
|
||||||
backgrounds: BackgroundApi;
|
|
||||||
completion: CompletionApi;
|
completion: CompletionApi;
|
||||||
"completion.transport": NonNullable<CompletionApi["transport"]>;
|
"completion.transport": NonNullable<CompletionApi["transport"]>;
|
||||||
"ui.showActionMenu": UiApi["showActionMenu"];
|
"ui.showActionMenu": UiApi["showActionMenu"];
|
||||||
@@ -33,10 +30,8 @@ export interface PluginFeatures {
|
|||||||
export type PluginFeature = keyof PluginFeatures;
|
export type PluginFeature = keyof PluginFeatures;
|
||||||
|
|
||||||
const descriptions: { [K in PluginFeature]: string } = {
|
const descriptions: { [K in PluginFeature]: string } = {
|
||||||
pty: "the terminal API",
|
|
||||||
files: "the folder grant API",
|
files: "the folder grant API",
|
||||||
services: "the plugin service API",
|
services: "the plugin service API",
|
||||||
backgrounds: "the background API",
|
|
||||||
completion: "the completion API",
|
completion: "the completion API",
|
||||||
"completion.transport": "the completion model transport",
|
"completion.transport": "the completion model transport",
|
||||||
"ui.showActionMenu": "the shared action menu",
|
"ui.showActionMenu": "the shared action menu",
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
// The public types and helpers of the RuneStone plugin API.
|
// The public types and helpers of the RuneStone plugin API.
|
||||||
// The icon and tooltip helpers use the DOM. Import them from "@runestone/plugin-sdk/icons" and "@runestone/plugin-sdk/tooltip".
|
// The icon and tooltip helpers use the DOM. Import them from "@runestone/plugin-sdk/icons" and "@runestone/plugin-sdk/tooltip".
|
||||||
export type * from "./api.ts";
|
export type * from "./api.ts";
|
||||||
export type * from "./backgrounds.ts";
|
|
||||||
export type * from "./completion.ts";
|
export type * from "./completion.ts";
|
||||||
export type * from "./contributions.ts";
|
export type * from "./contributions.ts";
|
||||||
export type * from "./menu.ts";
|
export type * from "./menu.ts";
|
||||||
|
|||||||
Generated
+176
-15
@@ -89,22 +89,34 @@ 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
|
||||||
mermaid:
|
mermaid:
|
||||||
specifier: ^12.0.0
|
specifier: ^12.0.0
|
||||||
version: 12.0.0
|
version: 12.0.0
|
||||||
|
pdfjs-dist:
|
||||||
|
specifier: 6.4.299
|
||||||
|
version: 6.4.299
|
||||||
|
yaml:
|
||||||
|
specifier: 2.9.1
|
||||||
|
version: 2.9.1
|
||||||
devDependencies:
|
devDependencies:
|
||||||
'@sveltejs/adapter-static':
|
'@sveltejs/adapter-static':
|
||||||
specifier: ^3.0.10
|
specifier: ^3.0.10
|
||||||
version: 3.0.10(@sveltejs/[email protected](@sveltejs/[email protected]([email protected])([email protected](@types/[email protected])))([email protected])([email protected])([email protected](@types/[email protected])))
|
version: 3.0.10(@sveltejs/[email protected](@sveltejs/[email protected]([email protected])([email protected](@types/[email protected])([email protected])))([email protected])([email protected])([email protected](@types/[email protected])([email protected])))
|
||||||
'@sveltejs/kit':
|
'@sveltejs/kit':
|
||||||
specifier: ^2.65.1
|
specifier: ^2.65.1
|
||||||
version: 2.70.3(@sveltejs/[email protected]([email protected])([email protected](@types/[email protected])))([email protected])([email protected])([email protected](@types/[email protected]))
|
version: 2.70.3(@sveltejs/[email protected]([email protected])([email protected](@types/[email protected])([email protected])))([email protected])([email protected])([email protected](@types/[email protected])([email protected]))
|
||||||
'@sveltejs/vite-plugin-svelte':
|
'@sveltejs/vite-plugin-svelte':
|
||||||
specifier: ^7.1.2
|
specifier: ^7.1.2
|
||||||
version: 7.3.0([email protected])([email protected](@types/[email protected]))
|
version: 7.3.0([email protected])([email protected](@types/[email protected])([email protected]))
|
||||||
'@tauri-apps/cli':
|
'@tauri-apps/cli':
|
||||||
specifier: ^2
|
specifier: ^2
|
||||||
version: 2.11.4
|
version: 2.11.4
|
||||||
@@ -125,7 +137,7 @@ importers:
|
|||||||
version: 6.0.3
|
version: 6.0.3
|
||||||
vite:
|
vite:
|
||||||
specifier: ^8.0.16
|
specifier: ^8.0.16
|
||||||
version: 8.3.0(@types/[email protected])
|
version: 8.3.0(@types/[email protected])([email protected])
|
||||||
|
|
||||||
packages:
|
packages:
|
||||||
|
|
||||||
@@ -272,6 +284,81 @@ packages:
|
|||||||
resolution: {integrity: sha512-K8BeapFUfrfxbRAUQAG5oBOCwo1+bNWzaVnPxTCutkfrTBn6T/j91FIhqxWJ32SUeQ9T3iy1zcmPZ5ROZEvDrg==}
|
resolution: {integrity: sha512-K8BeapFUfrfxbRAUQAG5oBOCwo1+bNWzaVnPxTCutkfrTBn6T/j91FIhqxWJ32SUeQ9T3iy1zcmPZ5ROZEvDrg==}
|
||||||
engines: {node: '>=22.12.0'}
|
engines: {node: '>=22.12.0'}
|
||||||
|
|
||||||
|
'@napi-rs/[email protected]':
|
||||||
|
resolution: {integrity: sha512-trn7AaDzQ+yeeA0ezhkC7cB1ZDPtp4UYk0EvB5F8qtYL9jEVWtVrU30WOpI52DszoTxaTsCgf5PP4ZVaOlOIHQ==}
|
||||||
|
engines: {node: '>= 10'}
|
||||||
|
cpu: [arm64]
|
||||||
|
os: [android]
|
||||||
|
|
||||||
|
'@napi-rs/[email protected]':
|
||||||
|
resolution: {integrity: sha512-6Y2djEetL8copxfNK6hg7oig/xqTwOchv19hBOm+zBNdKc/02Z3kjZN5wrLzv/l5O04/bAQS6I/AlQpwBlXgPg==}
|
||||||
|
engines: {node: '>= 10'}
|
||||||
|
cpu: [arm64]
|
||||||
|
os: [darwin]
|
||||||
|
|
||||||
|
'@napi-rs/[email protected]':
|
||||||
|
resolution: {integrity: sha512-OZoPwwu4TMMg8GTCFBrg8UFExwQTU/55i3uTC/izDat6PHE+ro9dimyQoOboFf91+NY7Pnn70ScR8f8I8+eZXw==}
|
||||||
|
engines: {node: '>= 10'}
|
||||||
|
cpu: [x64]
|
||||||
|
os: [darwin]
|
||||||
|
|
||||||
|
'@napi-rs/[email protected]':
|
||||||
|
resolution: {integrity: sha512-dZSYaKROuswU2eUWG5aBKndNVe68elo1YX93xtRax7q658tj8rYE+HwduovWJgs6qwv1r1/CLR60nDeBbyjvyg==}
|
||||||
|
engines: {node: '>= 10'}
|
||||||
|
cpu: [arm]
|
||||||
|
os: [linux]
|
||||||
|
|
||||||
|
'@napi-rs/[email protected]':
|
||||||
|
resolution: {integrity: sha512-W6FzYE8ADHI93In1vi80KBL6btDtAMuj50Ch5ptkWS8xuntyzbR4h5JDUmXoakxZn2yMInksudTEqVSWoFqFGg==}
|
||||||
|
engines: {node: '>= 10'}
|
||||||
|
cpu: [arm64]
|
||||||
|
os: [linux]
|
||||||
|
libc: [glibc]
|
||||||
|
|
||||||
|
'@napi-rs/[email protected]':
|
||||||
|
resolution: {integrity: sha512-+6fQ+rR49hkAa4voh2stLIwQ+4t+gmoseM8Bc53/DlMXb73IKymDPWK9A/NtWeqTW4ijWppYuyuxS2hPI8tzNA==}
|
||||||
|
engines: {node: '>= 10'}
|
||||||
|
cpu: [arm64]
|
||||||
|
os: [linux]
|
||||||
|
libc: [musl]
|
||||||
|
|
||||||
|
'@napi-rs/[email protected]':
|
||||||
|
resolution: {integrity: sha512-17XEMO3t9RW/TtHtSFf2AkaSWuCWdzbPeidz7zrOFawHxoLSJCnpTI1hN5aUvrZNnkNNmt/vZVJCh0ryUaik3A==}
|
||||||
|
engines: {node: '>= 10'}
|
||||||
|
cpu: [riscv64]
|
||||||
|
os: [linux]
|
||||||
|
libc: [glibc]
|
||||||
|
|
||||||
|
'@napi-rs/[email protected]':
|
||||||
|
resolution: {integrity: sha512-lc48IwknVHBsNzXn9Xs5OkUsRX38Ml3Z1aOybQ51mMEzZckm8+4A0qROlyYHEoBPzr1kL3IU8ZUAqDb7wtdX8w==}
|
||||||
|
engines: {node: '>= 10'}
|
||||||
|
cpu: [x64]
|
||||||
|
os: [linux]
|
||||||
|
libc: [glibc]
|
||||||
|
|
||||||
|
'@napi-rs/[email protected]':
|
||||||
|
resolution: {integrity: sha512-bGY1r26S2bs8UNFJcPWcCSNdCFbKep5PATsvtgtC9A5u6SRgr2/jJE/RlhHL5m9ZpixNDhVkLY/5h16Kx5V9YA==}
|
||||||
|
engines: {node: '>= 10'}
|
||||||
|
cpu: [x64]
|
||||||
|
os: [linux]
|
||||||
|
libc: [musl]
|
||||||
|
|
||||||
|
'@napi-rs/[email protected]':
|
||||||
|
resolution: {integrity: sha512-2vRPBZoaIvJrUkDhZTE2Hn0YrnpJRCWVM3EJACoBKjuWI6WgPxGtUoRMsxRviCsyks8bKTSFdyw14CellnG2qA==}
|
||||||
|
engines: {node: '>= 10'}
|
||||||
|
cpu: [arm64]
|
||||||
|
os: [win32]
|
||||||
|
|
||||||
|
'@napi-rs/[email protected]':
|
||||||
|
resolution: {integrity: sha512-DUlW3lZPz63kYsf8mxgyyZuevhlH0T3/BGP9l+NazhB0F1+gL6D4hqZdnhZpw24DlWmTpATDcyYSZlJOi+DdfQ==}
|
||||||
|
engines: {node: '>= 10'}
|
||||||
|
cpu: [x64]
|
||||||
|
os: [win32]
|
||||||
|
|
||||||
|
'@napi-rs/[email protected]':
|
||||||
|
resolution: {integrity: sha512-b87ugZpQ5ViwqVBkjervxpwa0GmJPsKHLBNoZN6GpjWeHzTbDUGryriq+2DYW2XbB+xCqSIINQysC0/I87nPbw==}
|
||||||
|
engines: {node: '>= 10'}
|
||||||
|
|
||||||
'@oxc-project/[email protected]':
|
'@oxc-project/[email protected]':
|
||||||
resolution: {integrity: sha512-rDS5/31E9HfPl/CIzGrn0DOlvBbXFseQ5URJ9sYMfstbKLD/c6Gm9vmRzRGDdAXyOIL4zmO37lc9RIwYqVruZw==}
|
resolution: {integrity: sha512-rDS5/31E9HfPl/CIzGrn0DOlvBbXFseQ5URJ9sYMfstbKLD/c6Gm9vmRzRGDdAXyOIL4zmO37lc9RIwYqVruZw==}
|
||||||
|
|
||||||
@@ -750,6 +837,12 @@ 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'}
|
||||||
@@ -1183,6 +1276,10 @@ packages:
|
|||||||
[email protected]:
|
[email protected]:
|
||||||
resolution: {integrity: sha512-NOnmBpt5Y2RWbuv0LMzsayp3lVylAHLPUTut412ZA3l+C4uw4ZVkQbjShYCQ8TCpUMdPapr4YjUqLYD6v68j+w==}
|
resolution: {integrity: sha512-NOnmBpt5Y2RWbuv0LMzsayp3lVylAHLPUTut412ZA3l+C4uw4ZVkQbjShYCQ8TCpUMdPapr4YjUqLYD6v68j+w==}
|
||||||
|
|
||||||
|
[email protected]:
|
||||||
|
resolution: {integrity: sha512-AVl138zALtfaAPvADulE0PZThbYzCBS79nL4pOSL/6Sm/4AH5A21BD9VHt97OlCuzJuCpmeZtAtkinisF4Vb1g==}
|
||||||
|
engines: {node: '>=22.13.0 || >=24'}
|
||||||
|
|
||||||
[email protected]:
|
[email protected]:
|
||||||
resolution: {integrity: sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==}
|
resolution: {integrity: sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==}
|
||||||
|
|
||||||
@@ -1395,6 +1492,11 @@ packages:
|
|||||||
[email protected]:
|
[email protected]:
|
||||||
resolution: {integrity: sha512-dpojBhNsCNN7T82Tm7k26A6G9ML3NkhDsnw9n/eoxSRlVBB4CEtIQ/KTCLI2Fwf3ataSXRhYFkQi3SlnFwPvPQ==}
|
resolution: {integrity: sha512-dpojBhNsCNN7T82Tm7k26A6G9ML3NkhDsnw9n/eoxSRlVBB4CEtIQ/KTCLI2Fwf3ataSXRhYFkQi3SlnFwPvPQ==}
|
||||||
|
|
||||||
|
[email protected]:
|
||||||
|
resolution: {integrity: sha512-3NxN8+78OdzbT7C/WjGsyfPAtJaN3FNDsWxv7Y7mcDsT/oOmgW8BpyQQFFBnvZE3j9Y2Sdz1ULFLezL7Eb2yFw==}
|
||||||
|
engines: {node: '>= 14.6'}
|
||||||
|
hasBin: true
|
||||||
|
|
||||||
[email protected]:
|
[email protected]:
|
||||||
resolution: {integrity: sha512-msJxIvYDYcoNL+PJsu+7qmpDWsYmAxTY+2TNYXXF0hzBzBk0BMecOqDOG/EckUoKCuKwObfbugIl8QpqHDXeFA==}
|
resolution: {integrity: sha512-msJxIvYDYcoNL+PJsu+7qmpDWsYmAxTY+2TNYXXF0hzBzBk0BMecOqDOG/EckUoKCuKwObfbugIl8QpqHDXeFA==}
|
||||||
|
|
||||||
@@ -1661,6 +1763,54 @@ snapshots:
|
|||||||
dependencies:
|
dependencies:
|
||||||
'@chevrotain/types': 11.1.2
|
'@chevrotain/types': 11.1.2
|
||||||
|
|
||||||
|
'@napi-rs/[email protected]':
|
||||||
|
optional: true
|
||||||
|
|
||||||
|
'@napi-rs/[email protected]':
|
||||||
|
optional: true
|
||||||
|
|
||||||
|
'@napi-rs/[email protected]':
|
||||||
|
optional: true
|
||||||
|
|
||||||
|
'@napi-rs/[email protected]':
|
||||||
|
optional: true
|
||||||
|
|
||||||
|
'@napi-rs/[email protected]':
|
||||||
|
optional: true
|
||||||
|
|
||||||
|
'@napi-rs/[email protected]':
|
||||||
|
optional: true
|
||||||
|
|
||||||
|
'@napi-rs/[email protected]':
|
||||||
|
optional: true
|
||||||
|
|
||||||
|
'@napi-rs/[email protected]':
|
||||||
|
optional: true
|
||||||
|
|
||||||
|
'@napi-rs/[email protected]':
|
||||||
|
optional: true
|
||||||
|
|
||||||
|
'@napi-rs/[email protected]':
|
||||||
|
optional: true
|
||||||
|
|
||||||
|
'@napi-rs/[email protected]':
|
||||||
|
optional: true
|
||||||
|
|
||||||
|
'@napi-rs/[email protected]':
|
||||||
|
optionalDependencies:
|
||||||
|
'@napi-rs/canvas-android-arm64': 1.0.13
|
||||||
|
'@napi-rs/canvas-darwin-arm64': 1.0.13
|
||||||
|
'@napi-rs/canvas-darwin-x64': 1.0.13
|
||||||
|
'@napi-rs/canvas-linux-arm-gnueabihf': 1.0.13
|
||||||
|
'@napi-rs/canvas-linux-arm64-gnu': 1.0.13
|
||||||
|
'@napi-rs/canvas-linux-arm64-musl': 1.0.13
|
||||||
|
'@napi-rs/canvas-linux-riscv64-gnu': 1.0.13
|
||||||
|
'@napi-rs/canvas-linux-x64-gnu': 1.0.13
|
||||||
|
'@napi-rs/canvas-linux-x64-musl': 1.0.13
|
||||||
|
'@napi-rs/canvas-win32-arm64-msvc': 1.0.13
|
||||||
|
'@napi-rs/canvas-win32-x64-msvc': 1.0.13
|
||||||
|
optional: true
|
||||||
|
|
||||||
'@oxc-project/[email protected]': {}
|
'@oxc-project/[email protected]': {}
|
||||||
|
|
||||||
'@polka/[email protected]': {}
|
'@polka/[email protected]': {}
|
||||||
@@ -1718,15 +1868,15 @@ snapshots:
|
|||||||
dependencies:
|
dependencies:
|
||||||
acorn: 8.18.0
|
acorn: 8.18.0
|
||||||
|
|
||||||
'@sveltejs/[email protected](@sveltejs/[email protected](@sveltejs/[email protected]([email protected])([email protected](@types/[email protected])))([email protected])([email protected])([email protected](@types/[email protected])))':
|
'@sveltejs/[email protected](@sveltejs/[email protected](@sveltejs/[email protected]([email protected])([email protected](@types/[email protected])([email protected])))([email protected])([email protected])([email protected](@types/[email protected])([email protected])))':
|
||||||
dependencies:
|
dependencies:
|
||||||
'@sveltejs/kit': 2.70.3(@sveltejs/[email protected]([email protected])([email protected](@types/[email protected])))([email protected])([email protected])([email protected](@types/[email protected]))
|
'@sveltejs/kit': 2.70.3(@sveltejs/[email protected]([email protected])([email protected](@types/[email protected])([email protected])))([email protected])([email protected])([email protected](@types/[email protected])([email protected]))
|
||||||
|
|
||||||
'@sveltejs/[email protected](@sveltejs/[email protected]([email protected])([email protected](@types/[email protected])))([email protected])([email protected])([email protected](@types/[email protected]))':
|
'@sveltejs/[email protected](@sveltejs/[email protected]([email protected])([email protected](@types/[email protected])([email protected])))([email protected])([email protected])([email protected](@types/[email protected])([email protected]))':
|
||||||
dependencies:
|
dependencies:
|
||||||
'@standard-schema/spec': 1.1.0
|
'@standard-schema/spec': 1.1.0
|
||||||
'@sveltejs/acorn-typescript': 1.0.13([email protected])
|
'@sveltejs/acorn-typescript': 1.0.13([email protected])
|
||||||
'@sveltejs/vite-plugin-svelte': 7.3.0([email protected])([email protected](@types/[email protected]))
|
'@sveltejs/vite-plugin-svelte': 7.3.0([email protected])([email protected](@types/[email protected])([email protected]))
|
||||||
'@types/cookie': 0.6.0
|
'@types/cookie': 0.6.0
|
||||||
acorn: 8.18.0
|
acorn: 8.18.0
|
||||||
cookie: 0.6.0
|
cookie: 0.6.0
|
||||||
@@ -1738,20 +1888,20 @@ snapshots:
|
|||||||
set-cookie-parser: 3.1.2
|
set-cookie-parser: 3.1.2
|
||||||
sirv: 3.0.2
|
sirv: 3.0.2
|
||||||
svelte: 5.57.1
|
svelte: 5.57.1
|
||||||
vite: 8.3.0(@types/[email protected])
|
vite: 8.3.0(@types/[email protected])([email protected])
|
||||||
optionalDependencies:
|
optionalDependencies:
|
||||||
typescript: 6.0.3
|
typescript: 6.0.3
|
||||||
|
|
||||||
'@sveltejs/[email protected]': {}
|
'@sveltejs/[email protected]': {}
|
||||||
|
|
||||||
'@sveltejs/[email protected]([email protected])([email protected](@types/[email protected]))':
|
'@sveltejs/[email protected]([email protected])([email protected](@types/[email protected])([email protected]))':
|
||||||
dependencies:
|
dependencies:
|
||||||
deepmerge: 4.3.1
|
deepmerge: 4.3.1
|
||||||
magic-string: 1.4.1
|
magic-string: 1.4.1
|
||||||
obug: 2.2.1
|
obug: 2.2.1
|
||||||
svelte: 5.57.1
|
svelte: 5.57.1
|
||||||
vite: 8.3.0(@types/[email protected])
|
vite: 8.3.0(@types/[email protected])([email protected])
|
||||||
vitefu: 1.1.3([email protected](@types/[email protected]))
|
vitefu: 1.1.3([email protected](@types/[email protected])([email protected]))
|
||||||
|
|
||||||
'@tauri-apps/[email protected]': {}
|
'@tauri-apps/[email protected]': {}
|
||||||
|
|
||||||
@@ -2095,6 +2245,10 @@ 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]: {}
|
||||||
@@ -2503,6 +2657,10 @@ snapshots:
|
|||||||
|
|
||||||
[email protected]: {}
|
[email protected]: {}
|
||||||
|
|
||||||
|
[email protected]:
|
||||||
|
optionalDependencies:
|
||||||
|
'@napi-rs/canvas': 1.0.13
|
||||||
|
|
||||||
[email protected]: {}
|
[email protected]: {}
|
||||||
|
|
||||||
[email protected]: {}
|
[email protected]: {}
|
||||||
@@ -2710,7 +2868,7 @@ snapshots:
|
|||||||
|
|
||||||
[email protected]: {}
|
[email protected]: {}
|
||||||
|
|
||||||
[email protected](@types/[email protected]):
|
[email protected](@types/[email protected])([email protected]):
|
||||||
dependencies:
|
dependencies:
|
||||||
lightningcss: 1.33.0
|
lightningcss: 1.33.0
|
||||||
picomatch: 4.0.7
|
picomatch: 4.0.7
|
||||||
@@ -2720,11 +2878,14 @@ snapshots:
|
|||||||
optionalDependencies:
|
optionalDependencies:
|
||||||
'@types/node': 24.19.2
|
'@types/node': 24.19.2
|
||||||
fsevents: 2.3.3
|
fsevents: 2.3.3
|
||||||
|
yaml: 2.9.1
|
||||||
|
|
||||||
[email protected]([email protected](@types/[email protected])):
|
[email protected]([email protected](@types/[email protected])([email protected])):
|
||||||
optionalDependencies:
|
optionalDependencies:
|
||||||
vite: 8.3.0(@types/[email protected])
|
vite: 8.3.0(@types/[email protected])([email protected])
|
||||||
|
|
||||||
[email protected]: {}
|
[email protected]: {}
|
||||||
|
|
||||||
|
[email protected]: {}
|
||||||
|
|
||||||
[email protected]: {}
|
[email protected]: {}
|
||||||
|
|||||||
@@ -12,7 +12,7 @@ import path from "node:path";
|
|||||||
import { fileURLToPath } from "node:url";
|
import { fileURLToPath } from "node:url";
|
||||||
|
|
||||||
/** The feature folders. The runtime files directly in `src/lib/features/` stay in the main bundle. */
|
/** The feature folders. The runtime files directly in `src/lib/features/` stay in the main bundle. */
|
||||||
export const FEATURE_FOLDERS = ["git"];
|
export const FEATURE_FOLDERS = ["git", "background", "terminal", "pdf", "pm"];
|
||||||
/** Libraries that only features need. */
|
/** Libraries that only features need. */
|
||||||
export const FEATURE_LIBRARIES = ["@xterm", "pdfjs-dist", "yaml"];
|
export const FEATURE_LIBRARIES = ["@xterm", "pdfjs-dist", "yaml"];
|
||||||
|
|
||||||
|
|||||||
@@ -31,7 +31,10 @@ export const TABLE = {
|
|||||||
background: {
|
background: {
|
||||||
plugin: { id: "runestone.bg-slideshow", repo: "runestone-bg-slideshow", tag: "v0.0.11", zip: `${PLUGIN_RELEASES}/RuneStone_Background_Slideshow/releases/runestone.bg-slideshow-0.0.11.zip` },
|
plugin: { id: "runestone.bg-slideshow", repo: "runestone-bg-slideshow", tag: "v0.0.11", zip: `${PLUGIN_RELEASES}/RuneStone_Background_Slideshow/releases/runestone.bg-slideshow-0.0.11.zip` },
|
||||||
nativeKey: "background",
|
nativeKey: "background",
|
||||||
/** The style property of the body that holds the current background image. The action counts its changes. */
|
/**
|
||||||
|
* The style property of the body that holds the current background image. The action counts its changes.
|
||||||
|
* Native: `backgroundHub.applyApp` (src/lib/plugins/backgrounds.ts) sets it for each new image of Background.
|
||||||
|
*/
|
||||||
imageProperty: { plugin: "--rs-background-image", native: "--rs-background-image" },
|
imageProperty: { plugin: "--rs-background-image", native: "--rs-background-image" },
|
||||||
changes: 3,
|
changes: 3,
|
||||||
seconds: 10,
|
seconds: 10,
|
||||||
@@ -39,6 +42,10 @@ export const TABLE = {
|
|||||||
terminal: {
|
terminal: {
|
||||||
plugin: { id: "runestone.terminal", repo: "runestone-terminal", tag: "v0.1.11", zip: `${PLUGIN_RELEASES}/RuneStone_Terminal/releases/runestone.terminal-0.1.11.zip` },
|
plugin: { id: "runestone.terminal", repo: "runestone-terminal", tag: "v0.1.11", zip: `${PLUGIN_RELEASES}/RuneStone_Terminal/releases/runestone.terminal-0.1.11.zip` },
|
||||||
nativeKey: "terminal",
|
nativeKey: "terminal",
|
||||||
|
/**
|
||||||
|
* Both modes use the same names. Native: the ribbon button comes from the feature switch, and the first click loads
|
||||||
|
* the Terminal feature and xterm (src/lib/features/TerminalHost.svelte), so the action includes that load.
|
||||||
|
*/
|
||||||
ribbon: ".plugin-ribbon",
|
ribbon: ".plugin-ribbon",
|
||||||
button: "Terminal",
|
button: "Terminal",
|
||||||
surface: ".xterm",
|
surface: ".xterm",
|
||||||
@@ -50,6 +57,11 @@ export const TABLE = {
|
|||||||
pdf: {
|
pdf: {
|
||||||
plugin: { id: "runestone.pdf-viewer", repo: "runestone-pdf-viewer", tag: "v0.0.5", zip: `${PLUGIN_RELEASES}/RuneStone_PDF_Viewer/releases/runestone.pdf-viewer-0.0.5.zip` },
|
plugin: { id: "runestone.pdf-viewer", repo: "runestone-pdf-viewer", tag: "v0.0.5", zip: `${PLUGIN_RELEASES}/RuneStone_PDF_Viewer/releases/runestone.pdf-viewer-0.0.5.zip` },
|
||||||
nativeKey: "pdf",
|
nativeKey: "pdf",
|
||||||
|
/**
|
||||||
|
* Both modes use the same names. Native: the tree row opens a PDF tab, and the first tab loads the PDF Viewer feature
|
||||||
|
* and PDF.js (src/lib/features/pdf/), so the action includes that load. Each page canvas is an image named "PDF page N",
|
||||||
|
* and the page field is a spin button named "Page number". Enter in the field goes to the page.
|
||||||
|
*/
|
||||||
row: '[data-tree-rel="sample.pdf"]',
|
row: '[data-tree-rel="sample.pdf"]',
|
||||||
firstPage: "PDF page 1",
|
firstPage: "PDF page 1",
|
||||||
pageInput: "Page number",
|
pageInput: "Page number",
|
||||||
@@ -59,8 +71,11 @@ export const TABLE = {
|
|||||||
pm: {
|
pm: {
|
||||||
plugin: { id: "runestone.pm", repo: "runestone-pm", tag: "v0.2.49", zip: `${PLUGIN_RELEASES}/RuneStone_Project_Management/releases/runestone.pm-0.2.49.zip` },
|
plugin: { id: "runestone.pm", repo: "runestone-pm", tag: "v0.2.49", zip: `${PLUGIN_RELEASES}/RuneStone_Project_Management/releases/runestone.pm-0.2.49.zip` },
|
||||||
nativeKey: "pm",
|
nativeKey: "pm",
|
||||||
/** Where the view opens: `palette`, or `menu:<ribbon menu name>`. */
|
/**
|
||||||
openIn: { plugin: "menu:Plug-in views", native: "menu:Plug-in views" },
|
* Where the view opens: `palette`, `menu:<ribbon menu name>`, or `ribbon:<ribbon button name>`. Native: the static
|
||||||
|
* ribbon button opens the default board or All tasks, and the first click loads the feature (src/lib/features/pm/).
|
||||||
|
*/
|
||||||
|
openIn: { plugin: "menu:Plug-in views", native: "ribbon:Project Management" },
|
||||||
title: "Project Management",
|
title: "Project Management",
|
||||||
card: { plugin: ".pm-card", native: ".pm-card" },
|
card: { plugin: ".pm-card", native: ".pm-card" },
|
||||||
minCards: 50,
|
minCards: 50,
|
||||||
@@ -89,9 +104,14 @@ export async function runPaletteCommand(page, title) {
|
|||||||
await input.press("Enter");
|
await input.press("Enter");
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Run a command from the palette or from a ribbon menu. `where` is `palette` or `menu:<menu name>`. */
|
/**
|
||||||
|
* Run a command from the palette, from a ribbon menu, or from a ribbon button.
|
||||||
|
* `where` is `palette`, `menu:<menu name>`, or `ribbon:<button name>`.
|
||||||
|
*/
|
||||||
export async function runCommand(page, where, title) {
|
export async function runCommand(page, where, title) {
|
||||||
if (where === "palette") return runPaletteCommand(page, title);
|
if (where === "palette") return runPaletteCommand(page, title);
|
||||||
|
const button = /^ribbon:(.+)$/.exec(where)?.[1];
|
||||||
|
if (button) return page.locator(".plugin-ribbon").getByRole("button", { name: button, exact: true }).click();
|
||||||
const menu = /^menu:(.+)$/.exec(where)?.[1];
|
const menu = /^menu:(.+)$/.exec(where)?.[1];
|
||||||
if (!menu) throw new Error(`Unknown command place ${where}.`);
|
if (!menu) throw new Error(`Unknown command place ${where}.`);
|
||||||
await page.locator(".plugin-ribbon").getByRole("button", { name: menu, exact: true }).click();
|
await page.locator(".plugin-ribbon").getByRole("button", { name: menu, exact: true }).click();
|
||||||
|
|||||||
@@ -3,6 +3,7 @@
|
|||||||
// The tool starts a test build with an isolated identifier, drives it through CDP, and stops only the process tree that it started.
|
// The tool starts a test build with an isolated identifier, drives it through CDP, and stops only the process tree that it started.
|
||||||
// Run `node scripts/measureFeatures.mjs --help` for the arguments. The results go to output/phase-7/<stage>/.
|
// Run `node scripts/measureFeatures.mjs --help` for the arguments. The results go to output/phase-7/<stage>/.
|
||||||
import { existsSync } from "node:fs";
|
import { existsSync } from "node:fs";
|
||||||
|
import { realpathSync } from "node:fs";
|
||||||
import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
|
import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
|
||||||
import os from "node:os";
|
import os from "node:os";
|
||||||
import path from "node:path";
|
import path from "node:path";
|
||||||
@@ -47,6 +48,19 @@ async function seedBackgroundPlugin(folders, backgrounds) {
|
|||||||
await writeFile(path.join(folder, "settings.json"), JSON.stringify({ grant, folder: backgrounds, seconds: TABLE.features.background.seconds, order: "name", enabled: true, targets: ["app"], overlay: 0, position: "center", size: "cover" }));
|
await writeFile(path.join(folder, "settings.json"), JSON.stringify({ grant, folder: backgrounds, seconds: TABLE.features.background.seconds, order: "name", enabled: true, targets: ["app"], overlay: 0, position: "center", size: "cover" }));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Write the `background` settings and the host folder file of the native Background before the first start
|
||||||
|
* (src/lib/features/backgroundSettings.ts and src-tauri/src/backgrounds.rs). The settings file has no other section,
|
||||||
|
* so the first start keeps it and migrates only the feature switches.
|
||||||
|
*/
|
||||||
|
async function seedBackgroundNative(folders, backgrounds) {
|
||||||
|
await mkdir(folders.roaming, { recursive: true });
|
||||||
|
const background = { source: "folder", seconds: TABLE.features.background.seconds, order: "name", paused: false, targets: ["app"], overlay: 0, position: "center", size: "cover" };
|
||||||
|
await writeFile(path.join(folders.roaming, "settings.json"), JSON.stringify({ schema: 1, revision: 1, background }, null, 2) + "\n");
|
||||||
|
// The host accepts the folder only at its resolved path.
|
||||||
|
await writeFile(path.join(folders.roaming, "background-folder.json"), JSON.stringify({ schema: 1, path: realpathSync.native(backgrounds) }, null, 2));
|
||||||
|
}
|
||||||
|
|
||||||
/** The features that are on in the running app. */
|
/** The features that are on in the running app. */
|
||||||
async function readState(app, mode, invoke) {
|
async function readState(app, mode, invoke) {
|
||||||
if (mode === "plugin") {
|
if (mode === "plugin") {
|
||||||
@@ -142,6 +156,7 @@ export async function main(argv = process.argv.slice(2)) {
|
|||||||
log(`Resetting ${folders.roaming} and ${folders.local}.`);
|
log(`Resetting ${folders.roaming} and ${folders.local}.`);
|
||||||
await resetData(folders, options.identifier);
|
await resetData(folders, options.identifier);
|
||||||
if (options.mode === "plugin" && options.features.includes("background")) await seedBackgroundPlugin(folders, fixture.backgrounds);
|
if (options.mode === "plugin" && options.features.includes("background")) await seedBackgroundPlugin(folders, fixture.backgrounds);
|
||||||
|
if (options.mode === "native" && options.features.includes("background")) await seedBackgroundNative(folders, fixture.backgrounds);
|
||||||
|
|
||||||
// The setup start opens the workspace. It also proves the test identity.
|
// The setup start opens the workspace. It also proves the test identity.
|
||||||
let session = await app.launch({ exe, port: options.port });
|
let session = await app.launch({ exe, port: options.port });
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ import { fileURLToPath } from 'node:url';
|
|||||||
|
|
||||||
const root = fileURLToPath(new URL('../', import.meta.url));
|
const root = fileURLToPath(new URL('../', import.meta.url));
|
||||||
const pluginRepos = process.env.RUNESTONE_PLUGIN_REPOS || path.resolve(root, '..');
|
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_PDF_Viewer', 'RuneStone_CSV_Viewer'];
|
export const projects = ['RuneStone', 'RuneStone_Local_Autocomplete', 'RuneStone_CSV_Viewer'];
|
||||||
const patterns = {
|
const patterns = {
|
||||||
action: /\b(?:showActionMenu|actionMenu)\s*\(/g,
|
action: /\b(?:showActionMenu|actionMenu)\s*\(/g,
|
||||||
svelteMenu: /<ContextMenu\b/g,
|
svelteMenu: /<ContextMenu\b/g,
|
||||||
|
|||||||
@@ -1,2 +0,0 @@
|
|||||||
// RuneStone_Terminal imports this path for its smoke test. The helper lives in the shared smoke harness.
|
|
||||||
export * from "../tests/smoke/_harness/pluginMocks.mjs";
|
|
||||||
+1
-5
@@ -6,7 +6,7 @@
|
|||||||
// After the parallel run, the runner runs each failed test again, one at a time (--retries, default 1).
|
// After the parallel run, the runner runs each failed test again, one at a time (--retries, default 1).
|
||||||
// A test that passes on a retry counts as "flaky". The summary lists it, but the run does not fail.
|
// A test that passes on a retry counts as "flaky". The summary lists it, but the run does not fail.
|
||||||
// A test declares what it needs on a line near the top:
|
// A test declares what it needs on a line near the top:
|
||||||
// // @requires plugin:terminal repo:RuneStone_Git/dist electron
|
// // @requires repo:RuneStone_Local_Autocomplete/src electron
|
||||||
// The runner skips a test, with the reason, when a requirement is missing.
|
// The runner skips a test, with the reason, when a requirement is missing.
|
||||||
// A test that fails because of a known app defect states it near the top:
|
// A test that fails because of a known app defect states it near the top:
|
||||||
// // @known-issue <the defect>
|
// // @known-issue <the defect>
|
||||||
@@ -67,10 +67,6 @@ async function header(file) {
|
|||||||
|
|
||||||
function missing(requirement) {
|
function missing(requirement) {
|
||||||
const [kind, value = ""] = requirement.split(/:(.*)/s);
|
const [kind, value = ""] = requirement.split(/:(.*)/s);
|
||||||
if (kind === "plugin" && value === "terminal") {
|
|
||||||
const dist = env.RUNESTONE_TERMINAL_DIST || path.join(pluginRepos, "RuneStone_Terminal", "dist");
|
|
||||||
return existsSync(path.join(dist, "main.js")) ? null : `the Terminal plugin is not built at ${dist}`;
|
|
||||||
}
|
|
||||||
if (kind === "repo") {
|
if (kind === "repo") {
|
||||||
const target = path.join(pluginRepos, value);
|
const target = path.join(pluginRepos, value);
|
||||||
return existsSync(target) ? null : `${target} is missing; set RUNESTONE_PLUGIN_REPOS to the folder of the plugin checkouts`;
|
return existsSync(target) ? null : `${target} is missing; set RUNESTONE_PLUGIN_REPOS to the folder of the plugin checkouts`;
|
||||||
|
|||||||
Generated
+1
-1
@@ -3130,7 +3130,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "runestone"
|
name = "runestone"
|
||||||
version = "0.1.49"
|
version = "0.1.51"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"base64 0.23.1",
|
"base64 0.23.1",
|
||||||
"dunce",
|
"dunce",
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "runestone"
|
name = "runestone"
|
||||||
version = "0.1.49"
|
version = "0.1.51"
|
||||||
description = "Writing workspace plus script editor"
|
description = "Writing workspace plus script editor"
|
||||||
authors = ["Knotty Wyvern"]
|
authors = ["Knotty Wyvern"]
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
@@ -46,4 +46,4 @@ opt-level = 3
|
|||||||
strip = true
|
strip = true
|
||||||
|
|
||||||
[package.metadata.runestone]
|
[package.metadata.runestone]
|
||||||
version = "0.1.49"
|
version = "0.1.51"
|
||||||
|
|||||||
+9
-6
@@ -3,12 +3,14 @@ fn main() {
|
|||||||
tauri_build::Attributes::new().app_manifest(
|
tauri_build::Attributes::new().app_manifest(
|
||||||
tauri_build::AppManifest::new().commands(&[
|
tauri_build::AppManifest::new().commands(&[
|
||||||
"theme_export",
|
"theme_export",
|
||||||
"backgrounds_choose_folder",
|
"background_choose_folder",
|
||||||
"backgrounds_default_folder",
|
"background_folder",
|
||||||
"backgrounds_list",
|
"background_clear_folder",
|
||||||
"backgrounds_read",
|
"background_list",
|
||||||
"backgrounds_read_image_settings",
|
"background_read",
|
||||||
"backgrounds_write_image_settings",
|
"background_read_sidecar",
|
||||||
|
"background_write_sidecar",
|
||||||
|
"background_migrate",
|
||||||
"folders_choose",
|
"folders_choose",
|
||||||
"folders_picture",
|
"folders_picture",
|
||||||
"folders_grants",
|
"folders_grants",
|
||||||
@@ -96,6 +98,7 @@ fn main() {
|
|||||||
"pty_profiles",
|
"pty_profiles",
|
||||||
"pty_new_window",
|
"pty_new_window",
|
||||||
"pty_dictation",
|
"pty_dictation",
|
||||||
|
"pty_running",
|
||||||
]),
|
]),
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -13,6 +13,10 @@
|
|||||||
"allow-browser-engine-install",
|
"allow-browser-engine-install",
|
||||||
"allow-browser-engine-cancel",
|
"allow-browser-engine-cancel",
|
||||||
"allow-plugins-snapshot",
|
"allow-plugins-snapshot",
|
||||||
|
"allow-background-folder",
|
||||||
|
"allow-background-list",
|
||||||
|
"allow-background-read",
|
||||||
|
"allow-background-read-sidecar",
|
||||||
"allow-settings-read",
|
"allow-settings-read",
|
||||||
"allow-window-snap-layouts",
|
"allow-window-snap-layouts",
|
||||||
"allow-settings-write",
|
"allow-settings-write",
|
||||||
|
|||||||
@@ -96,13 +96,16 @@
|
|||||||
"allow-pty-profiles",
|
"allow-pty-profiles",
|
||||||
"allow-pty-new-window",
|
"allow-pty-new-window",
|
||||||
"allow-pty-dictation",
|
"allow-pty-dictation",
|
||||||
|
"allow-pty-running",
|
||||||
"opener:allow-reveal-item-in-dir",
|
"opener:allow-reveal-item-in-dir",
|
||||||
"allow-backgrounds-choose-folder",
|
"allow-background-choose-folder",
|
||||||
"allow-backgrounds-default-folder",
|
"allow-background-folder",
|
||||||
"allow-backgrounds-list",
|
"allow-background-clear-folder",
|
||||||
"allow-backgrounds-read",
|
"allow-background-list",
|
||||||
"allow-backgrounds-read-image-settings",
|
"allow-background-read",
|
||||||
"allow-backgrounds-write-image-settings",
|
"allow-background-read-sidecar",
|
||||||
|
"allow-background-write-sidecar",
|
||||||
|
"allow-background-migrate",
|
||||||
"allow-folders-choose",
|
"allow-folders-choose",
|
||||||
"allow-folders-picture",
|
"allow-folders-picture",
|
||||||
"allow-folders-grants",
|
"allow-folders-grants",
|
||||||
|
|||||||
@@ -13,6 +13,8 @@
|
|||||||
"allow-settings-write",
|
"allow-settings-write",
|
||||||
"allow-settings-migrate",
|
"allow-settings-migrate",
|
||||||
"allow-features-legacy",
|
"allow-features-legacy",
|
||||||
|
"allow-pty-running",
|
||||||
|
"allow-pty-profiles",
|
||||||
"core:default",
|
"core:default",
|
||||||
"core:window:allow-close",
|
"core:window:allow-close",
|
||||||
"core:window:allow-minimize",
|
"core:window:allow-minimize",
|
||||||
@@ -43,12 +45,14 @@
|
|||||||
"allow-browser-engine-remove",
|
"allow-browser-engine-remove",
|
||||||
"allow-completion-request",
|
"allow-completion-request",
|
||||||
"allow-completion-cancel",
|
"allow-completion-cancel",
|
||||||
"allow-backgrounds-choose-folder",
|
"allow-background-choose-folder",
|
||||||
"allow-backgrounds-default-folder",
|
"allow-background-folder",
|
||||||
"allow-backgrounds-list",
|
"allow-background-clear-folder",
|
||||||
"allow-backgrounds-read",
|
"allow-background-list",
|
||||||
"allow-backgrounds-read-image-settings",
|
"allow-background-read",
|
||||||
"allow-backgrounds-write-image-settings",
|
"allow-background-read-sidecar",
|
||||||
|
"allow-background-write-sidecar",
|
||||||
|
"allow-background-migrate",
|
||||||
"allow-folders-choose",
|
"allow-folders-choose",
|
||||||
"allow-folders-picture",
|
"allow-folders-picture",
|
||||||
"allow-folders-grants",
|
"allow-folders-grants",
|
||||||
|
|||||||
@@ -0,0 +1,11 @@
|
|||||||
|
# Automatically generated - DO NOT EDIT!
|
||||||
|
|
||||||
|
[[permission]]
|
||||||
|
identifier = "allow-background-choose-folder"
|
||||||
|
description = "Enables the background_choose_folder command without any pre-configured scope."
|
||||||
|
commands.allow = ["background_choose_folder"]
|
||||||
|
|
||||||
|
[[permission]]
|
||||||
|
identifier = "deny-background-choose-folder"
|
||||||
|
description = "Denies the background_choose_folder command without any pre-configured scope."
|
||||||
|
commands.deny = ["background_choose_folder"]
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
# Automatically generated - DO NOT EDIT!
|
||||||
|
|
||||||
|
[[permission]]
|
||||||
|
identifier = "allow-background-clear-folder"
|
||||||
|
description = "Enables the background_clear_folder command without any pre-configured scope."
|
||||||
|
commands.allow = ["background_clear_folder"]
|
||||||
|
|
||||||
|
[[permission]]
|
||||||
|
identifier = "deny-background-clear-folder"
|
||||||
|
description = "Denies the background_clear_folder command without any pre-configured scope."
|
||||||
|
commands.deny = ["background_clear_folder"]
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
# Automatically generated - DO NOT EDIT!
|
||||||
|
|
||||||
|
[[permission]]
|
||||||
|
identifier = "allow-background-folder"
|
||||||
|
description = "Enables the background_folder command without any pre-configured scope."
|
||||||
|
commands.allow = ["background_folder"]
|
||||||
|
|
||||||
|
[[permission]]
|
||||||
|
identifier = "deny-background-folder"
|
||||||
|
description = "Denies the background_folder command without any pre-configured scope."
|
||||||
|
commands.deny = ["background_folder"]
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
# Automatically generated - DO NOT EDIT!
|
||||||
|
|
||||||
|
[[permission]]
|
||||||
|
identifier = "allow-background-list"
|
||||||
|
description = "Enables the background_list command without any pre-configured scope."
|
||||||
|
commands.allow = ["background_list"]
|
||||||
|
|
||||||
|
[[permission]]
|
||||||
|
identifier = "deny-background-list"
|
||||||
|
description = "Denies the background_list command without any pre-configured scope."
|
||||||
|
commands.deny = ["background_list"]
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
# Automatically generated - DO NOT EDIT!
|
||||||
|
|
||||||
|
[[permission]]
|
||||||
|
identifier = "allow-background-migrate"
|
||||||
|
description = "Enables the background_migrate command without any pre-configured scope."
|
||||||
|
commands.allow = ["background_migrate"]
|
||||||
|
|
||||||
|
[[permission]]
|
||||||
|
identifier = "deny-background-migrate"
|
||||||
|
description = "Denies the background_migrate command without any pre-configured scope."
|
||||||
|
commands.deny = ["background_migrate"]
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
# Automatically generated - DO NOT EDIT!
|
||||||
|
|
||||||
|
[[permission]]
|
||||||
|
identifier = "allow-background-read"
|
||||||
|
description = "Enables the background_read command without any pre-configured scope."
|
||||||
|
commands.allow = ["background_read"]
|
||||||
|
|
||||||
|
[[permission]]
|
||||||
|
identifier = "deny-background-read"
|
||||||
|
description = "Denies the background_read command without any pre-configured scope."
|
||||||
|
commands.deny = ["background_read"]
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
# Automatically generated - DO NOT EDIT!
|
||||||
|
|
||||||
|
[[permission]]
|
||||||
|
identifier = "allow-background-read-sidecar"
|
||||||
|
description = "Enables the background_read_sidecar command without any pre-configured scope."
|
||||||
|
commands.allow = ["background_read_sidecar"]
|
||||||
|
|
||||||
|
[[permission]]
|
||||||
|
identifier = "deny-background-read-sidecar"
|
||||||
|
description = "Denies the background_read_sidecar command without any pre-configured scope."
|
||||||
|
commands.deny = ["background_read_sidecar"]
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
# Automatically generated - DO NOT EDIT!
|
||||||
|
|
||||||
|
[[permission]]
|
||||||
|
identifier = "allow-background-write-sidecar"
|
||||||
|
description = "Enables the background_write_sidecar command without any pre-configured scope."
|
||||||
|
commands.allow = ["background_write_sidecar"]
|
||||||
|
|
||||||
|
[[permission]]
|
||||||
|
identifier = "deny-background-write-sidecar"
|
||||||
|
description = "Denies the background_write_sidecar command without any pre-configured scope."
|
||||||
|
commands.deny = ["background_write_sidecar"]
|
||||||
@@ -1,11 +0,0 @@
|
|||||||
# Automatically generated - DO NOT EDIT!
|
|
||||||
|
|
||||||
[[permission]]
|
|
||||||
identifier = "allow-backgrounds-choose-folder"
|
|
||||||
description = "Enables the backgrounds_choose_folder command without any pre-configured scope."
|
|
||||||
commands.allow = ["backgrounds_choose_folder"]
|
|
||||||
|
|
||||||
[[permission]]
|
|
||||||
identifier = "deny-backgrounds-choose-folder"
|
|
||||||
description = "Denies the backgrounds_choose_folder command without any pre-configured scope."
|
|
||||||
commands.deny = ["backgrounds_choose_folder"]
|
|
||||||
@@ -1,11 +0,0 @@
|
|||||||
# Automatically generated - DO NOT EDIT!
|
|
||||||
|
|
||||||
[[permission]]
|
|
||||||
identifier = "allow-backgrounds-default-folder"
|
|
||||||
description = "Enables the backgrounds_default_folder command without any pre-configured scope."
|
|
||||||
commands.allow = ["backgrounds_default_folder"]
|
|
||||||
|
|
||||||
[[permission]]
|
|
||||||
identifier = "deny-backgrounds-default-folder"
|
|
||||||
description = "Denies the backgrounds_default_folder command without any pre-configured scope."
|
|
||||||
commands.deny = ["backgrounds_default_folder"]
|
|
||||||
@@ -1,11 +0,0 @@
|
|||||||
# Automatically generated - DO NOT EDIT!
|
|
||||||
|
|
||||||
[[permission]]
|
|
||||||
identifier = "allow-backgrounds-list"
|
|
||||||
description = "Enables the backgrounds_list command without any pre-configured scope."
|
|
||||||
commands.allow = ["backgrounds_list"]
|
|
||||||
|
|
||||||
[[permission]]
|
|
||||||
identifier = "deny-backgrounds-list"
|
|
||||||
description = "Denies the backgrounds_list command without any pre-configured scope."
|
|
||||||
commands.deny = ["backgrounds_list"]
|
|
||||||
@@ -1,11 +0,0 @@
|
|||||||
# Automatically generated - DO NOT EDIT!
|
|
||||||
|
|
||||||
[[permission]]
|
|
||||||
identifier = "allow-backgrounds-read"
|
|
||||||
description = "Enables the backgrounds_read command without any pre-configured scope."
|
|
||||||
commands.allow = ["backgrounds_read"]
|
|
||||||
|
|
||||||
[[permission]]
|
|
||||||
identifier = "deny-backgrounds-read"
|
|
||||||
description = "Denies the backgrounds_read command without any pre-configured scope."
|
|
||||||
commands.deny = ["backgrounds_read"]
|
|
||||||
@@ -1,11 +0,0 @@
|
|||||||
# Automatically generated - DO NOT EDIT!
|
|
||||||
|
|
||||||
[[permission]]
|
|
||||||
identifier = "allow-backgrounds-read-image-settings"
|
|
||||||
description = "Enables the backgrounds_read_image_settings command without any pre-configured scope."
|
|
||||||
commands.allow = ["backgrounds_read_image_settings"]
|
|
||||||
|
|
||||||
[[permission]]
|
|
||||||
identifier = "deny-backgrounds-read-image-settings"
|
|
||||||
description = "Denies the backgrounds_read_image_settings command without any pre-configured scope."
|
|
||||||
commands.deny = ["backgrounds_read_image_settings"]
|
|
||||||
@@ -1,11 +0,0 @@
|
|||||||
# Automatically generated - DO NOT EDIT!
|
|
||||||
|
|
||||||
[[permission]]
|
|
||||||
identifier = "allow-backgrounds-write-image-settings"
|
|
||||||
description = "Enables the backgrounds_write_image_settings command without any pre-configured scope."
|
|
||||||
commands.allow = ["backgrounds_write_image_settings"]
|
|
||||||
|
|
||||||
[[permission]]
|
|
||||||
identifier = "deny-backgrounds-write-image-settings"
|
|
||||||
description = "Denies the backgrounds_write_image_settings command without any pre-configured scope."
|
|
||||||
commands.deny = ["backgrounds_write_image_settings"]
|
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
# Automatically generated - DO NOT EDIT!
|
||||||
|
|
||||||
|
[[permission]]
|
||||||
|
identifier = "allow-pty-running"
|
||||||
|
description = "Enables the pty_running command without any pre-configured scope."
|
||||||
|
commands.allow = ["pty_running"]
|
||||||
|
|
||||||
|
[[permission]]
|
||||||
|
identifier = "deny-pty-running"
|
||||||
|
description = "Denies the pty_running command without any pre-configured scope."
|
||||||
|
commands.deny = ["pty_running"]
|
||||||
+392
-302
@@ -1,99 +1,46 @@
|
|||||||
|
//! The image folder of the Background feature (`src/lib/features/background/`).
|
||||||
|
//!
|
||||||
|
//! The host keeps one folder in `background-folder.json` in the app data folder. Only the folder dialog
|
||||||
|
//! sets it, so the interface never sends a folder path. The commands read the image files directly in
|
||||||
|
//! that folder and the sidecar file `.runestone-backgrounds.json` with the per-image settings.
|
||||||
|
//! They use the rules of the plugin folder grants (`folders.rs`): plain file names only, no links,
|
||||||
|
//! raster images up to 64 MiB, a sidecar up to 1 MiB, and at most 10,000 files in the folder.
|
||||||
|
|
||||||
use crate::error::{Error, Result};
|
use crate::error::{Error, Result};
|
||||||
|
use crate::folders;
|
||||||
use crate::fsutil::{self, is_link};
|
use crate::fsutil::{self, is_link};
|
||||||
use crate::plugins::PluginState;
|
use serde::{Deserialize, Serialize};
|
||||||
use base64::Engine;
|
|
||||||
use serde::Serialize;
|
|
||||||
use std::fs;
|
use std::fs;
|
||||||
use std::path::{Component, Path, PathBuf};
|
use std::path::{Path, PathBuf};
|
||||||
|
use std::sync::Mutex;
|
||||||
use tauri::{AppHandle, Manager, Window};
|
use tauri::{AppHandle, Manager, Window};
|
||||||
use tauri_plugin_dialog::DialogExt;
|
use tauri_plugin_dialog::DialogExt;
|
||||||
|
|
||||||
const IMAGE_LIMIT: u64 = 50 * 1024 * 1024;
|
const FOLDER_FILE: &str = "background-folder.json";
|
||||||
const SETTINGS_LIMIT: u64 = 1024 * 1024;
|
const SIDECAR: &str = ".runestone-backgrounds.json";
|
||||||
const SETTINGS_FILE: &str = ".runestone-backgrounds.json";
|
/// The old plugin whose folder grant the migration takes.
|
||||||
|
const LEGACY_PLUGIN: &str = "runestone.bg-slideshow";
|
||||||
|
const FOLDER_FILE_LIMIT: u64 = 64 * 1024;
|
||||||
|
|
||||||
#[derive(Debug, Serialize)]
|
/// Serializes changes to the folder file.
|
||||||
pub struct BackgroundFile {
|
static LOCK: Mutex<()> = Mutex::new(());
|
||||||
name: String,
|
|
||||||
|
#[derive(Debug, Serialize, Deserialize)]
|
||||||
|
struct FolderFile {
|
||||||
|
schema: u32,
|
||||||
|
path: PathBuf,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The folder file and the plugin data of one app data folder.
|
||||||
fn require_plugin(app: &AppHandle, label: &str, id: &str) -> Result<()> {
|
struct Host {
|
||||||
app.state::<PluginState>().require_lease(app, label, id)
|
data: PathBuf,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Check the lease on a blocking worker, because the plugin lock can wait for package work.
|
fn raster(name: &str) -> bool {
|
||||||
async fn check_plugin(app: &AppHandle, window: &Window, id: &str) -> Result<()> {
|
|
||||||
let (app, label, id) = (app.clone(), window.label().to_owned(), id.to_owned());
|
|
||||||
tauri::async_runtime::spawn_blocking(move || require_plugin(&app, &label, &id)).await?
|
|
||||||
}
|
|
||||||
|
|
||||||
fn folder_root(folder: &Path) -> Result<PathBuf> {
|
|
||||||
if !folder.is_absolute()
|
|
||||||
|| folder
|
|
||||||
.components()
|
|
||||||
.any(|part| matches!(part, Component::ParentDir))
|
|
||||||
{
|
|
||||||
return Err("Supply an absolute background folder path without parent segments.".into());
|
|
||||||
}
|
|
||||||
let root = dunce::canonicalize(folder)?;
|
|
||||||
if !root.is_dir() {
|
|
||||||
return Err("The background folder does not exist.".into());
|
|
||||||
}
|
|
||||||
Ok(root)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn supported(name: &str) -> bool {
|
|
||||||
Path::new(name)
|
Path::new(name)
|
||||||
.extension()
|
.extension()
|
||||||
.and_then(|extension| extension.to_str())
|
.and_then(|extension| extension.to_str())
|
||||||
.is_some_and(|extension| {
|
.is_some_and(|extension| matches!(extension.to_ascii_lowercase().as_str(), "png" | "jpg" | "jpeg" | "gif" | "webp"))
|
||||||
matches!(
|
|
||||||
extension.to_ascii_lowercase().as_str(),
|
|
||||||
"png" | "jpg" | "jpeg" | "gif" | "webp"
|
|
||||||
)
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
fn image_path(root: &Path, name: &str) -> Result<PathBuf> {
|
|
||||||
if name.is_empty()
|
|
||||||
|| name.contains(['/', '\\', ':'])
|
|
||||||
|| name.ends_with(['.', ' '])
|
|
||||||
|| !supported(name)
|
|
||||||
|| Path::new(name).components().count() != 1
|
|
||||||
|| !matches!(
|
|
||||||
Path::new(name).components().next(),
|
|
||||||
Some(Component::Normal(_))
|
|
||||||
)
|
|
||||||
{
|
|
||||||
return Err("Supply one PNG, JPEG, GIF, or WebP filename.".into());
|
|
||||||
}
|
|
||||||
let path = root.join(name);
|
|
||||||
let metadata = fs::symlink_metadata(&path)?;
|
|
||||||
if !metadata.is_file() || is_link(&metadata) {
|
|
||||||
return Err("Background images must be ordinary files, not links.".into());
|
|
||||||
}
|
|
||||||
let resolved = dunce::canonicalize(&path)?;
|
|
||||||
if resolved.parent() != Some(root) {
|
|
||||||
return Err("The background image is outside its folder.".into());
|
|
||||||
}
|
|
||||||
Ok(path)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn list_images(folder: &Path) -> Result<Vec<BackgroundFile>> {
|
|
||||||
let root = folder_root(folder)?;
|
|
||||||
let mut images = Vec::new();
|
|
||||||
for entry in fs::read_dir(&root)? {
|
|
||||||
let entry = entry?;
|
|
||||||
let Some(name) = entry.file_name().to_str().map(str::to_owned) else {
|
|
||||||
continue;
|
|
||||||
};
|
|
||||||
if supported(&name) && image_path(&root, &name).is_ok() {
|
|
||||||
images.push(BackgroundFile { name });
|
|
||||||
}
|
|
||||||
}
|
|
||||||
images.sort_by(|a, b| a.name.cmp(&b.name));
|
|
||||||
Ok(images)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn raster_signature(bytes: &[u8]) -> bool {
|
fn raster_signature(bytes: &[u8]) -> bool {
|
||||||
@@ -104,176 +51,205 @@ fn raster_signature(bytes: &[u8]) -> bool {
|
|||||||
|| (bytes.len() >= 12 && bytes.starts_with(b"RIFF") && &bytes[8..12] == b"WEBP")
|
|| (bytes.len() >= 12 && bytes.starts_with(b"RIFF") && &bytes[8..12] == b"WEBP")
|
||||||
}
|
}
|
||||||
|
|
||||||
fn read_image(folder: &Path, name: &str) -> Result<Vec<u8>> {
|
/// Read a small JSON file. A missing file gives `None`. A link or a folder is an error.
|
||||||
let root = folder_root(folder)?;
|
fn read_json<T: for<'de> Deserialize<'de>>(path: &Path, limit: u64) -> Result<Option<T>> {
|
||||||
let path = image_path(&root, name)?;
|
let metadata = match fs::symlink_metadata(path) {
|
||||||
// Open the entry itself so a replaced link cannot redirect the read.
|
Ok(metadata) => metadata,
|
||||||
let file = fsutil::open_entry(&path)?;
|
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
|
||||||
let metadata = file.metadata()?;
|
Err(error) => return Err(error.into()),
|
||||||
if !metadata.is_file() || is_link(&metadata) {
|
|
||||||
return Err("Background images must be ordinary files, not links.".into());
|
|
||||||
}
|
|
||||||
if metadata.len() > IMAGE_LIMIT {
|
|
||||||
return Err("The background image exceeds 50 MiB.".into());
|
|
||||||
}
|
|
||||||
image_path(&root, name)?;
|
|
||||||
let Some(bytes) = fsutil::read_to_limit(file, IMAGE_LIMIT)? else {
|
|
||||||
return Err("The background image exceeds 50 MiB.".into());
|
|
||||||
};
|
};
|
||||||
|
if !metadata.is_file() || is_link(&metadata) {
|
||||||
|
return Err(Error::new(format!("{} must be an ordinary file.", path.display())));
|
||||||
|
}
|
||||||
|
let Some(bytes) = fsutil::read_to_limit(fsutil::open_entry(path)?, limit)? else {
|
||||||
|
return Err(Error::new(format!("{} is too large.", path.display())));
|
||||||
|
};
|
||||||
|
Ok(Some(serde_json::from_slice(&bytes)?))
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Host {
|
||||||
|
fn file(&self) -> PathBuf {
|
||||||
|
self.data.join(FOLDER_FILE)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn stored(&self) -> Result<Option<PathBuf>> {
|
||||||
|
let Some(file) = read_json::<FolderFile>(&self.file(), FOLDER_FILE_LIMIT)? else { return Ok(None) };
|
||||||
|
if file.schema != 1 {
|
||||||
|
return Err("Unknown background folder file schema.".into());
|
||||||
|
}
|
||||||
|
Ok(Some(file.path))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn save(&self, path: &Path) -> Result<()> {
|
||||||
|
fs::create_dir_all(&self.data)?;
|
||||||
|
let bytes = serde_json::to_vec_pretty(&FolderFile { schema: 1, path: path.to_path_buf() })?;
|
||||||
|
let temp = self.data.join(format!("{FOLDER_FILE}.{}.tmp", uuid::Uuid::new_v4()));
|
||||||
|
Ok(fsutil::replace_file(&self.file(), &temp, &bytes)?)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Keep `folder` as the background folder. It must be an existing folder, not a whole drive.
|
||||||
|
fn choose(&self, folder: &Path) -> Result<String> {
|
||||||
|
let root = folders::granted_root(folder)?;
|
||||||
|
let _lock = LOCK.lock()?;
|
||||||
|
self.save(&root)?;
|
||||||
|
Ok(root.to_string_lossy().into_owned())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The kept folder for display, or `None`.
|
||||||
|
fn folder(&self) -> Result<Option<String>> {
|
||||||
|
Ok(self.stored()?.map(|path| path.to_string_lossy().into_owned()))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn clear(&self) -> Result<()> {
|
||||||
|
let _lock = LOCK.lock()?;
|
||||||
|
match fs::remove_file(self.file()) {
|
||||||
|
Err(error) if error.kind() != std::io::ErrorKind::NotFound => Err(error.into()),
|
||||||
|
_ => Ok(()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The kept folder, still an ordinary folder at the same resolved path.
|
||||||
|
/// A folder that became a link or a file does not redirect the access.
|
||||||
|
fn root(&self) -> Result<PathBuf> {
|
||||||
|
let path = self.stored()?.ok_or_else(|| Error::new("Choose a background folder first."))?;
|
||||||
|
let metadata = fs::symlink_metadata(&path).map_err(|_| Error::new("The background folder is missing. Choose the folder again."))?;
|
||||||
|
if !metadata.is_dir() || is_link(&metadata) || dunce::canonicalize(&path)? != path {
|
||||||
|
return Err("The background folder changed into a link or a file. Choose the folder again.".into());
|
||||||
|
}
|
||||||
|
Ok(path)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The names of the raster images directly in the folder.
|
||||||
|
fn list(&self) -> Result<Vec<String>> {
|
||||||
|
Ok(folders::list_files(&self.root()?)?
|
||||||
|
.into_iter()
|
||||||
|
.map(|entry| entry.name)
|
||||||
|
.filter(|name| raster(name))
|
||||||
|
.collect())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn read(&self, name: &str) -> Result<Vec<u8>> {
|
||||||
|
if !raster(name) {
|
||||||
|
return Err("Supply one PNG, JPEG, GIF, or WebP file name.".into());
|
||||||
|
}
|
||||||
|
let bytes = folders::read_file(&self.root()?, name)?;
|
||||||
if !raster_signature(&bytes) {
|
if !raster_signature(&bytes) {
|
||||||
return Err("The file is not a supported raster image.".into());
|
return Err("The file is not a supported raster image.".into());
|
||||||
}
|
}
|
||||||
Ok(bytes)
|
Ok(bytes)
|
||||||
}
|
|
||||||
|
|
||||||
#[tauri::command]
|
|
||||||
pub async fn backgrounds_default_folder(
|
|
||||||
app: AppHandle,
|
|
||||||
window: Window,
|
|
||||||
id: String,
|
|
||||||
) -> Result<String> {
|
|
||||||
check_plugin(&app, &window, &id).await?;
|
|
||||||
let pictures = app.path().picture_dir()?;
|
|
||||||
let folder = pictures.join("RuneStone Backgrounds");
|
|
||||||
let created = folder.clone();
|
|
||||||
tauri::async_runtime::spawn_blocking(move || fs::create_dir_all(created)).await??;
|
|
||||||
check_plugin(&app, &window, &id).await?;
|
|
||||||
folder_root(&folder).map(|root| root.to_string_lossy().into_owned())
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tauri::command]
|
|
||||||
pub async fn backgrounds_choose_folder(
|
|
||||||
app: AppHandle,
|
|
||||||
window: Window,
|
|
||||||
id: String,
|
|
||||||
) -> Result<Option<String>> {
|
|
||||||
check_plugin(&app, &window, &id).await?;
|
|
||||||
let picker_app = app.clone();
|
|
||||||
let picker_window = window.clone();
|
|
||||||
let selected = tauri::async_runtime::spawn_blocking(move || {
|
|
||||||
picker_app
|
|
||||||
.dialog()
|
|
||||||
.file()
|
|
||||||
.set_parent(&picker_window)
|
|
||||||
.set_title("Choose background image folder")
|
|
||||||
.blocking_pick_folder()
|
|
||||||
})
|
|
||||||
.await?;
|
|
||||||
check_plugin(&app, &window, &id).await?;
|
|
||||||
selected
|
|
||||||
.map(|source| {
|
|
||||||
let path = source.into_path().map_err(Error::from_display)?;
|
|
||||||
folder_root(&path).map(|root| root.to_string_lossy().into_owned())
|
|
||||||
})
|
|
||||||
.transpose()
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tauri::command]
|
|
||||||
pub async fn backgrounds_list(
|
|
||||||
app: AppHandle,
|
|
||||||
window: Window,
|
|
||||||
id: String,
|
|
||||||
folder: String,
|
|
||||||
) -> Result<Vec<BackgroundFile>> {
|
|
||||||
check_plugin(&app, &window, &id).await?;
|
|
||||||
let result = tauri::async_runtime::spawn_blocking(move || list_images(Path::new(&folder)))
|
|
||||||
.await??;
|
|
||||||
check_plugin(&app, &window, &id).await?;
|
|
||||||
Ok(result)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tauri::command]
|
|
||||||
pub async fn backgrounds_read(
|
|
||||||
app: AppHandle,
|
|
||||||
window: Window,
|
|
||||||
id: String,
|
|
||||||
folder: String,
|
|
||||||
name: String,
|
|
||||||
) -> Result<String> {
|
|
||||||
check_plugin(&app, &window, &id).await?;
|
|
||||||
let result =
|
|
||||||
tauri::async_runtime::spawn_blocking(move || read_image(Path::new(&folder), &name))
|
|
||||||
.await??;
|
|
||||||
check_plugin(&app, &window, &id).await?;
|
|
||||||
Ok(base64::engine::general_purpose::STANDARD.encode(result))
|
|
||||||
}
|
|
||||||
|
|
||||||
fn read_image_settings(folder: &Path) -> Result<Option<String>> {
|
|
||||||
let root = folder_root(folder)?;
|
|
||||||
let path = root.join(SETTINGS_FILE);
|
|
||||||
let metadata = match fs::symlink_metadata(&path) {
|
|
||||||
Ok(metadata) => metadata,
|
|
||||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
|
|
||||||
Err(error) => return Err(Error::from(error)),
|
|
||||||
};
|
|
||||||
if !metadata.is_file() || is_link(&metadata) || metadata.len() > SETTINGS_LIMIT {
|
|
||||||
return Err("Image settings must be an ordinary file within 1 MiB.".into());
|
|
||||||
}
|
}
|
||||||
let file = fsutil::open_entry(&path)?;
|
|
||||||
let metadata = file.metadata()?;
|
|
||||||
if !metadata.is_file() || is_link(&metadata) {
|
|
||||||
return Err("Image settings must be an ordinary file, not a link.".into());
|
|
||||||
}
|
|
||||||
let Some(bytes) = fsutil::read_to_limit(file, SETTINGS_LIMIT)? else {
|
|
||||||
return Err("Image settings exceed 1 MiB.".into());
|
|
||||||
};
|
|
||||||
String::from_utf8(bytes).map(Some).map_err(Error::from)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn write_image_settings(folder: &Path, contents: &str, expected: Option<&str>) -> Result<()> {
|
fn read_sidecar(&self) -> Result<Option<String>> {
|
||||||
static WRITE_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
|
folders::read_sidecar(&self.root()?, SIDECAR)
|
||||||
let _lock = WRITE_LOCK.lock()?;
|
|
||||||
if contents.len() as u64 > SETTINGS_LIMIT {
|
|
||||||
return Err("Image settings exceed 1 MiB.".into());
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Save the per-image settings only if the file still holds `expected` (`None` when it does not exist).
|
||||||
|
fn write_sidecar(&self, contents: &str, expected: Option<&str>) -> Result<()> {
|
||||||
let value: serde_json::Value = serde_json::from_str(contents)?;
|
let value: serde_json::Value = serde_json::from_str(contents)?;
|
||||||
if value.get("schema").and_then(serde_json::Value::as_u64) != Some(1)
|
if value.get("schema").and_then(serde_json::Value::as_u64) != Some(1) || !value.get("images").is_some_and(serde_json::Value::is_object) {
|
||||||
|| !value.get("images").is_some_and(serde_json::Value::is_object)
|
|
||||||
{
|
|
||||||
return Err("Use image settings with schema 1 and an images object.".into());
|
return Err("Use image settings with schema 1 and an images object.".into());
|
||||||
}
|
}
|
||||||
let root = folder_root(folder)?;
|
folders::write_sidecar(&self.root()?, SIDECAR, contents, expected)
|
||||||
if read_image_settings(&root)?.as_deref() != expected {
|
|
||||||
return Err("Image settings changed. Reload them before saving.".into());
|
|
||||||
}
|
}
|
||||||
let path = root.join(SETTINGS_FILE);
|
|
||||||
if expected.is_some() {
|
/// Take the folder of the old Background Slideshow grant when the host has no folder yet.
|
||||||
fsutil::write_text(&path, contents, expected)
|
/// Returns the folder after the migration, or `None`. It changes no plugin file.
|
||||||
} else {
|
fn migrate(&self) -> Result<Option<String>> {
|
||||||
// Publish a complete new file without replacing a file created by another process.
|
let _lock = LOCK.lock()?;
|
||||||
let temp = root.join(format!(".runestone-backgrounds-{}.tmp", uuid::Uuid::new_v4()));
|
if let Some(path) = self.stored()? {
|
||||||
Ok(fsutil::create_file(&path, &temp, contents.as_bytes())?)
|
return Ok(Some(path.to_string_lossy().into_owned()));
|
||||||
|
}
|
||||||
|
let plugin_data = self.data.join("plugin-data");
|
||||||
|
let settings = plugin_data.join(LEGACY_PLUGIN).join("settings.json");
|
||||||
|
let Some(value) = read_json::<serde_json::Value>(&settings, 1024 * 1024).ok().flatten() else { return Ok(None) };
|
||||||
|
let Some(grant) = value.get("grant").and_then(serde_json::Value::as_str).filter(|grant| !grant.is_empty()) else { return Ok(None) };
|
||||||
|
let Ok(path) = folders::plugin_grant(&plugin_data, LEGACY_PLUGIN, grant) else { return Ok(None) };
|
||||||
|
self.save(&path)?;
|
||||||
|
Ok(Some(path.to_string_lossy().into_owned()))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn host(app: &AppHandle) -> Result<Host> {
|
||||||
|
Ok(Host { data: app.path().app_data_dir()? })
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Run `work` on a blocking worker, because the file system calls can wait.
|
||||||
|
async fn run<T: Send + 'static>(app: &AppHandle, work: impl FnOnce(Host) -> Result<T> + Send + 'static) -> Result<T> {
|
||||||
|
let host = host(app)?;
|
||||||
|
tauri::async_runtime::spawn_blocking(move || work(host)).await?
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Show the folder dialog and keep the chosen folder. Returns the folder for display, or `None` after Cancel.
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
pub async fn backgrounds_read_image_settings(app: AppHandle, window: Window, id: String, folder: String) -> Result<Option<String>> {
|
pub async fn background_choose_folder(app: AppHandle, window: Window, title: Option<String>) -> Result<Option<String>> {
|
||||||
check_plugin(&app, &window, &id).await?;
|
let (picker_app, picker_window) = (app.clone(), window.clone());
|
||||||
let result = tauri::async_runtime::spawn_blocking(move || read_image_settings(Path::new(&folder))).await??;
|
let title = title.filter(|title| !title.trim().is_empty() && title.len() <= 200).unwrap_or_else(|| "Choose the background folder".into());
|
||||||
check_plugin(&app, &window, &id).await?;
|
let selected = tauri::async_runtime::spawn_blocking(move || {
|
||||||
Ok(result)
|
picker_app.dialog().file().set_parent(&picker_window).set_title(title).blocking_pick_folder()
|
||||||
|
})
|
||||||
|
.await?;
|
||||||
|
let Some(selected) = selected else { return Ok(None) };
|
||||||
|
let folder = selected.into_path().map_err(Error::from_display)?;
|
||||||
|
run(&app, move |host| host.choose(&folder)).await.map(Some)
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
pub async fn backgrounds_write_image_settings(app: AppHandle, window: Window, id: String, folder: String, contents: String, expected: Option<String>) -> Result<()> {
|
pub async fn background_folder(app: AppHandle) -> Result<Option<String>> {
|
||||||
check_plugin(&app, &window, &id).await?;
|
run(&app, |host| host.folder()).await
|
||||||
// Check the lease again immediately before the write on the blocking worker.
|
}
|
||||||
tauri::async_runtime::spawn_blocking(move || {
|
|
||||||
require_plugin(&app, window.label(), &id)?;
|
#[tauri::command]
|
||||||
write_image_settings(Path::new(&folder), &contents, expected.as_deref())
|
pub async fn background_clear_folder(app: AppHandle) -> Result<()> {
|
||||||
}).await?
|
run(&app, |host| host.clear()).await
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn background_list(app: AppHandle) -> Result<Vec<String>> {
|
||||||
|
run(&app, |host| host.list()).await
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Return the bytes as an `ArrayBuffer`, not as JSON or base64 text.
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn background_read(app: AppHandle, name: String) -> Result<tauri::ipc::Response> {
|
||||||
|
Ok(tauri::ipc::Response::new(run(&app, move |host| host.read(&name)).await?))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn background_read_sidecar(app: AppHandle) -> Result<Option<String>> {
|
||||||
|
run(&app, |host| host.read_sidecar()).await
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn background_write_sidecar(app: AppHandle, contents: String, expected: Option<String>) -> Result<()> {
|
||||||
|
run(&app, move |host| host.write_sidecar(&contents, expected.as_deref())).await
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn background_migrate(app: AppHandle) -> Result<Option<String>> {
|
||||||
|
run(&app, |host| host.migrate()).await
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
|
use crate::folders::LIST_LIMIT;
|
||||||
|
|
||||||
|
const PNG: &[u8] = b"\x89PNG\r\n\x1a\n";
|
||||||
|
|
||||||
struct Fixture(PathBuf);
|
struct Fixture(PathBuf);
|
||||||
impl Fixture {
|
impl Fixture {
|
||||||
fn new() -> Self {
|
fn new() -> Self {
|
||||||
let root = std::env::temp_dir()
|
let root = std::env::temp_dir().join(format!("runestone-background-{}", uuid::Uuid::new_v4()));
|
||||||
.join(format!("runestone-backgrounds-{}", uuid::Uuid::new_v4()));
|
|
||||||
fs::create_dir(&root).unwrap();
|
fs::create_dir(&root).unwrap();
|
||||||
Self(root)
|
Self(dunce::canonicalize(root).unwrap())
|
||||||
|
}
|
||||||
|
fn folder(&self, name: &str) -> PathBuf {
|
||||||
|
let path = self.0.join(name);
|
||||||
|
fs::create_dir_all(&path).unwrap();
|
||||||
|
path
|
||||||
|
}
|
||||||
|
fn host(&self) -> Host {
|
||||||
|
Host { data: self.folder("app") }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
impl Drop for Fixture {
|
impl Drop for Fixture {
|
||||||
@@ -282,103 +258,217 @@ mod tests {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
/// Make a link, or return `false` when Windows does not allow links for this user.
|
||||||
fn image_settings_preserve_external_changes_and_validate_file_limits() {
|
fn link(original: &Path, link: &Path, folder: bool) -> bool {
|
||||||
let fixture = Fixture::new();
|
#[cfg(unix)]
|
||||||
let first = r#"{"schema":1,"images":{"portrait.png":{"fit":"blurred"}}}"#;
|
{
|
||||||
let next = r#"{"schema":1,"images":{}}"#;
|
let _ = folder;
|
||||||
assert_eq!(read_image_settings(&fixture.0).unwrap(), None);
|
std::os::unix::fs::symlink(original, link).unwrap();
|
||||||
write_image_settings(&fixture.0, first, None).unwrap();
|
true
|
||||||
assert_eq!(read_image_settings(&fixture.0).unwrap().as_deref(), Some(first));
|
}
|
||||||
assert!(write_image_settings(&fixture.0, next, None).is_err());
|
#[cfg(windows)]
|
||||||
assert!(write_image_settings(&fixture.0, next, Some("stale")).is_err());
|
{
|
||||||
assert_eq!(read_image_settings(&fixture.0).unwrap().as_deref(), Some(first));
|
let result = if folder { std::os::windows::fs::symlink_dir(original, link) } else { std::os::windows::fs::symlink_file(original, link) };
|
||||||
write_image_settings(&fixture.0, next, Some(first)).unwrap();
|
match result {
|
||||||
assert!(write_image_settings(&fixture.0, r#"{"schema":2,"images":{}}"#, Some(next)).is_err());
|
Ok(()) => true,
|
||||||
assert!(write_image_settings(&fixture.0, &"x".repeat(SETTINGS_LIMIT as usize + 1), Some(next)).is_err());
|
Err(error) if error.raw_os_error() == Some(windows_sys::Win32::Foundation::ERROR_PRIVILEGE_NOT_HELD as i32) => {
|
||||||
fs::File::create(fixture.0.join(SETTINGS_FILE)).unwrap().set_len(SETTINGS_LIMIT + 1).unwrap();
|
eprintln!("The link check requires Windows Developer Mode or the symbolic-link privilege.");
|
||||||
assert!(read_image_settings(&fixture.0).is_err());
|
false
|
||||||
|
}
|
||||||
|
Err(error) => panic!("{error}"),
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn listing_is_nonrecursive_and_filters_extensions() {
|
fn the_host_keeps_one_folder_until_it_is_cleared() {
|
||||||
let fixture = Fixture::new();
|
let fixture = Fixture::new();
|
||||||
fs::write(fixture.0.join("a.PNG"), b"\x89PNG\r\n\x1a\n").unwrap();
|
let images = fixture.folder("images");
|
||||||
fs::write(fixture.0.join("b.jpg"), b"\xff\xd8\xff").unwrap();
|
let other = fixture.folder("other");
|
||||||
fs::write(fixture.0.join("text.svg"), b"<svg />").unwrap();
|
let host = fixture.host();
|
||||||
fs::create_dir(fixture.0.join("nested.gif")).unwrap();
|
assert_eq!(host.folder().unwrap(), None);
|
||||||
fs::write(fixture.0.join("nested.gif/hidden.png"), b"png").unwrap();
|
assert!(host.list().unwrap_err().to_string().contains("Choose a background folder"));
|
||||||
let names: Vec<_> = list_images(&fixture.0)
|
assert_eq!(host.choose(&images).unwrap(), images.to_string_lossy());
|
||||||
.unwrap()
|
// A new host reads the kept folder, as after a restart.
|
||||||
.into_iter()
|
assert_eq!(fixture.host().folder().unwrap(), Some(images.to_string_lossy().into_owned()));
|
||||||
.map(|image| image.name)
|
host.choose(&other).unwrap();
|
||||||
.collect();
|
assert_eq!(host.folder().unwrap(), Some(other.to_string_lossy().into_owned()));
|
||||||
assert_eq!(names, vec!["a.PNG", "b.jpg"]);
|
host.clear().unwrap();
|
||||||
assert_eq!(
|
host.clear().unwrap();
|
||||||
read_image(&fixture.0, "a.PNG").unwrap(),
|
assert_eq!(host.folder().unwrap(), None);
|
||||||
b"\x89PNG\r\n\x1a\n"
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn reads_reject_traversal_invalid_images_and_oversized_files() {
|
fn the_chosen_folder_must_be_an_existing_folder() {
|
||||||
let fixture = Fixture::new();
|
let fixture = Fixture::new();
|
||||||
for name in [
|
let host = fixture.host();
|
||||||
"../escape.png",
|
let images = fixture.folder("images");
|
||||||
"nested/image.png",
|
assert!(host.choose(Path::new("relative")).is_err());
|
||||||
"nested\\image.png",
|
assert!(host.choose(&images.join("..").join("images")).is_err());
|
||||||
"C:\\image.png",
|
assert!(host.choose(&fixture.0.join("missing")).is_err());
|
||||||
"image.png:stream",
|
fs::write(fixture.0.join("file.txt"), "x").unwrap();
|
||||||
"image.svg",
|
assert!(host.choose(&fixture.0.join("file.txt")).is_err());
|
||||||
] {
|
let drive = images.ancestors().last().unwrap().to_path_buf();
|
||||||
assert!(read_image(&fixture.0, name).is_err(), "{name}");
|
assert!(host.choose(&drive).is_err());
|
||||||
}
|
assert_eq!(host.folder().unwrap(), None);
|
||||||
assert!(list_images(Path::new("relative")).is_err());
|
// A damaged folder file is an error, not a silent reset.
|
||||||
fs::write(fixture.0.join("invalid.png"), b"<svg />").unwrap();
|
fs::write(host.file(), "{damaged").unwrap();
|
||||||
assert!(read_image(&fixture.0, "invalid.png")
|
assert!(host.folder().is_err());
|
||||||
.unwrap_err()
|
fs::write(host.file(), r#"{"schema":2,"path":"C:\\"}"#).unwrap();
|
||||||
.to_string()
|
assert!(host.folder().is_err());
|
||||||
.contains("raster"));
|
|
||||||
let file = fs::File::create(fixture.0.join("large.png")).unwrap();
|
|
||||||
file.set_len(IMAGE_LIMIT + 1).unwrap();
|
|
||||||
assert!(read_image(&fixture.0, "large.png")
|
|
||||||
.unwrap_err()
|
|
||||||
.to_string()
|
|
||||||
.contains("50 MiB"));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn raster_types_are_recognized() {
|
fn the_listing_has_only_the_raster_files_directly_in_the_folder() {
|
||||||
for bytes in [
|
let fixture = Fixture::new();
|
||||||
b"\x89PNG\r\n\x1a\n".as_slice(),
|
let images = fixture.folder("images");
|
||||||
b"\xff\xd8\xff",
|
let host = fixture.host();
|
||||||
b"GIF87a",
|
host.choose(&images).unwrap();
|
||||||
b"GIF89a",
|
fs::write(images.join("b.PNG"), PNG).unwrap();
|
||||||
b"RIFF0000WEBP",
|
fs::write(images.join("a.jpg"), b"\xff\xd8\xff").unwrap();
|
||||||
] {
|
fs::write(images.join("c.webp"), b"RIFF0000WEBP").unwrap();
|
||||||
assert!(raster_signature(bytes));
|
fs::write(images.join("text.svg"), b"<svg />").unwrap();
|
||||||
|
fs::write(images.join("notes.md"), b"# notes").unwrap();
|
||||||
|
fs::write(images.join(SIDECAR), b"{}").unwrap();
|
||||||
|
fixture.folder("images/nested.gif");
|
||||||
|
fs::write(images.join("nested.gif/hidden.png"), PNG).unwrap();
|
||||||
|
assert_eq!(host.list().unwrap(), vec!["a.jpg", "b.PNG", "c.webp"]);
|
||||||
|
assert_eq!(host.read("b.PNG").unwrap(), PNG);
|
||||||
}
|
}
|
||||||
assert!(!raster_signature(b"RIFF0000WAVE"));
|
|
||||||
|
#[test]
|
||||||
|
fn reads_reject_other_names_other_types_and_large_files() {
|
||||||
|
let fixture = Fixture::new();
|
||||||
|
let images = fixture.folder("images");
|
||||||
|
fs::write(fixture.0.join("outside.png"), PNG).unwrap();
|
||||||
|
let host = fixture.host();
|
||||||
|
host.choose(&images).unwrap();
|
||||||
|
for name in ["../outside.png", "nested/image.png", "nested\\image.png", "C:\\image.png", "image.png:stream", "image.svg", "notes.md", "", "nul.png"] {
|
||||||
|
assert!(host.read(name).is_err(), "{name}");
|
||||||
|
}
|
||||||
|
fs::write(images.join("fake.png"), b"<svg />").unwrap();
|
||||||
|
assert!(host.read("fake.png").unwrap_err().to_string().contains("raster"));
|
||||||
|
fs::File::create(images.join("large.png")).unwrap().set_len(folders::READ_LIMIT + 1).unwrap();
|
||||||
|
assert!(host.read("large.png").unwrap_err().to_string().contains("64 MiB"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_listing_has_a_size_limit() {
|
||||||
|
let fixture = Fixture::new();
|
||||||
|
let images = fixture.folder("images");
|
||||||
|
let host = fixture.host();
|
||||||
|
host.choose(&images).unwrap();
|
||||||
|
for index in 0..=LIST_LIMIT {
|
||||||
|
fs::write(images.join(format!("{index}.png")), b"").unwrap();
|
||||||
|
}
|
||||||
|
assert!(host.list().unwrap_err().to_string().contains("10000"));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn links_cannot_escape_the_folder() {
|
fn links_cannot_escape_the_folder() {
|
||||||
let fixture = Fixture::new();
|
let fixture = Fixture::new();
|
||||||
let outside = Fixture::new();
|
let images = fixture.folder("images");
|
||||||
let original = outside.0.join("outside.png");
|
let outside = fixture.folder("outside");
|
||||||
fs::write(&original, b"\x89PNG\r\n\x1a\n").unwrap();
|
fs::write(outside.join("secret.png"), PNG).unwrap();
|
||||||
let link = fixture.0.join("link.png");
|
let host = fixture.host();
|
||||||
#[cfg(unix)]
|
host.choose(&images).unwrap();
|
||||||
std::os::unix::fs::symlink(&original, &link).unwrap();
|
if !link(&outside.join("secret.png"), &images.join("link.png"), false) {
|
||||||
#[cfg(windows)]
|
|
||||||
if let Err(error) = std::os::windows::fs::symlink_file(&original, &link) {
|
|
||||||
if error.raw_os_error() == Some(windows_sys::Win32::Foundation::ERROR_PRIVILEGE_NOT_HELD as i32) {
|
|
||||||
eprintln!("The link check requires Windows Developer Mode or the symbolic-link privilege.");
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
panic!("{error}");
|
assert!(host.list().unwrap().is_empty());
|
||||||
|
assert!(host.read("link.png").is_err());
|
||||||
|
// A kept folder that is replaced by a link loses its access.
|
||||||
|
let moved = fixture.folder("moved");
|
||||||
|
host.choose(&moved).unwrap();
|
||||||
|
fs::remove_dir(&moved).unwrap();
|
||||||
|
assert!(link(&outside, &moved, true));
|
||||||
|
assert!(host.list().unwrap_err().to_string().contains("Choose the folder again"));
|
||||||
}
|
}
|
||||||
assert!(list_images(&fixture.0).unwrap().is_empty());
|
|
||||||
assert!(read_image(&fixture.0, "link.png").is_err());
|
#[test]
|
||||||
|
fn the_sidecar_keeps_external_changes_and_needs_schema_one() {
|
||||||
|
let fixture = Fixture::new();
|
||||||
|
let images = fixture.folder("images");
|
||||||
|
let host = fixture.host();
|
||||||
|
host.choose(&images).unwrap();
|
||||||
|
let first = r#"{"schema":1,"images":{"portrait.png":{"fit":"blurred"}}}"#;
|
||||||
|
let next = r#"{"schema":1,"images":{}}"#;
|
||||||
|
assert_eq!(host.read_sidecar().unwrap(), None);
|
||||||
|
host.write_sidecar(first, None).unwrap();
|
||||||
|
assert_eq!(host.read_sidecar().unwrap().as_deref(), Some(first));
|
||||||
|
assert!(host.write_sidecar(next, None).is_err());
|
||||||
|
assert!(host.write_sidecar(next, Some("stale")).is_err());
|
||||||
|
host.write_sidecar(next, Some(first)).unwrap();
|
||||||
|
assert_eq!(fs::read_to_string(images.join(SIDECAR)).unwrap(), next);
|
||||||
|
for bad in [r#"{"schema":2,"images":{}}"#, r#"{"schema":1,"images":[]}"#, "not json"] {
|
||||||
|
assert!(host.write_sidecar(bad, Some(next)).is_err(), "{bad}");
|
||||||
|
}
|
||||||
|
assert!(host.write_sidecar(&format!(r#"{{"schema":1,"images":{{}},"x":"{}"}}"#, "x".repeat(folders::SIDECAR_LIMIT as usize)), Some(next)).is_err());
|
||||||
|
fs::File::create(images.join(SIDECAR)).unwrap().set_len(folders::SIDECAR_LIMIT + 1).unwrap();
|
||||||
|
assert!(host.read_sidecar().is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
fn seed_plugin(fixture: &Fixture, folder: &Path, settings: &str) -> String {
|
||||||
|
let grant = uuid::Uuid::new_v4().to_string();
|
||||||
|
let data = fixture.folder(&format!("app/plugin-data/{LEGACY_PLUGIN}"));
|
||||||
|
fs::write(data.join("folder-grants.json"), serde_json::to_vec(&serde_json::json!({ "schema": 1, "grants": [{ "id": grant, "path": folder }] })).unwrap()).unwrap();
|
||||||
|
fs::write(data.join("settings.json"), settings.replace("GRANT", &grant)).unwrap();
|
||||||
|
grant
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_migration_takes_the_folder_of_the_old_grant() {
|
||||||
|
let fixture = Fixture::new();
|
||||||
|
let images = fixture.folder("images");
|
||||||
|
seed_plugin(&fixture, &images, r#"{"grant":"GRANT","enabled":true}"#);
|
||||||
|
let data = fixture.0.join("app/plugin-data").join(LEGACY_PLUGIN);
|
||||||
|
let before = (fs::read(data.join("folder-grants.json")).unwrap(), fs::read(data.join("settings.json")).unwrap());
|
||||||
|
let host = fixture.host();
|
||||||
|
assert_eq!(host.migrate().unwrap(), Some(images.to_string_lossy().into_owned()));
|
||||||
|
assert_eq!(host.folder().unwrap(), Some(images.to_string_lossy().into_owned()));
|
||||||
|
assert_eq!((fs::read(data.join("folder-grants.json")).unwrap(), fs::read(data.join("settings.json")).unwrap()), before, "The migration changes no plugin file.");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_migration_keeps_an_existing_host_folder() {
|
||||||
|
let fixture = Fixture::new();
|
||||||
|
let images = fixture.folder("images");
|
||||||
|
let chosen = fixture.folder("chosen");
|
||||||
|
seed_plugin(&fixture, &images, r#"{"grant":"GRANT"}"#);
|
||||||
|
let host = fixture.host();
|
||||||
|
host.choose(&chosen).unwrap();
|
||||||
|
assert_eq!(host.migrate().unwrap(), Some(chosen.to_string_lossy().into_owned()));
|
||||||
|
assert_eq!(host.folder().unwrap(), Some(chosen.to_string_lossy().into_owned()));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_migration_without_a_usable_grant_keeps_no_folder() {
|
||||||
|
// No plugin data.
|
||||||
|
let fixture = Fixture::new();
|
||||||
|
assert_eq!(fixture.host().migrate().unwrap(), None);
|
||||||
|
// Settings without a grant, with an unknown grant, and with damaged JSON.
|
||||||
|
for settings in [r#"{"folder":"D:\\Pictures"}"#, r#"{"grant":"6f0c7a8e-5b1d-4c2e-9a3f-2d7b8e1c4a90"}"#, r#"{"grant":"not-a-uuid"}"#, "{damaged"] {
|
||||||
|
let fixture = Fixture::new();
|
||||||
|
let images = fixture.folder("images");
|
||||||
|
seed_plugin(&fixture, &images, settings);
|
||||||
|
let host = fixture.host();
|
||||||
|
assert_eq!(host.migrate().unwrap(), None, "{settings}");
|
||||||
|
assert_eq!(host.folder().unwrap(), None);
|
||||||
|
}
|
||||||
|
// A granted folder that no longer exists.
|
||||||
|
let fixture = Fixture::new();
|
||||||
|
let images = fixture.folder("images");
|
||||||
|
seed_plugin(&fixture, &images, r#"{"grant":"GRANT"}"#);
|
||||||
|
fs::remove_dir(&images).unwrap();
|
||||||
|
assert_eq!(fixture.host().migrate().unwrap(), None);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn raster_types_are_recognized() {
|
||||||
|
for bytes in [PNG, b"\xff\xd8\xff", b"GIF87a", b"GIF89a", b"RIFF0000WEBP"] {
|
||||||
|
assert!(raster_signature(bytes));
|
||||||
|
}
|
||||||
|
assert!(!raster_signature(b"RIFF0000WAVE"));
|
||||||
|
assert!(raster("A.JPEG") && raster("b.gif") && !raster("c.svg") && !raster("png"));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ use crate::error::{Error, Result};
|
|||||||
use crate::plugins::{legacy_packages, LegacyPackage};
|
use crate::plugins::{legacy_packages, LegacyPackage};
|
||||||
|
|
||||||
/// The packages that native features replace. A request for another ID fails.
|
/// The packages that native features replace. A request for another ID fails.
|
||||||
pub const LEGACY_PACKAGES: [&str; 1] = ["runestone.git"];
|
pub const LEGACY_PACKAGES: [&str; 5] = ["runestone.git", "runestone.bg-slideshow", "runestone.terminal", "runestone.pdf-viewer", "runestone.pm"];
|
||||||
|
|
||||||
fn check(ids: &[String]) -> Result<()> {
|
fn check(ids: &[String]) -> Result<()> {
|
||||||
if ids.len() > LEGACY_PACKAGES.len() {
|
if ids.len() > LEGACY_PACKAGES.len() {
|
||||||
@@ -33,10 +33,17 @@ mod tests {
|
|||||||
#[test]
|
#[test]
|
||||||
fn only_the_packages_of_native_features_are_read() {
|
fn only_the_packages_of_native_features_are_read() {
|
||||||
assert!(check(&["runestone.git".into()]).is_ok());
|
assert!(check(&["runestone.git".into()]).is_ok());
|
||||||
|
assert!(check(&["runestone.git".into(), "runestone.bg-slideshow".into()]).is_ok());
|
||||||
|
assert!(check(&["runestone.terminal".into()]).is_ok());
|
||||||
|
assert!(check(&["runestone.pdf-viewer".into()]).is_ok());
|
||||||
|
assert!(check(&["runestone.pm".into()]).is_ok());
|
||||||
|
assert!(check(&LEGACY_PACKAGES.map(String::from)).is_ok());
|
||||||
assert!(check(&[]).is_ok());
|
assert!(check(&[]).is_ok());
|
||||||
for id in ["runestone.csv-viewer", "../plugin-state", "runestone.git/..", ""] {
|
for id in ["runestone.csv-viewer", "../plugin-state", "runestone.git/..", ""] {
|
||||||
assert!(check(&[id.into()]).is_err(), "{id}");
|
assert!(check(&[id.into()]).is_err(), "{id}");
|
||||||
}
|
}
|
||||||
assert!(check(&["runestone.git".into(), "runestone.git".into()]).is_err());
|
let too_many = ["runestone.git", "runestone.bg-slideshow", "runestone.terminal", "runestone.pdf-viewer", "runestone.pm", "runestone.git"].map(String::from);
|
||||||
|
assert!(too_many.len() > LEGACY_PACKAGES.len());
|
||||||
|
assert!(check(&too_many).is_err());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+16
-10
@@ -18,9 +18,9 @@ use tauri_plugin_dialog::DialogExt;
|
|||||||
|
|
||||||
const GRANTS_FILE: &str = "folder-grants.json";
|
const GRANTS_FILE: &str = "folder-grants.json";
|
||||||
const GRANT_LIMIT: usize = 64;
|
const GRANT_LIMIT: usize = 64;
|
||||||
const READ_LIMIT: u64 = 64 * 1024 * 1024;
|
pub(crate) const READ_LIMIT: u64 = 64 * 1024 * 1024;
|
||||||
const SIDECAR_LIMIT: u64 = 1024 * 1024;
|
pub(crate) const SIDECAR_LIMIT: u64 = 1024 * 1024;
|
||||||
const LIST_LIMIT: usize = 10_000;
|
pub(crate) const LIST_LIMIT: usize = 10_000;
|
||||||
|
|
||||||
/// Serializes changes to grant files and sidecar files.
|
/// Serializes changes to grant files and sidecar files.
|
||||||
static LOCK: Mutex<()> = Mutex::new(());
|
static LOCK: Mutex<()> = Mutex::new(());
|
||||||
@@ -47,7 +47,7 @@ pub struct FolderGrant {
|
|||||||
|
|
||||||
#[derive(Debug, Serialize, PartialEq)]
|
#[derive(Debug, Serialize, PartialEq)]
|
||||||
pub struct FolderEntry {
|
pub struct FolderEntry {
|
||||||
name: String,
|
pub(crate) name: String,
|
||||||
size: u64,
|
size: u64,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -172,7 +172,7 @@ impl Grants {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Resolve a chosen folder. Reject relative paths, parent segments, files, and whole drives.
|
/// Resolve a chosen folder. Reject relative paths, parent segments, files, and whole drives.
|
||||||
fn granted_root(folder: &Path) -> Result<PathBuf> {
|
pub(crate) fn granted_root(folder: &Path) -> Result<PathBuf> {
|
||||||
if !folder.is_absolute() || folder.components().any(|part| matches!(part, Component::ParentDir)) {
|
if !folder.is_absolute() || folder.components().any(|part| matches!(part, Component::ParentDir)) {
|
||||||
return Err("Supply an absolute folder path without parent segments.".into());
|
return Err("Supply an absolute folder path without parent segments.".into());
|
||||||
}
|
}
|
||||||
@@ -200,7 +200,7 @@ fn file_path(root: &Path, name: &str) -> Result<PathBuf> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Open one ordinary file. Reject links, also a link that replaces the file after the check.
|
/// Open one ordinary file. Reject links, also a link that replaces the file after the check.
|
||||||
fn open_plain(root: &Path, path: &Path) -> Result<(fs::File, u64)> {
|
pub(crate) fn open_plain(root: &Path, path: &Path) -> Result<(fs::File, u64)> {
|
||||||
let metadata = fs::symlink_metadata(path)?;
|
let metadata = fs::symlink_metadata(path)?;
|
||||||
if !metadata.is_file() || is_link(&metadata) {
|
if !metadata.is_file() || is_link(&metadata) {
|
||||||
return Err("Granted folder access is limited to ordinary files, not links or folders.".into());
|
return Err("Granted folder access is limited to ordinary files, not links or folders.".into());
|
||||||
@@ -213,7 +213,7 @@ fn open_plain(root: &Path, path: &Path) -> Result<(fs::File, u64)> {
|
|||||||
Ok((file, opened.len()))
|
Ok((file, opened.len()))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn list_files(root: &Path) -> Result<Vec<FolderEntry>> {
|
pub(crate) fn list_files(root: &Path) -> Result<Vec<FolderEntry>> {
|
||||||
let mut entries = Vec::new();
|
let mut entries = Vec::new();
|
||||||
for entry in fs::read_dir(root)? {
|
for entry in fs::read_dir(root)? {
|
||||||
let entry = entry?;
|
let entry = entry?;
|
||||||
@@ -232,7 +232,7 @@ fn list_files(root: &Path) -> Result<Vec<FolderEntry>> {
|
|||||||
Ok(entries)
|
Ok(entries)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn read_file(root: &Path, name: &str) -> Result<Vec<u8>> {
|
pub(crate) fn read_file(root: &Path, name: &str) -> Result<Vec<u8>> {
|
||||||
let path = file_path(root, name)?;
|
let path = file_path(root, name)?;
|
||||||
let (file, size) = open_plain(root, &path)?;
|
let (file, size) = open_plain(root, &path)?;
|
||||||
if size > READ_LIMIT {
|
if size > READ_LIMIT {
|
||||||
@@ -251,7 +251,7 @@ fn sidecar_path(root: &Path, name: &str) -> Result<PathBuf> {
|
|||||||
file_path(root, name)
|
file_path(root, name)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn read_sidecar(root: &Path, name: &str) -> Result<Option<String>> {
|
pub(crate) fn read_sidecar(root: &Path, name: &str) -> Result<Option<String>> {
|
||||||
let path = sidecar_path(root, name)?;
|
let path = sidecar_path(root, name)?;
|
||||||
match fs::symlink_metadata(&path) {
|
match fs::symlink_metadata(&path) {
|
||||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
|
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
|
||||||
@@ -267,7 +267,7 @@ fn read_sidecar(root: &Path, name: &str) -> Result<Option<String>> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Save a sidecar only if it still holds `expected` (`None` when the file does not exist).
|
/// Save a sidecar only if it still holds `expected` (`None` when the file does not exist).
|
||||||
fn write_sidecar(root: &Path, name: &str, contents: &str, expected: Option<&str>) -> Result<()> {
|
pub(crate) fn write_sidecar(root: &Path, name: &str, contents: &str, expected: Option<&str>) -> Result<()> {
|
||||||
let path = sidecar_path(root, name)?;
|
let path = sidecar_path(root, name)?;
|
||||||
if contents.len() as u64 > SIDECAR_LIMIT {
|
if contents.len() as u64 > SIDECAR_LIMIT {
|
||||||
return Err("The sidecar file exceeds 1 MiB.".into());
|
return Err("The sidecar file exceeds 1 MiB.".into());
|
||||||
@@ -285,6 +285,12 @@ fn write_sidecar(root: &Path, name: &str, contents: &str, expected: Option<&str>
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The folder of one grant of `plugin` in the plugin data folder `data`, with the checks of a normal access.
|
||||||
|
/// The Background feature uses it to take the folder of the old Background Slideshow plugin. It changes no file.
|
||||||
|
pub(crate) fn plugin_grant(data: &Path, plugin: &str, id: &str) -> Result<PathBuf> {
|
||||||
|
Grants { data: data.to_path_buf() }.resolve(plugin, id)
|
||||||
|
}
|
||||||
|
|
||||||
fn grants(app: &AppHandle) -> Result<Grants> {
|
fn grants(app: &AppHandle) -> Result<Grants> {
|
||||||
Ok(Grants { data: app.path().app_data_dir()?.join("plugin-data") })
|
Ok(Grants { data: app.path().app_data_dir()?.join("plugin-data") })
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -38,12 +38,14 @@ pub fn run() {
|
|||||||
.manage(preferences::PreferencesState::default())
|
.manage(preferences::PreferencesState::default())
|
||||||
.manage(tab_transfer::TabTransferState::default())
|
.manage(tab_transfer::TabTransferState::default())
|
||||||
.invoke_handler(tauri::generate_handler![
|
.invoke_handler(tauri::generate_handler![
|
||||||
backgrounds::backgrounds_choose_folder,
|
backgrounds::background_choose_folder,
|
||||||
backgrounds::backgrounds_default_folder,
|
backgrounds::background_folder,
|
||||||
backgrounds::backgrounds_list,
|
backgrounds::background_clear_folder,
|
||||||
backgrounds::backgrounds_read,
|
backgrounds::background_list,
|
||||||
backgrounds::backgrounds_read_image_settings,
|
backgrounds::background_read,
|
||||||
backgrounds::backgrounds_write_image_settings,
|
backgrounds::background_read_sidecar,
|
||||||
|
backgrounds::background_write_sidecar,
|
||||||
|
backgrounds::background_migrate,
|
||||||
folders::folders_choose,
|
folders::folders_choose,
|
||||||
folders::folders_picture,
|
folders::folders_picture,
|
||||||
folders::folders_grants,
|
folders::folders_grants,
|
||||||
@@ -132,6 +134,7 @@ pub fn run() {
|
|||||||
pty::pty_profiles,
|
pty::pty_profiles,
|
||||||
pty::pty_new_window,
|
pty::pty_new_window,
|
||||||
pty::pty_dictation,
|
pty::pty_dictation,
|
||||||
|
pty::pty_running,
|
||||||
])
|
])
|
||||||
.build(tauri::generate_context!())
|
.build(tauri::generate_context!())
|
||||||
.expect("error while building tauri application")
|
.expect("error while building tauri application")
|
||||||
|
|||||||
@@ -20,8 +20,8 @@ use crate::fsutil;
|
|||||||
pub const FILE_NAME: &str = "settings.json";
|
pub const FILE_NAME: &str = "settings.json";
|
||||||
pub const SCHEMA: u64 = 1;
|
pub const SCHEMA: u64 = 1;
|
||||||
/// The known sections. `customThemesLegacy` keeps the original version 1 themes from before their conversion.
|
/// The known sections. `customThemesLegacy` keeps the original version 1 themes from before their conversion.
|
||||||
/// `features` holds the switches of the native features.
|
/// `features` holds the switches of the native features. `background` and `terminal` hold the settings of the Background and Terminal features.
|
||||||
pub const SECTIONS: [&str; 6] = ["general", "appearance", "customThemes", "customThemesLegacy", "language", "features"];
|
pub const SECTIONS: [&str; 9] = ["general", "appearance", "customThemes", "customThemesLegacy", "language", "features", "background", "terminal", "projectManagement"];
|
||||||
/// The appearance section can hold an image data URL of up to 3,000,000 characters.
|
/// 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 MAX_FILE_BYTES: usize = 8 * 1024 * 1024;
|
||||||
pub const CHANGED_EVENT: &str = "settings-changed";
|
pub const CHANGED_EVENT: &str = "settings-changed";
|
||||||
|
|||||||
+410
-103
@@ -1,24 +1,54 @@
|
|||||||
use std::collections::HashMap;
|
//! Shell sessions for the native Terminal feature of RuneStone (`src/lib/features/terminal/`).
|
||||||
|
|
||||||
|
use std::collections::{HashMap, VecDeque};
|
||||||
use std::io::{Read, Write};
|
use std::io::{Read, Write};
|
||||||
|
use std::sync::atomic::{AtomicU64, Ordering};
|
||||||
|
use std::sync::mpsc::{Receiver, RecvTimeoutError};
|
||||||
use std::sync::Mutex;
|
use std::sync::Mutex;
|
||||||
use std::thread;
|
use std::thread;
|
||||||
use std::path::{Path, PathBuf};
|
use std::path::{Path, PathBuf};
|
||||||
|
use std::time::{Duration, Instant};
|
||||||
|
|
||||||
use portable_pty::{native_pty_system, CommandBuilder, MasterPty, PtySize};
|
use portable_pty::{native_pty_system, CommandBuilder, MasterPty, PtySize};
|
||||||
use serde::Serialize;
|
use serde::Serialize;
|
||||||
use tauri::ipc::{Channel, InvokeResponseBody, JavaScriptChannelId};
|
use tauri::ipc::{Channel, InvokeResponseBody, JavaScriptChannelId};
|
||||||
use tauri::{AppHandle, Emitter, Manager, State};
|
use tauri::{AppHandle, Manager, State};
|
||||||
|
|
||||||
use crate::error::{Error, Result};
|
use crate::error::{Error, Result};
|
||||||
use crate::workspace::{current_root, WorkspaceState};
|
use crate::workspace::{current_root, WorkspaceState};
|
||||||
use crate::terminal_platform::find_executable;
|
use crate::terminal_platform::find_executable;
|
||||||
|
|
||||||
|
/// The largest output message in bytes.
|
||||||
|
const BATCH_BYTES: usize = 64 * 1024;
|
||||||
|
/// The longest time that output waits for more output before it goes to the webview.
|
||||||
|
const BATCH_WAIT: Duration = Duration::from_millis(8);
|
||||||
|
/// The number of retired page IDs that each window keeps.
|
||||||
|
const RETIRED_PAGES: usize = 16;
|
||||||
|
const NOT_OPEN: &str = "terminal is not open";
|
||||||
|
const RETIRED_PAGE: &str = "terminal page is no longer active";
|
||||||
|
|
||||||
pub struct PtyState {
|
pub struct PtyState {
|
||||||
inner: Mutex<HashMap<String, OpenPty>>,
|
inner: Mutex<Sessions>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Default)]
|
||||||
|
struct Sessions {
|
||||||
|
open: HashMap<String, OpenPty>,
|
||||||
|
/// The page IDs of each window, by window label.
|
||||||
|
pages: HashMap<String, Pages>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The page loads of one window. Each page load of the frontend makes a new page ID.
|
||||||
|
#[derive(Default)]
|
||||||
|
struct Pages {
|
||||||
|
current: String,
|
||||||
|
retired: VecDeque<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
struct OpenPty {
|
struct OpenPty {
|
||||||
owner: String,
|
owner: String,
|
||||||
|
/// A unique number for this session. A session ID can come back after a reload.
|
||||||
|
serial: u64,
|
||||||
integration_file: Option<PathBuf>,
|
integration_file: Option<PathBuf>,
|
||||||
master: Box<dyn MasterPty + Send>,
|
master: Box<dyn MasterPty + Send>,
|
||||||
writer: std::sync::Arc<Mutex<Box<dyn Write + Send>>>,
|
writer: std::sync::Arc<Mutex<Box<dyn Write + Send>>>,
|
||||||
@@ -33,12 +63,13 @@ impl Drop for OpenPty {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl PtyState {
|
impl PtyState {
|
||||||
/// Close the window's terminals. Remove them under the lock, then stop the shells outside it.
|
/// Close the window's terminals and forget its pages. Remove the terminals under the lock,
|
||||||
|
/// then stop the shells outside it.
|
||||||
pub fn close_window(&self, label: &str) {
|
pub fn close_window(&self, label: &str) {
|
||||||
let closed: Vec<OpenPty> = match self.inner.lock() {
|
let closed: Vec<OpenPty> = match self.inner.lock() {
|
||||||
Ok(mut sessions) => {
|
Ok(mut sessions) => {
|
||||||
let ids: Vec<String> = sessions.iter().filter(|(_, session)| session.owner == label).map(|(id, _)| id.clone()).collect();
|
sessions.pages.remove(label);
|
||||||
ids.iter().filter_map(|id| sessions.remove(id)).collect()
|
take_window(&mut sessions.open, label)
|
||||||
}
|
}
|
||||||
Err(_) => return,
|
Err(_) => return,
|
||||||
};
|
};
|
||||||
@@ -55,22 +86,51 @@ impl PtyState {
|
|||||||
|
|
||||||
pub fn new() -> Self {
|
pub fn new() -> Self {
|
||||||
Self {
|
Self {
|
||||||
inner: Mutex::new(HashMap::new()),
|
inner: Mutex::new(Sessions::default()),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone, Serialize)]
|
/// Remove the sessions of one window from the map. The caller stops them outside the lock.
|
||||||
pub struct PtyData {
|
fn take_window(open: &mut HashMap<String, OpenPty>, owner: &str) -> Vec<OpenPty> {
|
||||||
pub id: String,
|
let ids: Vec<String> = open.iter().filter(|(_, session)| session.owner == owner).map(|(id, _)| id.clone()).collect();
|
||||||
// xterm owns UTF-8 decoding so multibyte characters split across reads survive.
|
ids.iter().filter_map(|id| open.remove(id)).collect()
|
||||||
pub data: Vec<u8>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone, Serialize)]
|
/// The number of open sessions of all windows.
|
||||||
pub struct PtyExit {
|
fn running(pty: &PtyState) -> Result<usize> {
|
||||||
pub id: String,
|
Ok(pty.inner.lock().map_err(|_| Error::new("pty lock"))?.open.len())
|
||||||
pub code: Option<u32>,
|
}
|
||||||
|
|
||||||
|
/// A page ID has 1 to 64 ASCII letters, digits, and hyphens.
|
||||||
|
fn check_page(page: &str) -> Result<()> {
|
||||||
|
if page.is_empty() || page.len() > 64 || !page.chars().all(|c| c.is_ascii_alphanumeric() || c == '-') {
|
||||||
|
return Err(Error::new("Invalid terminal page ID"));
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Apply the page rule to an open request of the window `owner`. A new page is a reload of
|
||||||
|
/// the window. It retires the current page and returns the sessions of the earlier page.
|
||||||
|
/// The caller stops them outside the lock. A retired page gets an error, so a late request
|
||||||
|
/// of an old page cannot close the sessions of the new page.
|
||||||
|
fn enter_page(sessions: &mut Sessions, owner: &str, page: &str) -> Result<Vec<OpenPty>> {
|
||||||
|
let Some(pages) = sessions.pages.get_mut(owner) else {
|
||||||
|
sessions.pages.insert(owner.to_owned(), Pages { current: page.to_owned(), retired: VecDeque::new() });
|
||||||
|
return Ok(Vec::new());
|
||||||
|
};
|
||||||
|
if pages.current == page {
|
||||||
|
return Ok(Vec::new());
|
||||||
|
}
|
||||||
|
if pages.retired.iter().any(|retired| retired == page) {
|
||||||
|
return Err(Error::new(RETIRED_PAGE));
|
||||||
|
}
|
||||||
|
let earlier = std::mem::replace(&mut pages.current, page.to_owned());
|
||||||
|
pages.retired.push_back(earlier);
|
||||||
|
while pages.retired.len() > RETIRED_PAGES {
|
||||||
|
pages.retired.pop_front();
|
||||||
|
}
|
||||||
|
Ok(take_window(&mut sessions.open, owner))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The destination of the output and the exit status of one terminal session.
|
/// The destination of the output and the exit status of one terminal session.
|
||||||
@@ -79,24 +139,6 @@ trait PtyOutput: Send {
|
|||||||
fn exit(&self, code: Option<u32>);
|
fn exit(&self, code: Option<u32>);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Window events for the released Terminal plugin, which listens for `pty-data` and `pty-exit`.
|
|
||||||
/// The events go to the window that opened the session. A global `listen` in that window
|
|
||||||
/// receives them. Tauri 2 also delivers an addressed event to a global `listen` in other windows.
|
|
||||||
struct EventOutput {
|
|
||||||
app: AppHandle,
|
|
||||||
owner: String,
|
|
||||||
id: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl PtyOutput for EventOutput {
|
|
||||||
fn data(&self, bytes: &[u8]) {
|
|
||||||
let _ = self.app.emit_to(self.owner.as_str(), "pty-data", PtyData { id: self.id.clone(), data: bytes.to_vec() });
|
|
||||||
}
|
|
||||||
fn exit(&self, code: Option<u32>) {
|
|
||||||
let _ = self.app.emit_to(self.owner.as_str(), "pty-exit", PtyExit { id: self.id.clone(), code });
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A channel to the webview that opened the session. Output goes as raw bytes (an
|
/// A channel to the webview that opened the session. Output goes as raw bytes (an
|
||||||
/// `ArrayBuffer` in JavaScript). The exit status goes as `{ "exit": code }`.
|
/// `ArrayBuffer` in JavaScript). The exit status goes as `{ "exit": code }`.
|
||||||
struct ChannelOutput(Channel<InvokeResponseBody>);
|
struct ChannelOutput(Channel<InvokeResponseBody>);
|
||||||
@@ -110,23 +152,58 @@ impl PtyOutput for ChannelOutput {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Use the channel when the caller supplies one. Without a channel, use window events.
|
/// Read the PTY until EOF and send each read to `chunks`.
|
||||||
fn output(channel: Option<Channel<InvokeResponseBody>>, events: impl FnOnce() -> Box<dyn PtyOutput>) -> Box<dyn PtyOutput> {
|
fn read_chunks(mut reader: impl Read, chunks: std::sync::mpsc::Sender<Vec<u8>>) {
|
||||||
match channel {
|
let mut buf = vec![0u8; 16 * 1024];
|
||||||
Some(channel) => Box::new(ChannelOutput(channel)),
|
|
||||||
None => events(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Send the output until the reader reaches EOF. Then send the exit status.
|
|
||||||
fn pump(mut reader: impl Read, exit: std::sync::mpsc::Receiver<Option<u32>>, output: &dyn PtyOutput) {
|
|
||||||
let mut buf = [0u8; 4096];
|
|
||||||
loop {
|
loop {
|
||||||
match reader.read(&mut buf) {
|
match reader.read(&mut buf) {
|
||||||
Ok(0) | Err(_) => break,
|
Ok(0) | Err(_) => break,
|
||||||
Ok(n) => output.data(&buf[..n]),
|
Ok(n) => {
|
||||||
|
if chunks.send(buf[..n].to_vec()).is_err() { break; }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Join the output chunks into messages, then send the exit status. A message starts with
|
||||||
|
/// the first chunk that arrives. It collects more chunks until `wait` after that chunk or
|
||||||
|
/// until `max_bytes`. A chunk that does not fit starts the next message. A chunk larger than
|
||||||
|
/// `max_bytes` goes in parts. When the reader stops, the loop sends the rest of the output
|
||||||
|
/// and then the exit status.
|
||||||
|
fn pump(chunks: Receiver<Vec<u8>>, exit: Receiver<Option<u32>>, output: &dyn PtyOutput, max_bytes: usize, wait: Duration) {
|
||||||
|
let max_bytes = max_bytes.max(1);
|
||||||
|
let mut next: Option<Vec<u8>> = None;
|
||||||
|
loop {
|
||||||
|
let mut message = match next.take() {
|
||||||
|
Some(chunk) => chunk,
|
||||||
|
None => match chunks.recv() {
|
||||||
|
Ok(chunk) => chunk,
|
||||||
|
Err(_) => break,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
let deadline = Instant::now() + wait;
|
||||||
|
let mut ended = false;
|
||||||
|
while message.len() < max_bytes {
|
||||||
|
let now = Instant::now();
|
||||||
|
if now >= deadline { break; }
|
||||||
|
match chunks.recv_timeout(deadline - now) {
|
||||||
|
Ok(chunk) if message.len() + chunk.len() > max_bytes => {
|
||||||
|
next = Some(chunk);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
Ok(chunk) => message.extend(chunk),
|
||||||
|
Err(RecvTimeoutError::Timeout) => break,
|
||||||
|
Err(RecvTimeoutError::Disconnected) => {
|
||||||
|
ended = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for part in message.chunks(max_bytes) {
|
||||||
|
output.data(part);
|
||||||
|
}
|
||||||
|
if ended { break; }
|
||||||
|
}
|
||||||
output.exit(exit.recv().ok().flatten());
|
output.exit(exit.recv().ok().flatten());
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -246,7 +323,7 @@ fn spawn_shell(root: &Path, cols: u16, rows: u16, profile: Option<&str>, owner:
|
|||||||
integration_file = Some(rc);
|
integration_file = Some(rc);
|
||||||
}
|
}
|
||||||
// The cmd prompt cannot encode base64, so it reports the folder as plain text with `Cwd`.
|
// The cmd prompt cannot encode base64, so it reports the folder as plain text with `Cwd`.
|
||||||
// The Terminal plugin reads both `Cwd` (plain) and `RSCwd` (base64). A Windows path
|
// The Terminal feature reads both `Cwd` (plain) and `RSCwd` (base64). A Windows path
|
||||||
// cannot contain the escape or bell characters that end the sequence.
|
// cannot contain the escape or bell characters that end the sequence.
|
||||||
"cmd" => { cmd.args(["/D", "/K", "prompt $E]633;Cwd;$P$E\\$E]133;A$E\\$P$G$E]133;B$E\\"]); }
|
"cmd" => { cmd.args(["/D", "/K", "prompt $E]633;Cwd;$P$E\\$E]133;A$E\\$P$G$E]133;B$E\\"]); }
|
||||||
"node" => { cmd.args(["--inspect=127.0.0.1:0", "-i"]); }
|
"node" => { cmd.args(["--inspect=127.0.0.1:0", "-i"]); }
|
||||||
@@ -265,8 +342,10 @@ fn spawn_shell(root: &Path, cols: u16, rows: u16, profile: Option<&str>, owner:
|
|||||||
.spawn_command(cmd)
|
.spawn_command(cmd)
|
||||||
.map_err(Error::from_display)?;
|
.map_err(Error::from_display)?;
|
||||||
drop(pair.slave);
|
drop(pair.slave);
|
||||||
|
static NEXT_SERIAL: AtomicU64 = AtomicU64::new(0);
|
||||||
let session = OpenPty {
|
let session = OpenPty {
|
||||||
owner: owner.into(),
|
owner: owner.into(),
|
||||||
|
serial: NEXT_SERIAL.fetch_add(1, Ordering::Relaxed),
|
||||||
integration_file,
|
integration_file,
|
||||||
master: pair.master,
|
master: pair.master,
|
||||||
writer: std::sync::Arc::new(Mutex::new(writer)),
|
writer: std::sync::Arc::new(Mutex::new(writer)),
|
||||||
@@ -284,77 +363,103 @@ pub async fn pty_open(
|
|||||||
webview: tauri::Webview,
|
webview: tauri::Webview,
|
||||||
workspace: State<'_, WorkspaceState>,
|
workspace: State<'_, WorkspaceState>,
|
||||||
id: String,
|
id: String,
|
||||||
|
page: String,
|
||||||
cols: u16,
|
cols: u16,
|
||||||
rows: u16,
|
rows: u16,
|
||||||
cwd: String,
|
cwd: String,
|
||||||
profile: Option<String>,
|
profile: Option<String>,
|
||||||
directory: Option<String>,
|
directory: Option<String>,
|
||||||
channel: Option<JavaScriptChannelId>,
|
channel: JavaScriptChannelId,
|
||||||
) -> Result<()> {
|
) -> Result<()> {
|
||||||
|
check_page(&page)?;
|
||||||
let root = current_root(&workspace, window.label())?;
|
let root = current_root(&workspace, window.label())?;
|
||||||
if root.to_string_lossy() != cwd {
|
if root.to_string_lossy() != cwd {
|
||||||
return Err(Error::new("workspace changed before the terminal started"));
|
return Err(Error::new("workspace changed before the terminal started"));
|
||||||
}
|
}
|
||||||
let owner = window.label().to_owned();
|
let owner = window.label().to_owned();
|
||||||
// A session with a channel sends no `pty-data` or `pty-exit` events.
|
let output = ChannelOutput(channel.channel_on(webview));
|
||||||
let channel = channel.map(|channel| channel.channel_on(webview));
|
let request = OpenRequest { owner, page, id, cols, rows, profile, directory: directory.map(PathBuf::from).unwrap_or(root) };
|
||||||
tauri::async_runtime::spawn_blocking(move || open(app, owner, root, id, cols, rows, profile, directory, channel)).await?
|
tauri::async_runtime::spawn_blocking(move || open(app, request, output)).await?
|
||||||
}
|
}
|
||||||
|
|
||||||
#[allow(clippy::too_many_arguments)]
|
struct OpenRequest {
|
||||||
fn open(
|
|
||||||
app: AppHandle,
|
|
||||||
owner: String,
|
owner: String,
|
||||||
root: PathBuf,
|
page: String,
|
||||||
id: String,
|
id: String,
|
||||||
cols: u16,
|
cols: u16,
|
||||||
rows: u16,
|
rows: u16,
|
||||||
profile: Option<String>,
|
profile: Option<String>,
|
||||||
directory: Option<String>,
|
directory: PathBuf,
|
||||||
channel: Option<Channel<InvokeResponseBody>>,
|
}
|
||||||
) -> Result<()> {
|
|
||||||
|
/// Apply the page rule and start the shell under one lock, so two opens cannot race.
|
||||||
|
fn open(app: AppHandle, request: OpenRequest, output: impl PtyOutput + 'static) -> Result<()> {
|
||||||
let pty = app.state::<PtyState>();
|
let pty = app.state::<PtyState>();
|
||||||
|
let (left, started) = {
|
||||||
let mut guard = pty.inner.lock().map_err(|_| Error::new("pty lock"))?;
|
let mut guard = pty.inner.lock().map_err(|_| Error::new("pty lock"))?;
|
||||||
if guard.contains_key(&id) {
|
let left = enter_page(&mut guard, &request.owner, &request.page)?;
|
||||||
return Err(Error::new("terminal already exists"));
|
(left, start(&mut guard, &request))
|
||||||
}
|
};
|
||||||
let directory = directory.map(PathBuf::from).unwrap_or(root);
|
// A reload left these sessions. Stop their shells outside the lock.
|
||||||
if !directory.is_dir() { return Err(Error::new("Terminal working directory does not exist")); }
|
drop(left);
|
||||||
let (session, reader, mut child) = spawn_shell(&directory, cols, rows, profile.as_deref(), &owner)?;
|
let (serial, reader, mut child) = started?;
|
||||||
guard.insert(id.clone(), session);
|
|
||||||
drop(guard);
|
|
||||||
let (exit_tx, exit_rx) = std::sync::mpsc::channel();
|
let (exit_tx, exit_rx) = std::sync::mpsc::channel();
|
||||||
let wait_app = app.clone();
|
let wait_app = app.clone();
|
||||||
let wait_id = id.clone();
|
let wait_id = request.id;
|
||||||
thread::spawn(move || {
|
thread::spawn(move || {
|
||||||
let code = child.wait().ok().map(|status| status.exit_code());
|
let code = child.wait().ok().map(|status| status.exit_code());
|
||||||
// Close ConPTY after the shell exits so the output reader reaches EOF.
|
// Close ConPTY after the shell exits so the output reader reaches EOF.
|
||||||
|
// A later session can use the same ID, so remove only this session.
|
||||||
let session = wait_app
|
let session = wait_app
|
||||||
.state::<PtyState>()
|
.state::<PtyState>()
|
||||||
.inner
|
.inner
|
||||||
.lock()
|
.lock()
|
||||||
.ok()
|
.ok()
|
||||||
.and_then(|mut sessions| sessions.remove(&wait_id));
|
.and_then(|mut sessions| match sessions.open.get(&wait_id) {
|
||||||
|
Some(session) if session.serial == serial => sessions.open.remove(&wait_id),
|
||||||
|
_ => None,
|
||||||
|
});
|
||||||
drop(session);
|
drop(session);
|
||||||
let _ = exit_tx.send(code);
|
let _ = exit_tx.send(code);
|
||||||
});
|
});
|
||||||
let output = output(channel, || Box::new(EventOutput { app: app.clone(), owner, id }));
|
let (chunk_tx, chunk_rx) = std::sync::mpsc::channel();
|
||||||
thread::spawn(move || pump(reader, exit_rx, output.as_ref()));
|
thread::spawn(move || read_chunks(reader, chunk_tx));
|
||||||
|
thread::spawn(move || pump(chunk_rx, exit_rx, &output, BATCH_BYTES, BATCH_WAIT));
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Write input on a blocking worker. A shell that does not read its input can fill the pipe,
|
type StartedShell = (u64, Box<dyn Read + Send>, Box<dyn portable_pty::Child + Send + Sync>);
|
||||||
/// and the write then waits. The Terminal plugin waits for each write before the next one.
|
|
||||||
#[tauri::command]
|
/// Start the shell and insert its session. The caller holds the lock.
|
||||||
pub async fn pty_write(app: AppHandle, id: String, data: String) -> Result<()> {
|
fn start(sessions: &mut Sessions, request: &OpenRequest) -> Result<StartedShell> {
|
||||||
tauri::async_runtime::spawn_blocking(move || write(&app.state::<PtyState>(), &id, &data)).await?
|
if sessions.open.contains_key(&request.id) {
|
||||||
|
return Err(Error::new("terminal already exists"));
|
||||||
|
}
|
||||||
|
if !request.directory.is_dir() { return Err(Error::new("Terminal working directory does not exist")); }
|
||||||
|
let (session, reader, child) = spawn_shell(&request.directory, request.cols, request.rows, request.profile.as_deref(), &request.owner)?;
|
||||||
|
let serial = session.serial;
|
||||||
|
sessions.open.insert(request.id.clone(), session);
|
||||||
|
Ok((serial, reader, child))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn write(pty: &PtyState, id: &str, data: &str) -> Result<()> {
|
/// Find a session of the window `owner`. A session of another window gives the same error
|
||||||
|
/// as a missing session.
|
||||||
|
fn owned<'a>(sessions: &'a Sessions, owner: &str, id: &str) -> Result<&'a OpenPty> {
|
||||||
|
sessions.open.get(id).filter(|session| session.owner == owner).ok_or_else(|| Error::new(NOT_OPEN))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Write input on a blocking worker. A shell that does not read its input can fill the pipe,
|
||||||
|
/// and the write then waits. The Terminal feature waits for each write before the next one.
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn pty_write(app: AppHandle, window: tauri::Window, id: String, data: String) -> Result<()> {
|
||||||
|
let owner = window.label().to_owned();
|
||||||
|
tauri::async_runtime::spawn_blocking(move || write(&app.state::<PtyState>(), &owner, &id, &data)).await?
|
||||||
|
}
|
||||||
|
|
||||||
|
fn write(pty: &PtyState, owner: &str, id: &str, data: &str) -> Result<()> {
|
||||||
let writer = {
|
let writer = {
|
||||||
let guard = pty.inner.lock().map_err(|_| Error::new("pty lock"))?;
|
let guard = pty.inner.lock().map_err(|_| Error::new("pty lock"))?;
|
||||||
let session = guard.get(id).ok_or_else(|| Error::new("terminal is not open"))?;
|
owned(&guard, owner, id)?.writer.clone()
|
||||||
session.writer.clone()
|
|
||||||
};
|
};
|
||||||
// Other terminals stay usable while this write waits.
|
// Other terminals stay usable while this write waits.
|
||||||
let mut writer = writer.lock().map_err(|_| Error::new("pty writer lock"))?;
|
let mut writer = writer.lock().map_err(|_| Error::new("pty writer lock"))?;
|
||||||
@@ -366,10 +471,13 @@ fn write(pty: &PtyState, id: &str, data: &str) -> Result<()> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
pub fn pty_resize(pty: State<PtyState>, id: String, cols: u16, rows: u16) -> Result<()> {
|
pub fn pty_resize(pty: State<PtyState>, window: tauri::Window, id: String, cols: u16, rows: u16) -> Result<()> {
|
||||||
|
resize(&pty, window.label(), &id, cols, rows)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn resize(pty: &PtyState, owner: &str, id: &str, cols: u16, rows: u16) -> Result<()> {
|
||||||
let guard = pty.inner.lock().map_err(|_| Error::new("pty lock"))?;
|
let guard = pty.inner.lock().map_err(|_| Error::new("pty lock"))?;
|
||||||
let session = guard.get(&id).ok_or_else(|| Error::new("terminal is not open"))?;
|
owned(&guard, owner, id)?
|
||||||
session
|
|
||||||
.master
|
.master
|
||||||
.resize(PtySize {
|
.resize(PtySize {
|
||||||
rows: rows.max(2),
|
rows: rows.max(2),
|
||||||
@@ -382,19 +490,34 @@ pub fn pty_resize(pty: State<PtyState>, id: String, cols: u16, rows: u16) -> Res
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Stop a shell on a blocking worker. Closing a pseudo console can wait for its output.
|
/// Stop a shell on a blocking worker. Closing a pseudo console can wait for its output.
|
||||||
|
/// A missing session and a session of another window are not an error. Neither one closes.
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
pub async fn pty_close(app: AppHandle, id: String) -> Result<()> {
|
pub async fn pty_close(app: AppHandle, window: tauri::Window, id: String) -> Result<()> {
|
||||||
|
let owner = window.label().to_owned();
|
||||||
tauri::async_runtime::spawn_blocking(move || {
|
tauri::async_runtime::spawn_blocking(move || {
|
||||||
let pty = app.state::<PtyState>();
|
let session = close(&app.state::<PtyState>(), &owner, &id)?;
|
||||||
let mut guard = pty.inner.lock().map_err(|_| Error::new("pty lock"))?;
|
|
||||||
let session = guard.remove(&id);
|
|
||||||
drop(guard);
|
|
||||||
drop(session);
|
drop(session);
|
||||||
Ok(())
|
Ok(())
|
||||||
})
|
})
|
||||||
.await?
|
.await?
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Remove a session of the window `owner` under the lock. The caller stops it outside the lock.
|
||||||
|
fn close(pty: &PtyState, owner: &str, id: &str) -> Result<Option<OpenPty>> {
|
||||||
|
let mut guard = pty.inner.lock().map_err(|_| Error::new("pty lock"))?;
|
||||||
|
if owned(&guard, owner, id).is_err() {
|
||||||
|
return Ok(None);
|
||||||
|
}
|
||||||
|
Ok(guard.open.remove(id))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The number of open terminals of all windows. The Settings window asks before Terminal
|
||||||
|
/// goes off when shells run.
|
||||||
|
#[tauri::command]
|
||||||
|
pub fn pty_running(pty: State<PtyState>) -> Result<usize> {
|
||||||
|
running(&pty)
|
||||||
|
}
|
||||||
|
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
pub async fn pty_new_window(app: AppHandle, window: tauri::Window, workspace: State<'_, WorkspaceState>, id: String) -> Result<()> {
|
pub async fn pty_new_window(app: AppHandle, window: tauri::Window, workspace: State<'_, WorkspaceState>, id: String) -> Result<()> {
|
||||||
let root = current_root(&workspace, window.label())?;
|
let root = current_root(&workspace, window.label())?;
|
||||||
@@ -436,28 +559,111 @@ mod tests {
|
|||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
use std::time::{Duration, Instant};
|
use std::time::{Duration, Instant};
|
||||||
|
|
||||||
/// Records the window events that a session would send.
|
#[derive(Debug, PartialEq)]
|
||||||
struct FakeEvents(Arc<Mutex<Vec<String>>>);
|
enum Sent {
|
||||||
impl PtyOutput for FakeEvents {
|
Data(Vec<u8>),
|
||||||
fn data(&self, bytes: &[u8]) { self.0.lock().unwrap().push(format!("pty-data {}", String::from_utf8_lossy(bytes))); }
|
Exit(Option<u32>),
|
||||||
fn exit(&self, code: Option<u32>) { self.0.lock().unwrap().push(format!("pty-exit {code:?}")); }
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn run_pump(channel: Option<Channel<InvokeResponseBody>>, events: Arc<Mutex<Vec<String>>>) {
|
/// Records the messages that a session sends.
|
||||||
|
#[derive(Clone, Default)]
|
||||||
|
struct Recorder(Arc<Mutex<Vec<Sent>>>);
|
||||||
|
impl PtyOutput for Recorder {
|
||||||
|
fn data(&self, bytes: &[u8]) { self.0.lock().unwrap().push(Sent::Data(bytes.to_vec())); }
|
||||||
|
fn exit(&self, code: Option<u32>) { self.0.lock().unwrap().push(Sent::Exit(code)); }
|
||||||
|
}
|
||||||
|
impl Recorder {
|
||||||
|
fn take(&self) -> Vec<Sent> { std::mem::take(&mut *self.0.lock().unwrap()) }
|
||||||
|
}
|
||||||
|
|
||||||
|
type Pump = (std::sync::mpsc::Sender<Vec<u8>>, std::sync::mpsc::Sender<Option<u32>>, Recorder, thread::JoinHandle<()>);
|
||||||
|
|
||||||
|
/// Run the batch loop on its own thread. The test sends the chunks and the exit status.
|
||||||
|
fn start_pump(max_bytes: usize, wait: Duration) -> Pump {
|
||||||
|
let (chunk_tx, chunk_rx) = std::sync::mpsc::channel();
|
||||||
let (exit_tx, exit_rx) = std::sync::mpsc::channel();
|
let (exit_tx, exit_rx) = std::sync::mpsc::channel();
|
||||||
exit_tx.send(Some(3)).unwrap();
|
let recorder = Recorder::default();
|
||||||
let output = output(channel, move || Box::new(FakeEvents(events)));
|
let output = recorder.clone();
|
||||||
pump(std::io::Cursor::new(b"hello \xce\xbb".to_vec()), exit_rx, output.as_ref());
|
let handle = thread::spawn(move || pump(chunk_rx, exit_rx, &output, max_bytes, wait));
|
||||||
|
(chunk_tx, exit_tx, recorder, handle)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn data_sizes(sent: &[Sent]) -> Vec<usize> {
|
||||||
|
sent.iter().filter_map(|message| match message { Sent::Data(bytes) => Some(bytes.len()), Sent::Exit(_) => None }).collect()
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn a_channel_session_sends_raw_bytes_and_no_window_events() {
|
fn small_chunks_within_the_wait_become_one_message() {
|
||||||
let events = Arc::new(Mutex::new(Vec::new()));
|
let (chunks, exit, recorder, handle) = start_pump(BATCH_BYTES, Duration::from_secs(5));
|
||||||
|
for _ in 0..100 { chunks.send(b"ab".to_vec()).unwrap(); }
|
||||||
|
drop(chunks);
|
||||||
|
exit.send(Some(0)).unwrap();
|
||||||
|
handle.join().unwrap();
|
||||||
|
assert_eq!(recorder.take(), vec![Sent::Data(b"ab".repeat(100)), Sent::Exit(Some(0))]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn output_larger_than_the_limit_becomes_several_messages() {
|
||||||
|
let (chunks, exit, recorder, handle) = start_pump(BATCH_BYTES, Duration::from_secs(5));
|
||||||
|
let mut expected: Vec<u8> = Vec::new();
|
||||||
|
for index in 0..40u8 {
|
||||||
|
let chunk = vec![index; 4000];
|
||||||
|
expected.extend(&chunk);
|
||||||
|
chunks.send(chunk).unwrap();
|
||||||
|
}
|
||||||
|
// One chunk larger than the limit goes in parts.
|
||||||
|
let large = vec![b'x'; BATCH_BYTES + 100];
|
||||||
|
expected.extend(&large);
|
||||||
|
chunks.send(large).unwrap();
|
||||||
|
drop(chunks);
|
||||||
|
exit.send(None).unwrap();
|
||||||
|
handle.join().unwrap();
|
||||||
|
let sent = recorder.take();
|
||||||
|
let sizes = data_sizes(&sent);
|
||||||
|
assert!(sizes.len() > 1, "{sizes:?}");
|
||||||
|
assert!(sizes.iter().all(|&size| size > 0 && size <= BATCH_BYTES), "{sizes:?}");
|
||||||
|
let joined: Vec<u8> = sent.iter().flat_map(|message| match message { Sent::Data(bytes) => bytes.clone(), Sent::Exit(_) => Vec::new() }).collect();
|
||||||
|
assert_eq!(joined, expected);
|
||||||
|
assert_eq!(sent.last(), Some(&Sent::Exit(None)));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_chunk_after_a_pause_goes_in_a_new_message() {
|
||||||
|
let (chunks, exit, recorder, handle) = start_pump(BATCH_BYTES, Duration::from_millis(20));
|
||||||
|
chunks.send(b"first".to_vec()).unwrap();
|
||||||
|
thread::sleep(Duration::from_millis(300));
|
||||||
|
chunks.send(b"second".to_vec()).unwrap();
|
||||||
|
drop(chunks);
|
||||||
|
exit.send(Some(1)).unwrap();
|
||||||
|
handle.join().unwrap();
|
||||||
|
assert_eq!(recorder.take(), vec![Sent::Data(b"first".to_vec()), Sent::Data(b"second".to_vec()), Sent::Exit(Some(1))]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_exit_comes_after_all_output() {
|
||||||
|
let (chunks, exit, recorder, handle) = start_pump(16, Duration::from_secs(5));
|
||||||
|
// The exit status is ready before the output ends.
|
||||||
|
exit.send(Some(9)).unwrap();
|
||||||
|
for _ in 0..10 { chunks.send(b"0123456789".to_vec()).unwrap(); }
|
||||||
|
drop(chunks);
|
||||||
|
handle.join().unwrap();
|
||||||
|
let sent = recorder.take();
|
||||||
|
assert_eq!(data_sizes(&sent).iter().sum::<usize>(), 100);
|
||||||
|
assert!(data_sizes(&sent).iter().all(|&size| size <= 16));
|
||||||
|
assert_eq!(sent.iter().position(|message| matches!(message, Sent::Exit(_))), Some(sent.len() - 1));
|
||||||
|
assert_eq!(sent.last(), Some(&Sent::Exit(Some(9))));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_channel_session_sends_raw_bytes_then_the_json_exit() {
|
||||||
let received = Arc::new(Mutex::new(Vec::new()));
|
let received = Arc::new(Mutex::new(Vec::new()));
|
||||||
let sink = received.clone();
|
let sink = received.clone();
|
||||||
let channel = Channel::new(move |body| { sink.lock().unwrap().push(body); Ok(()) });
|
let channel = Channel::new(move |body| { sink.lock().unwrap().push(body); Ok(()) });
|
||||||
run_pump(Some(channel), events.clone());
|
let (chunk_tx, chunk_rx) = std::sync::mpsc::channel();
|
||||||
assert!(events.lock().unwrap().is_empty(), "a channel session must not send pty-data or pty-exit events");
|
let (exit_tx, exit_rx) = std::sync::mpsc::channel();
|
||||||
|
exit_tx.send(Some(3)).unwrap();
|
||||||
|
read_chunks(std::io::Cursor::new(b"hello \xce\xbb".to_vec()), chunk_tx);
|
||||||
|
pump(chunk_rx, exit_rx, &ChannelOutput(channel), BATCH_BYTES, BATCH_WAIT);
|
||||||
let received = received.lock().unwrap();
|
let received = received.lock().unwrap();
|
||||||
assert_eq!(received.len(), 2);
|
assert_eq!(received.len(), 2);
|
||||||
match &received[0] {
|
match &received[0] {
|
||||||
@@ -470,11 +676,112 @@ mod tests {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Start a real shell for `owner`. A thread reads its output until EOF.
|
||||||
|
fn shell(owner: &str) -> OpenPty {
|
||||||
|
let root = std::env::current_dir().unwrap();
|
||||||
|
let (session, mut reader, _child) = spawn_shell(&root, 80, 24, None, owner).unwrap();
|
||||||
|
thread::spawn(move || {
|
||||||
|
let _ = std::io::copy(&mut reader, &mut std::io::sink());
|
||||||
|
});
|
||||||
|
session
|
||||||
|
}
|
||||||
|
|
||||||
|
fn ids(pty: &PtyState) -> Vec<String> {
|
||||||
|
let mut ids: Vec<String> = pty.inner.lock().unwrap().open.keys().cloned().collect();
|
||||||
|
ids.sort();
|
||||||
|
ids
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn a_session_without_a_channel_keeps_the_window_events() {
|
fn only_the_owner_window_can_use_a_session() {
|
||||||
let events = Arc::new(Mutex::new(Vec::new()));
|
let pty = PtyState::new();
|
||||||
run_pump(None, events.clone());
|
pty.inner.lock().unwrap().open.insert("t1".into(), shell("a"));
|
||||||
assert_eq!(*events.lock().unwrap(), vec!["pty-data hello λ".to_owned(), "pty-exit Some(3)".to_owned()]);
|
assert_eq!(write(&pty, "b", "t1", "\r").unwrap_err().to_string(), NOT_OPEN);
|
||||||
|
assert_eq!(resize(&pty, "b", "t1", 100, 40).unwrap_err().to_string(), NOT_OPEN);
|
||||||
|
assert!(close(&pty, "b", "t1").unwrap().is_none());
|
||||||
|
assert_eq!(ids(&pty), vec!["t1"]);
|
||||||
|
// A missing session gives the same results.
|
||||||
|
assert_eq!(write(&pty, "a", "t2", "\r").unwrap_err().to_string(), NOT_OPEN);
|
||||||
|
assert_eq!(resize(&pty, "a", "t2", 100, 40).unwrap_err().to_string(), NOT_OPEN);
|
||||||
|
assert!(close(&pty, "a", "t2").unwrap().is_none());
|
||||||
|
write(&pty, "a", "t1", "\r").unwrap();
|
||||||
|
resize(&pty, "a", "t1", 100, 40).unwrap();
|
||||||
|
let session = close(&pty, "a", "t1").unwrap();
|
||||||
|
assert!(session.is_some());
|
||||||
|
assert!(ids(&pty).is_empty());
|
||||||
|
drop(session);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_new_page_closes_the_sessions_of_its_window_only() {
|
||||||
|
let pty = PtyState::new();
|
||||||
|
let enter = |owner: &str, page: &str| enter_page(&mut pty.inner.lock().unwrap(), owner, page);
|
||||||
|
// The first page of each window becomes current.
|
||||||
|
assert!(enter("a", "page-1").unwrap().is_empty());
|
||||||
|
assert!(enter("b", "page-b").unwrap().is_empty());
|
||||||
|
{
|
||||||
|
let mut sessions = pty.inner.lock().unwrap();
|
||||||
|
sessions.open.insert("a1".into(), shell("a"));
|
||||||
|
sessions.open.insert("b1".into(), shell("b"));
|
||||||
|
}
|
||||||
|
// A second dock of the same page keeps the sessions.
|
||||||
|
assert!(enter("a", "page-1").unwrap().is_empty());
|
||||||
|
assert_eq!(ids(&pty), vec!["a1", "b1"]);
|
||||||
|
// A reload of window "a" closes its sessions. The session of window "b" stays.
|
||||||
|
let left = enter("a", "page-2").unwrap();
|
||||||
|
assert_eq!(left.iter().map(|session| session.owner.as_str()).collect::<Vec<_>>(), vec!["a"]);
|
||||||
|
drop(left);
|
||||||
|
assert_eq!(ids(&pty), vec!["b1"]);
|
||||||
|
// A late open of the old page is refused and closes nothing.
|
||||||
|
pty.inner.lock().unwrap().open.insert("a2".into(), shell("a"));
|
||||||
|
assert_eq!(enter("a", "page-1").err().map(|error| error.to_string()).as_deref(), Some(RETIRED_PAGE));
|
||||||
|
assert_eq!(ids(&pty), vec!["a2", "b1"]);
|
||||||
|
// The window forgets its pages when it closes.
|
||||||
|
pty.close_window("a");
|
||||||
|
assert_eq!(ids(&pty), vec!["b1"]);
|
||||||
|
assert!(!pty.inner.lock().unwrap().pages.contains_key("a"));
|
||||||
|
assert!(enter("a", "page-1").unwrap().is_empty());
|
||||||
|
pty.close_all();
|
||||||
|
assert!(ids(&pty).is_empty());
|
||||||
|
assert!(pty.inner.lock().unwrap().pages.is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_window_keeps_a_limited_number_of_retired_pages() {
|
||||||
|
let mut sessions = Sessions::default();
|
||||||
|
for index in 0..=RETIRED_PAGES + 4 {
|
||||||
|
assert!(enter_page(&mut sessions, "a", &format!("page-{index}")).unwrap().is_empty());
|
||||||
|
}
|
||||||
|
let pages = &sessions.pages["a"];
|
||||||
|
assert_eq!(pages.retired.len(), RETIRED_PAGES);
|
||||||
|
assert_eq!(pages.current, format!("page-{}", RETIRED_PAGES + 4));
|
||||||
|
assert!(enter_page(&mut sessions, "a", &format!("page-{}", RETIRED_PAGES + 3)).is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn page_ids_are_checked() {
|
||||||
|
assert!(check_page("0f3c-9a1b").is_ok());
|
||||||
|
assert!(check_page(&"a".repeat(64)).is_ok());
|
||||||
|
for page in ["", "a b", "../page", "page_1", "λ"] {
|
||||||
|
assert!(check_page(page).is_err(), "{page}");
|
||||||
|
}
|
||||||
|
assert!(check_page(&"a".repeat(65)).is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn running_counts_the_sessions_of_all_windows() {
|
||||||
|
let pty = PtyState::new();
|
||||||
|
assert_eq!(running(&pty).unwrap(), 0);
|
||||||
|
{
|
||||||
|
let mut sessions = pty.inner.lock().unwrap();
|
||||||
|
sessions.open.insert("a1".into(), shell("a"));
|
||||||
|
sessions.open.insert("b1".into(), shell("b"));
|
||||||
|
}
|
||||||
|
assert_eq!(running(&pty).unwrap(), 2);
|
||||||
|
pty.close_window("a");
|
||||||
|
assert_eq!(running(&pty).unwrap(), 1);
|
||||||
|
pty.close_all();
|
||||||
|
assert_eq!(running(&pty).unwrap(), 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
|
|||||||
@@ -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.49",
|
"version": "0.1.51",
|
||||||
"identifier": "com.runestone.app",
|
"identifier": "com.runestone.app",
|
||||||
"build": {
|
"build": {
|
||||||
"beforeDevCommand": "pnpm dev",
|
"beforeDevCommand": "pnpm dev",
|
||||||
|
|||||||
@@ -3,6 +3,7 @@
|
|||||||
@import "./lib/ui/menu.css";
|
@import "./lib/ui/menu.css";
|
||||||
@import "./lib/ui/switch.css";
|
@import "./lib/ui/switch.css";
|
||||||
@import "./lib/theme/base.css";
|
@import "./lib/theme/base.css";
|
||||||
|
@import "./lib/theme/background.css";
|
||||||
@import "./lib/ui/tooltip.css";
|
@import "./lib/ui/tooltip.css";
|
||||||
@import "./lib/layout/reading.css";
|
@import "./lib/layout/reading.css";
|
||||||
@import "./lib/editor/noteTitle.css";
|
@import "./lib/editor/noteTitle.css";
|
||||||
|
|||||||
@@ -0,0 +1,123 @@
|
|||||||
|
<!--
|
||||||
|
Settings → Project Management, and the Project Management settings of the board menu. It is in the main bundle and
|
||||||
|
loads no feature code: the priority levels are in the `projectManagement` settings section (`pmSettings.ts`), and
|
||||||
|
the default board is in `.runestone/pm/workspace.json` of the workspace (`pmBoards.ts`). It shows only while
|
||||||
|
Project Management is on. Each change saves at once.
|
||||||
|
-->
|
||||||
|
<script lang="ts">
|
||||||
|
import { onDestroy, onMount } from "svelte";
|
||||||
|
import { message, t } from "$lib/i18n";
|
||||||
|
import Icon from "$lib/ui/Icon.svelte";
|
||||||
|
import { showActionMenu } from "$lib/ui/managedActionMenu";
|
||||||
|
import { PRIORITY_LEVELS, onProjectManagementChange, readProjectManagement, writeProjectManagement, type PriorityLevels, type ProjectManagementSettings } from "./pmSettings";
|
||||||
|
import { readBoardCatalog, writeDefaultBoard, type BoardSummary } from "./pmBoards";
|
||||||
|
|
||||||
|
let { compact = false }: { compact?: boolean } = $props();
|
||||||
|
// The errors here are catalog keys without values (pmBoards.ts) or host text. The full `errorText()` of the feature
|
||||||
|
// (pm/ui/text.ts) is not necessary, and this component must load no feature module.
|
||||||
|
const errorText = (reason: unknown) => $t(reason instanceof Error ? reason.message : String(reason));
|
||||||
|
|
||||||
|
const levelNames: Record<PriorityLevels, string> = { 2: message("2 — High and Low"), 3: message("3 — High, Medium, and Low"), 5: message("5 — Highest through Lowest") };
|
||||||
|
let settings = $state<ProjectManagementSettings>(readProjectManagement());
|
||||||
|
let boards = $state<BoardSummary[]>([]);
|
||||||
|
let defaultBoard = $state("");
|
||||||
|
let boardsReady = $state(false);
|
||||||
|
let boardNote = $state("");
|
||||||
|
let saving = $state(false);
|
||||||
|
let notice = $state("");
|
||||||
|
let error = $state("");
|
||||||
|
let closeMenu = () => {};
|
||||||
|
let disposed = false;
|
||||||
|
const active = $derived(boards.filter(board => !board.archived));
|
||||||
|
const boardName = $derived(defaultBoard ? active.find(board => board.id === defaultBoard)?.name ?? $t("Unavailable board (opens All tasks)") : $t("All tasks"));
|
||||||
|
|
||||||
|
function picker(event: MouseEvent, label: string, choices: { label: string; checked: boolean; run: () => void }[]) {
|
||||||
|
closeMenu();
|
||||||
|
const anchor = event.currentTarget as HTMLButtonElement;
|
||||||
|
const bounds = anchor.getBoundingClientRect();
|
||||||
|
closeMenu = showActionMenu({ x: bounds.left, y: bounds.bottom + 4, label, parent: anchor.closest("dialog") ?? undefined,
|
||||||
|
items: choices.map(choice => ({ label: choice.label, radio: true, checked: choice.checked, run: choice.run })) }).close;
|
||||||
|
}
|
||||||
|
|
||||||
|
function saveLevels(priorityLevels: PriorityLevels) {
|
||||||
|
error = "";
|
||||||
|
settings = { ...settings, priorityLevels };
|
||||||
|
writeProjectManagement(settings).then(() => { notice = $t("Changes saved."); })
|
||||||
|
.catch(() => { error = $t("Could not save these settings. Your previous settings still apply. Try again."); notice = ""; settings = readProjectManagement(); });
|
||||||
|
}
|
||||||
|
|
||||||
|
async function saveDefault(id: string) {
|
||||||
|
const previous = defaultBoard;
|
||||||
|
error = ""; saving = true; defaultBoard = id;
|
||||||
|
try { await writeDefaultBoard(id || null); if (!disposed) notice = $t("Changes saved."); }
|
||||||
|
catch (reason) { if (!disposed) { defaultBoard = previous; notice = ""; error = errorText(reason); } }
|
||||||
|
finally { saving = false; }
|
||||||
|
}
|
||||||
|
|
||||||
|
async function readBoards() {
|
||||||
|
try {
|
||||||
|
const catalog = await readBoardCatalog();
|
||||||
|
if (disposed) return;
|
||||||
|
boards = catalog.boards;
|
||||||
|
defaultBoard = catalog.defaultBoardId ?? "";
|
||||||
|
boardsReady = true;
|
||||||
|
boardNote = "";
|
||||||
|
} catch (reason) {
|
||||||
|
if (!disposed) boardNote = /no workspace/i.test(String(reason)) ? $t("Open a workspace to choose its default board.") : errorText(reason);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
onMount(() => {
|
||||||
|
void readBoards();
|
||||||
|
return onProjectManagementChange(() => { settings = readProjectManagement(); });
|
||||||
|
});
|
||||||
|
onDestroy(() => { disposed = true; closeMenu(); });
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<div class="pm-settings">
|
||||||
|
{#if !compact}
|
||||||
|
<h2>{$t("Project Management")}</h2>
|
||||||
|
<p class="intro">{$t("The boards of each workspace stay in {folder} in the workspace.", { folder: ".runestone/pm" })}</p>
|
||||||
|
{/if}
|
||||||
|
<div class="card">
|
||||||
|
<div class="setting-row">
|
||||||
|
<div><span class="name" id="pm-priority-label">{$t("Priority levels")}</span><p id="pm-priority-description">{$t("Existing card priorities stay unchanged when you change this setting.")}</p></div>
|
||||||
|
<button class="picker" type="button" aria-label={$t("Priority levels")} aria-describedby="pm-priority-description" aria-haspopup="menu"
|
||||||
|
onclick={event => picker(event, $t("Priority levels"), PRIORITY_LEVELS.map(levels => ({ label: $t(levelNames[levels]), checked: settings.priorityLevels === levels, run: () => saveLevels(levels) })))}>
|
||||||
|
{$t(levelNames[settings.priorityLevels])}<Icon icon="chevron-down" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<div class="setting-row">
|
||||||
|
<div><span class="name" id="pm-default-label">{$t("Default board")}</span><p id="pm-default-description">{boardNote || $t("Choose the board that opens in this workspace. Restored tabs keep their board.")}</p></div>
|
||||||
|
<button class="picker" type="button" aria-label={$t("Default board")} aria-describedby="pm-default-description" aria-haspopup="menu" disabled={!boardsReady || saving}
|
||||||
|
onclick={event => picker(event, $t("Default board"), [
|
||||||
|
{ label: $t("All tasks"), checked: !defaultBoard, run: () => void saveDefault("") },
|
||||||
|
...active.map(board => ({ label: board.name, checked: defaultBoard === board.id, run: () => void saveDefault(board.id) })),
|
||||||
|
])}>
|
||||||
|
{boardName}<Icon icon="chevron-down" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{#if error}<p class="error" role="alert">{error}</p>{/if}
|
||||||
|
<p class="saved" role="status">{notice}</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<style>
|
||||||
|
.pm-settings { min-width: 0; }
|
||||||
|
h2 { margin: 0; font-size: var(--rs-settings-heading-size); font-weight: 600; color: var(--rs-text-strong); }
|
||||||
|
p { margin: 0; color: var(--rs-text-dim); line-height: 1.45; overflow-wrap: anywhere; }
|
||||||
|
.intro { margin: 6px 0 var(--rs-settings-section-gap); }
|
||||||
|
.card { padding: 0 12px; background: var(--rs-bg-elevated); border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); }
|
||||||
|
.setting-row { display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: 8px 16px; padding: var(--rs-settings-row-padding) 0; }
|
||||||
|
.setting-row > div:first-child { flex: 1 1 200px; min-width: 0; }
|
||||||
|
.setting-row + .setting-row { border-top: 1px solid var(--rs-border); }
|
||||||
|
.name { font-weight: 500; color: var(--rs-text); }
|
||||||
|
.setting-row p { margin-top: 3px; font-size: var(--rs-settings-description-size); }
|
||||||
|
.picker { display: inline-flex; align-items: center; justify-content: space-between; gap: var(--rs-settings-gap); min-height: var(--rs-settings-control-height); box-sizing: border-box; max-width: 100%; min-width: 160px; padding: 4px 8px; border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); background: var(--rs-bg); color: var(--rs-text); font: inherit; text-align: left; cursor: pointer; }
|
||||||
|
.picker:not(:disabled):hover { background: var(--rs-bg-active); }
|
||||||
|
.picker:disabled { color: var(--rs-text-dim); cursor: default; }
|
||||||
|
.picker :global(svg) { width: 14px; height: 14px; flex-shrink: 0; fill: none; stroke: currentColor; stroke-width: 2; }
|
||||||
|
.picker:focus-visible { outline: 2px solid var(--rs-focus); outline-offset: 2px; }
|
||||||
|
.saved { font-size: 12px; color: var(--rs-ok); min-height: 20px; margin-top: 10px; }
|
||||||
|
.error { color: var(--rs-error); margin-top: 10px; }
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
// The place of the terminal panel in the workbench and in the terminal window. It is in the main bundle.
|
||||||
|
// The first mount loads the Terminal feature (xterm included). An unmount closes the sessions of this panel.
|
||||||
|
import { onMount } from "svelte";
|
||||||
|
import { t } from "$lib/i18n";
|
||||||
|
import { terminalInstance, type TerminalAction, type TerminalMount, type TerminalProps } from "./terminalHost";
|
||||||
|
let props: TerminalProps = $props();
|
||||||
|
let container: HTMLDivElement;
|
||||||
|
let mounted = $state.raw<TerminalMount>();
|
||||||
|
let loading = $state(true);
|
||||||
|
let error = $state("");
|
||||||
|
let ready: Promise<TerminalMount | undefined> = Promise.resolve(undefined);
|
||||||
|
onMount(() => {
|
||||||
|
let disposed = false;
|
||||||
|
ready = terminalInstance().then(instance => {
|
||||||
|
if (disposed) return undefined;
|
||||||
|
mounted = instance.mountDock(container, { ...props });
|
||||||
|
return mounted;
|
||||||
|
}).catch(reason => { if (!disposed) error = String(reason); return undefined; }).finally(() => { loading = false; });
|
||||||
|
return () => {
|
||||||
|
disposed = true;
|
||||||
|
const current = mounted;
|
||||||
|
mounted = undefined;
|
||||||
|
void current?.dispose().catch(reason => console.error("The terminal panel did not close cleanly.", reason));
|
||||||
|
};
|
||||||
|
});
|
||||||
|
$effect(() => { mounted?.update({ ...props }); });
|
||||||
|
/** Run a terminal action. It waits for the first load. */
|
||||||
|
export async function command(action: Exclude<TerminalAction, "toggle">) { await (await ready)?.command(action); }
|
||||||
|
</script>
|
||||||
|
{#if error}<p class="error" role="alert">{$t("The terminal could not start: {error}", { error })}</p>{/if}
|
||||||
|
{#if loading}<p class="loading">{$t("Loading the terminal…")}</p>{/if}
|
||||||
|
<div class="terminal-host" bind:this={container}></div>
|
||||||
|
<style>
|
||||||
|
.terminal-host { display: flex; flex-direction: column; flex: 1; height: 100%; min-height: 0; min-width: 0; }
|
||||||
|
.error, .loading { margin: 0; padding: 7px 12px; font-size: 12px; }
|
||||||
|
.error { color: var(--rs-error); }
|
||||||
|
.loading { color: var(--rs-text-dim); }
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,113 @@
|
|||||||
|
<!--
|
||||||
|
Settings → Terminal. It is in the main bundle and loads no feature code, so it does not load xterm.
|
||||||
|
It shows only while Terminal is on. Each change saves at once to the `terminal` section, and open terminals take it.
|
||||||
|
-->
|
||||||
|
<script lang="ts">
|
||||||
|
import { onDestroy, onMount } from "svelte";
|
||||||
|
import { invoke, isTauri } from "@tauri-apps/api/core";
|
||||||
|
import { t, tr } from "$lib/i18n";
|
||||||
|
import Icon from "$lib/ui/Icon.svelte";
|
||||||
|
import { showActionMenu } from "$lib/ui/managedActionMenu";
|
||||||
|
import { FONT_SIZE, SCROLLBACK, onTerminalChange, readTerminal, writeTerminal, type TerminalSettings } from "./terminalSettings";
|
||||||
|
|
||||||
|
type Profile = { id: string; title: string; kind: string };
|
||||||
|
const initial = readTerminal();
|
||||||
|
let settings = $state<TerminalSettings>(initial);
|
||||||
|
let fontSize = $state<number | undefined>(initial.fontSize);
|
||||||
|
let scrollback = $state<number | undefined>(initial.scrollback);
|
||||||
|
let profiles = $state<Profile[]>([]);
|
||||||
|
let profileNote = $state("");
|
||||||
|
let message = $state("");
|
||||||
|
let error = $state("");
|
||||||
|
let closeMenu = () => {};
|
||||||
|
/** The shells that a new terminal can use. The Node.js debug terminal is not a default. */
|
||||||
|
const shells = $derived(profiles.filter(profile => profile.kind !== "node"));
|
||||||
|
const current = $derived(shells.find(profile => profile.id === settings.defaultProfile) ?? shells[0]);
|
||||||
|
|
||||||
|
function read() {
|
||||||
|
settings = readTerminal();
|
||||||
|
fontSize = settings.fontSize;
|
||||||
|
scrollback = settings.scrollback;
|
||||||
|
}
|
||||||
|
function save(next: TerminalSettings) {
|
||||||
|
error = "";
|
||||||
|
settings = next;
|
||||||
|
writeTerminal(next).then(() => { message = tr("Changes saved."); })
|
||||||
|
.catch(() => { error = tr("Could not save these settings. Your previous settings still apply. Try again."); message = ""; });
|
||||||
|
}
|
||||||
|
function changeNumber(value: number | undefined, range: { min: number; max: number }, key: "fontSize" | "scrollback") {
|
||||||
|
if (typeof value !== "number" || !Number.isInteger(value) || value < range.min || value > range.max) {
|
||||||
|
error = tr("Choose a whole number from {min} to {max}.", { min: range.min.toLocaleString(), max: range.max.toLocaleString() });
|
||||||
|
message = "";
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
save({ ...settings, [key]: value });
|
||||||
|
}
|
||||||
|
function profileMenu(event: MouseEvent) {
|
||||||
|
closeMenu();
|
||||||
|
const anchor = event.currentTarget as HTMLButtonElement;
|
||||||
|
const bounds = anchor.getBoundingClientRect();
|
||||||
|
closeMenu = showActionMenu({ x: bounds.left, y: bounds.bottom + 4, label: tr("Default terminal profile"), parent: anchor.closest("dialog") ?? undefined,
|
||||||
|
items: shells.map(profile => ({ label: profile.title, icon: "code", radio: true, checked: current?.id === profile.id,
|
||||||
|
run: () => save({ ...settings, defaultProfile: profile.id }) })) }).close;
|
||||||
|
}
|
||||||
|
onMount(() => {
|
||||||
|
const stop = onTerminalChange(read);
|
||||||
|
if (!isTauri()) profileNote = tr("The desktop app lists the installed shells.");
|
||||||
|
else invoke<Profile[]>("pty_profiles").then(found => {
|
||||||
|
profiles = found;
|
||||||
|
if (!found.some(profile => profile.kind !== "node")) profileNote = tr("RuneStone found no supported shells on PATH.");
|
||||||
|
}).catch(reason => { profileNote = tr("RuneStone could not list the shells: {error}", { error: String(reason) }); });
|
||||||
|
return stop;
|
||||||
|
});
|
||||||
|
onDestroy(() => closeMenu());
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<div class="terminal-settings">
|
||||||
|
<h2>{$t("Terminal")}</h2>
|
||||||
|
<p class="intro">{$t("Font, scrollback, and cursor apply to open terminals. The default profile applies to new terminals.")}</p>
|
||||||
|
<div class="card">
|
||||||
|
<div class="setting-row">
|
||||||
|
<div><span class="name" id="terminal-profile-label">{$t("Default profile")}</span><p id="terminal-profile-description">{profileNote || $t("The shell of a new terminal.")}</p></div>
|
||||||
|
<button class="picker" type="button" aria-label={$t("Default profile")} aria-describedby="terminal-profile-description" aria-haspopup="menu" disabled={!shells.length} onclick={profileMenu}>
|
||||||
|
{current?.title ?? $t("No shell")}<Icon icon="chevron-down" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<div class="setting-row">
|
||||||
|
<div><label for="terminal-font-size">{$t("Font size")}</label><p id="terminal-font-description">{$t("From {min} to {max} pixels.", { min: FONT_SIZE.min, max: FONT_SIZE.max })}</p></div>
|
||||||
|
<input id="terminal-font-size" type="number" min={FONT_SIZE.min} max={FONT_SIZE.max} step="1" required aria-describedby="terminal-font-description" bind:value={fontSize} onchange={() => changeNumber(fontSize, FONT_SIZE, "fontSize")} />
|
||||||
|
</div>
|
||||||
|
<div class="setting-row">
|
||||||
|
<div><label for="terminal-scrollback">{$t("Scrollback lines")}</label><p id="terminal-scrollback-description">{$t("The lines that a terminal keeps above the screen, from {min} to {max}.", { min: SCROLLBACK.min.toLocaleString(), max: SCROLLBACK.max.toLocaleString() })}</p></div>
|
||||||
|
<input id="terminal-scrollback" type="number" min={SCROLLBACK.min} max={SCROLLBACK.max} step="100" required aria-describedby="terminal-scrollback-description" bind:value={scrollback} onchange={() => changeNumber(scrollback, SCROLLBACK, "scrollback")} />
|
||||||
|
</div>
|
||||||
|
<div class="setting-row">
|
||||||
|
<div><label for="terminal-cursor-blink">{$t("Blink cursor")}</label><p id="terminal-blink-description">{$t("The cursor blinks in the focused terminal.")}</p></div>
|
||||||
|
<input id="terminal-cursor-blink" class="rs-switch" type="checkbox" role="switch" aria-describedby="terminal-blink-description" checked={settings.cursorBlink} onchange={event => save({ ...settings, cursorBlink: event.currentTarget.checked })} />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{#if error}<p class="error" role="alert">{error}</p>{/if}
|
||||||
|
<p class="saved" role="status">{message}</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<style>
|
||||||
|
.terminal-settings { min-width: 0; }
|
||||||
|
h2 { margin: 0; font-size: var(--rs-settings-heading-size); font-weight: 600; color: var(--rs-text-strong); }
|
||||||
|
p { margin: 0; color: var(--rs-text-dim); line-height: 1.45; overflow-wrap: anywhere; }
|
||||||
|
.intro { margin: 6px 0 var(--rs-settings-section-gap); }
|
||||||
|
.card { padding: 0 12px; background: var(--rs-bg-elevated); border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); }
|
||||||
|
.setting-row { display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: 8px 16px; padding: var(--rs-settings-row-padding) 0; }
|
||||||
|
.setting-row > div:first-child { flex: 1 1 200px; min-width: 0; }
|
||||||
|
.setting-row + .setting-row { border-top: 1px solid var(--rs-border); }
|
||||||
|
.setting-row label, .name { font-weight: 500; color: var(--rs-text); }
|
||||||
|
.setting-row p { margin-top: 3px; font-size: var(--rs-settings-description-size); }
|
||||||
|
input[type=number], .picker { min-height: var(--rs-settings-control-height); box-sizing: border-box; padding: 4px 8px; border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); background: var(--rs-bg); color: var(--rs-text); font: inherit; }
|
||||||
|
input[type=number] { width: 96px; }
|
||||||
|
.picker { display: inline-flex; align-items: center; justify-content: space-between; gap: var(--rs-settings-gap); max-width: 100%; min-width: 160px; text-align: left; cursor: pointer; }
|
||||||
|
.picker:not(:disabled):hover { background: var(--rs-bg-active); }
|
||||||
|
.picker:disabled { color: var(--rs-text-dim); cursor: default; }
|
||||||
|
.picker :global(svg) { width: 14px; height: 14px; flex-shrink: 0; fill: none; stroke: currentColor; stroke-width: 2; }
|
||||||
|
:is(.picker, input):focus-visible { outline: 2px solid var(--rs-focus); outline-offset: 2px; }
|
||||||
|
.saved { font-size: 12px; color: var(--rs-ok); min-height: 20px; margin-top: 10px; }
|
||||||
|
.error { color: var(--rs-error); margin-top: 10px; }
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,295 @@
|
|||||||
|
<!--
|
||||||
|
Appearance → Background. The source is a folder (a slideshow), one image, or none. The folder layout and the order
|
||||||
|
are in the `background` settings section. The image and its layout stay in `appearance.newTabBackground`.
|
||||||
|
This component also works in the settings window, where the slideshow does not run. It sends Next to every window.
|
||||||
|
-->
|
||||||
|
<script lang="ts">
|
||||||
|
import { onDestroy, onMount } from "svelte";
|
||||||
|
import { t, tr } from "$lib/i18n";
|
||||||
|
import Icon from "$lib/ui/Icon.svelte";
|
||||||
|
import { showActionMenu } from "$lib/ui/managedActionMenu";
|
||||||
|
import { onSettingsChange } from "$lib/settings/store";
|
||||||
|
import { featureSwitches } from "$lib/features/state";
|
||||||
|
import { readBoardCatalog } from "../pmBoards";
|
||||||
|
import { BACKGROUND_POSITIONS, BACKGROUND_SIZES, readAppearance, saveAppearance, type Appearance } from "$lib/theme/appearance";
|
||||||
|
import { removeBackgroundImage, saveBackgroundImage } from "$lib/theme/backgroundImages";
|
||||||
|
import { hasImage, normalizeLayout, readBackground, writeBackground, type BackgroundLayout, type BackgroundSettings, type BackgroundSource } from "../backgroundSettings";
|
||||||
|
import { folderHost, readSavedImage, sendBackgroundCommand } from "./sources";
|
||||||
|
import { imageNames } from "./imageSettings";
|
||||||
|
import ImageEditor from "./ImageEditor.svelte";
|
||||||
|
|
||||||
|
/** The background targets of single boards need a UUID board ID. */
|
||||||
|
const boardId = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
||||||
|
|
||||||
|
let settings = $state<BackgroundSettings>(readBackground());
|
||||||
|
let appearance = $state<Appearance>(readAppearance());
|
||||||
|
let folder = $state<string | null>(null);
|
||||||
|
let folderNote = $state("");
|
||||||
|
let boards = $state<{ id: string; name: string }[]>([]);
|
||||||
|
let boardsNote = $state("");
|
||||||
|
let previewUrl = $state("");
|
||||||
|
let error = $state("");
|
||||||
|
let imageInput: HTMLInputElement;
|
||||||
|
let imageRevision = 0;
|
||||||
|
let boardRevision = 0;
|
||||||
|
let previewKey = "";
|
||||||
|
let closeMenu = () => {};
|
||||||
|
let disposed = false;
|
||||||
|
|
||||||
|
const image = $derived(appearance.newTabBackground);
|
||||||
|
const layout = $derived<BackgroundLayout | null>(settings.source === "folder" ? normalizeLayout(settings) : settings.source === "image" && hasImage(appearance) ? normalizeLayout(image) : null);
|
||||||
|
const sourceLabels = $derived<Record<BackgroundSource, string>>({ folder: $t("Folder"), image: $t("Image"), none: $t("None") });
|
||||||
|
const positionLabels = $derived([$t("Center"), $t("Top left"), $t("Top center"), $t("Top right"), $t("Center left"), $t("Center right"), $t("Bottom left"), $t("Bottom center"), $t("Bottom right")]);
|
||||||
|
const sizeLabels = $derived([$t("Fill"), $t("Fit"), $t("Actual size")]);
|
||||||
|
const orderLabels = $derived({ name: $t("File name"), random: $t("Random") });
|
||||||
|
const targets = $derived([
|
||||||
|
{ id: "app", name: $t("The workspace and new tabs") },
|
||||||
|
{ id: "pm-all", name: $t("All Project Management boards") },
|
||||||
|
...boards.map(board => ({ id: `pm-board:${board.id}`, name: $t("Board: {name}", { name: board.name }) })),
|
||||||
|
// Keep saved targets without a current board, so that the user can remove them.
|
||||||
|
...settings.targets.filter(id => id.startsWith("pm-board:") && !boards.some(board => `pm-board:${board.id}` === id))
|
||||||
|
.map(id => ({ id, name: $t("Unavailable board: {id}", { id: id.slice(9) }) })),
|
||||||
|
]);
|
||||||
|
|
||||||
|
const report = (reason: unknown) => { if (!disposed) error = reason instanceof Error ? reason.message : String(reason); };
|
||||||
|
|
||||||
|
function save(next: BackgroundSettings) {
|
||||||
|
settings = next; error = "";
|
||||||
|
writeBackground(next).catch(() => report(tr("Could not save the background settings.")));
|
||||||
|
}
|
||||||
|
|
||||||
|
function saveImageAppearance(next: Appearance) {
|
||||||
|
try {
|
||||||
|
saveAppearance(next).catch(() => report(tr("Could not save appearance settings.")));
|
||||||
|
appearance = readAppearance(); error = ""; return true;
|
||||||
|
} catch { report(tr("Could not save appearance settings.")); return false; }
|
||||||
|
}
|
||||||
|
|
||||||
|
function changeLayout(patch: Partial<BackgroundLayout>) {
|
||||||
|
if (settings.source === "folder") save({ ...settings, ...patch });
|
||||||
|
else if (image) saveImageAppearance({ ...appearance, newTabBackground: { ...image, ...patch } });
|
||||||
|
}
|
||||||
|
|
||||||
|
function changeOverlay(input: HTMLInputElement) {
|
||||||
|
const percent = input.valueAsNumber;
|
||||||
|
if (!Number.isFinite(percent)) return;
|
||||||
|
changeLayout({ overlay: Math.round(Math.max(-100, Math.min(100, percent))) / 100 });
|
||||||
|
}
|
||||||
|
|
||||||
|
function picker(event: MouseEvent, label: string, choices: { label: string; checked: boolean; run: () => void }[]) {
|
||||||
|
closeMenu();
|
||||||
|
const anchor = event.currentTarget as HTMLButtonElement;
|
||||||
|
const bounds = anchor.getBoundingClientRect();
|
||||||
|
closeMenu = showActionMenu({ x: bounds.left, y: bounds.bottom + 4, label, parent: anchor.closest("dialog") ?? undefined,
|
||||||
|
items: choices.map(choice => ({ label: choice.label, radio: true, checked: choice.checked, run: choice.run })) }).close;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function chooseSource(source: BackgroundSource) {
|
||||||
|
error = "";
|
||||||
|
if (source === "folder" && !folder) { await chooseFolder(); return; }
|
||||||
|
if (source === "image" && !hasImage(appearance)) { imageInput.click(); return; }
|
||||||
|
save({ ...settings, source });
|
||||||
|
}
|
||||||
|
|
||||||
|
async function chooseFolder() {
|
||||||
|
try {
|
||||||
|
const chosen = await folderHost.choose(tr("Choose the background folder"));
|
||||||
|
if (!chosen || disposed) return;
|
||||||
|
folder = chosen;
|
||||||
|
save({ ...settings, source: "folder" });
|
||||||
|
await sendBackgroundCommand("reload");
|
||||||
|
void inspectFolder();
|
||||||
|
} catch (reason) { report(reason); }
|
||||||
|
}
|
||||||
|
|
||||||
|
async function removeFolder() {
|
||||||
|
try {
|
||||||
|
await folderHost.clear();
|
||||||
|
folder = null; folderNote = "";
|
||||||
|
if (settings.source === "folder") save({ ...settings, source: "none" });
|
||||||
|
await sendBackgroundCommand("reload");
|
||||||
|
} catch (reason) { report(reason); }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Count the images of the folder, so that the user sees a problem at once. */
|
||||||
|
async function inspectFolder() {
|
||||||
|
if (!folder) { folderNote = ""; return; }
|
||||||
|
try {
|
||||||
|
const count = imageNames(await folderHost.list()).length;
|
||||||
|
if (!disposed) folderNote = count ? tr(count === 1 ? "{count} image." : "{count} images.", { count }) : tr("No supported images in this folder. Add PNG, JPEG, GIF, or WebP files.");
|
||||||
|
} catch (reason) { if (!disposed) folderNote = reason instanceof Error ? reason.message : String(reason); }
|
||||||
|
}
|
||||||
|
|
||||||
|
async function importImage(file?: File) {
|
||||||
|
if (!file) return;
|
||||||
|
const revision = ++imageRevision;
|
||||||
|
try {
|
||||||
|
if (!["image/png", "image/jpeg", "image/webp", "image/gif"].includes(file.type)) throw new Error(tr("Choose a PNG, JPEG, WebP, or GIF image."));
|
||||||
|
const imageId = await saveBackgroundImage(file);
|
||||||
|
if (revision !== imageRevision) { await removeBackgroundImage(imageId); return; }
|
||||||
|
const old = appearance.newTabBackground?.imageId;
|
||||||
|
if (saveImageAppearance({ ...appearance, newTabBackground: { ...appearance.newTabBackground, image: undefined, imageId, overlay: appearance.newTabBackground?.overlay ?? 0 } })) {
|
||||||
|
if (settings.source !== "image") save({ ...settings, source: "image" });
|
||||||
|
if (old) await removeBackgroundImage(old);
|
||||||
|
} else await removeBackgroundImage(imageId);
|
||||||
|
} catch (reason) { if (revision === imageRevision) report(reason); }
|
||||||
|
finally { if (revision === imageRevision) imageInput.value = ""; }
|
||||||
|
}
|
||||||
|
|
||||||
|
async function removeImage() {
|
||||||
|
imageRevision++;
|
||||||
|
const old = appearance.newTabBackground?.imageId;
|
||||||
|
if (saveImageAppearance({ ...appearance, newTabBackground: undefined }) && old) {
|
||||||
|
try { await removeBackgroundImage(old); } catch { report(tr("Could not remove the saved image from storage.")); }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function toggleTarget(id: string, on: boolean) {
|
||||||
|
save({ ...settings, targets: on ? [...new Set([...settings.targets, id])] : settings.targets.filter(target => target !== id) });
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The active boards of `.runestone/pm/workspace.json`. It needs no Project Management code. */
|
||||||
|
async function discoverBoards(on: boolean) {
|
||||||
|
const revision = ++boardRevision;
|
||||||
|
if (!on) {
|
||||||
|
boards = []; boardsNote = tr("Turn on Project Management to show the background on one board.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const catalog = await readBoardCatalog();
|
||||||
|
if (disposed || revision !== boardRevision) return;
|
||||||
|
boards = catalog.boards.filter(board => !board.archived && boardId.test(board.id)).map(board => ({ id: board.id, name: board.name }));
|
||||||
|
boardsNote = boards.length ? "" : tr("The workspace has no boards.");
|
||||||
|
} catch (reason) {
|
||||||
|
if (!disposed && revision === boardRevision) boardsNote = tr("Could not read the workspace boards: {error}", { error: reason instanceof Error ? reason.message : String(reason) });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The preview of the saved image. It uses its own blob URL, so it works in every window. */
|
||||||
|
async function updatePreview() {
|
||||||
|
const saved = settings.source === "image" ? appearance.newTabBackground : undefined;
|
||||||
|
const key = saved && hasImage(appearance) ? saved.imageId ?? `${saved.image?.length}:${saved.image?.slice(-48)}` : "";
|
||||||
|
if (key === previewKey) return;
|
||||||
|
previewKey = key;
|
||||||
|
if (previewUrl) URL.revokeObjectURL(previewUrl);
|
||||||
|
previewUrl = "";
|
||||||
|
if (!key || !saved) return;
|
||||||
|
try {
|
||||||
|
const url = URL.createObjectURL(await readSavedImage(saved));
|
||||||
|
if (disposed || previewKey !== key) { URL.revokeObjectURL(url); return; }
|
||||||
|
previewUrl = url;
|
||||||
|
} catch (reason) { report(reason); }
|
||||||
|
}
|
||||||
|
|
||||||
|
const overlayShade = $derived(layout ? `linear-gradient(rgba(${layout.overlay < 0 ? "255,255,255" : "0,0,0"},${Math.abs(layout.overlay)}),rgba(${layout.overlay < 0 ? "255,255,255" : "0,0,0"},${Math.abs(layout.overlay)}))` : "none");
|
||||||
|
|
||||||
|
$effect(() => { void settings.source; void appearance.newTabBackground; void updatePreview(); });
|
||||||
|
|
||||||
|
onMount(() => {
|
||||||
|
const read = () => { settings = readBackground(); appearance = readAppearance(); };
|
||||||
|
const stops = [onSettingsChange("background", read), onSettingsChange("appearance", read), featureSwitches.subscribe(switches => { void discoverBoards(switches.pm); })];
|
||||||
|
void folderHost.current().then(value => { if (!disposed) { folder = value; void inspectFolder(); } }, () => { folder = null; });
|
||||||
|
return () => stops.forEach(stop => stop());
|
||||||
|
});
|
||||||
|
onDestroy(() => { disposed = true; closeMenu(); if (previewUrl) URL.revokeObjectURL(previewUrl); });
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<div class="background-settings">
|
||||||
|
<div class="card">
|
||||||
|
<div class="setting-row"><span>{$t("Background source")}</span><button class="picker" aria-label={$t("Background source")} aria-haspopup="menu"
|
||||||
|
onclick={event => picker(event, $t("Background source"), (["folder", "image", "none"] as const).map(source => ({ label: sourceLabels[source], checked: settings.source === source, run: () => void chooseSource(source) })))}>{sourceLabels[settings.source]}<Icon icon="chevron-down" /></button></div>
|
||||||
|
{#if settings.source === "folder"}
|
||||||
|
<div class="setting-row folder-row"><label for="background-folder">{$t("Image folder")}</label><div class="controls folder-controls">
|
||||||
|
<input id="background-folder" readonly value={folder ?? ""} title={folder ?? ""} placeholder={$t("No folder selected")} />
|
||||||
|
<button onclick={() => void chooseFolder()}><Icon icon="folder-open" />{$t("Choose folder…")}</button>
|
||||||
|
{#if folder}<button onclick={() => void removeFolder()}>{$t("Remove folder")}</button>{/if}
|
||||||
|
</div></div>
|
||||||
|
<div class="setting-row"><label for="background-seconds">{$t("Seconds per image")}</label><input id="background-seconds" type="number" min="1" max="86400" step="1" value={settings.seconds}
|
||||||
|
onchange={event => { if (event.currentTarget.reportValidity()) save({ ...settings, seconds: event.currentTarget.valueAsNumber }); }} /></div>
|
||||||
|
<div class="setting-row"><span>{$t("Image order")}</span><button class="picker" aria-label={$t("Image order")} aria-haspopup="menu"
|
||||||
|
onclick={event => picker(event, $t("Image order"), (["name", "random"] as const).map(order => ({ label: orderLabels[order], checked: settings.order === order, run: () => save({ ...settings, order }) })))}>{orderLabels[settings.order]}<Icon icon="chevron-down" /></button></div>
|
||||||
|
<div class="setting-row"><span>{$t("Slideshow")}</span><div class="controls">
|
||||||
|
<button onclick={() => void sendBackgroundCommand("next").catch(report)}><Icon icon="arrow-right" />{$t("Next image")}</button>
|
||||||
|
<button aria-pressed={settings.paused} onclick={() => save({ ...settings, paused: !settings.paused })}>{settings.paused ? $t("Resume slideshow") : $t("Pause slideshow")}</button>
|
||||||
|
</div></div>
|
||||||
|
{:else if settings.source === "image"}
|
||||||
|
<div class="background-preview" role="img" aria-label={$t("Background image preview")}
|
||||||
|
style:background-image={previewUrl ? `${overlayShade}, url("${previewUrl}")` : "none"}
|
||||||
|
style:background-size={layout ? `100% 100%, ${layout.size}` : undefined}
|
||||||
|
style:background-position={layout ? `center, ${layout.position}` : undefined}><span>{$t("Background")}</span></div>
|
||||||
|
<div class="actions">
|
||||||
|
<button onclick={() => imageInput.click()}>{$t("Choose image…")}</button>
|
||||||
|
{#if image}<button onclick={() => void removeImage()}>{$t("Remove image")}</button>{/if}
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
{#if layout}
|
||||||
|
<div class="setting-row"><span>{$t("Image position")}</span><button class="picker" aria-label={$t("Image position")} aria-haspopup="menu"
|
||||||
|
onclick={event => picker(event, $t("Image position"), BACKGROUND_POSITIONS.map((value, index) => ({ label: positionLabels[index], checked: layout?.position === value, run: () => changeLayout({ position: value }) })))}>{positionLabels[BACKGROUND_POSITIONS.indexOf(layout.position)]}<Icon icon="chevron-down" /></button></div>
|
||||||
|
<div class="setting-row"><span>{$t("Image size")}</span><button class="picker" aria-label={$t("Image size")} aria-haspopup="menu"
|
||||||
|
onclick={event => picker(event, $t("Image size"), BACKGROUND_SIZES.map((value, index) => ({ label: sizeLabels[index], checked: layout?.size === value, run: () => changeLayout({ size: value }) })))}>{sizeLabels[BACKGROUND_SIZES.indexOf(layout.size)]}<Icon icon="chevron-down" /></button></div>
|
||||||
|
<div class="setting-row"><span>{$t("Image overlay")}</span><div class="controls overlay-controls">
|
||||||
|
<input type="range" aria-label={$t("Image overlay")} min="-100" max="100" value={Math.round(layout.overlay * 100)} oninput={event => changeOverlay(event.currentTarget)} />
|
||||||
|
<label class="overlay-value"><input type="number" aria-label={$t("Image overlay percentage")} min="-100" max="100" step="1" value={Math.round(layout.overlay * 100)}
|
||||||
|
oninput={event => changeOverlay(event.currentTarget)} onblur={event => { event.currentTarget.value = String(Math.round((layout?.overlay ?? 0) * 100)); }} /><span>%</span></label>
|
||||||
|
</div></div>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
<input bind:this={imageInput} type="file" accept="image/png,image/jpeg,image/webp,image/gif" aria-label={$t("Background image file")} hidden onchange={event => void importImage(event.currentTarget.files?.[0])} />
|
||||||
|
{#if settings.source === "folder"}
|
||||||
|
<p>{$t("Add PNG, JPEG, GIF, or WebP images to the folder. Portrait images show in full over a blurred fill.")}</p>
|
||||||
|
{#if folderNote}<p role="status">{folderNote}</p>{/if}
|
||||||
|
{:else if settings.source === "image"}
|
||||||
|
<p>{$t("PNG, JPEG, WebP, or GIF, up to 50 MiB. The image stays on this device.")}</p>
|
||||||
|
{:else}
|
||||||
|
<p>{$t("Choose a folder for a slideshow, or one image.")}</p>
|
||||||
|
{/if}
|
||||||
|
{#if layout}<p>{$t("Move the overlay left to lighten the image or right to darken it.")}</p>{/if}
|
||||||
|
{#if settings.source === "folder" && folder}
|
||||||
|
<ImageEditor {settings} />
|
||||||
|
{/if}
|
||||||
|
{#if settings.source !== "none"}
|
||||||
|
<fieldset class="targets">
|
||||||
|
<legend>{$t("Show the background in")}</legend>
|
||||||
|
{#each targets as target (target.id)}
|
||||||
|
<label class="check"><input type="checkbox" checked={settings.targets.includes(target.id)} onchange={event => toggleTarget(target.id, event.currentTarget.checked)} /><span>{target.name}</span></label>
|
||||||
|
{/each}
|
||||||
|
{#if boardsNote}<p>{boardsNote}</p>{/if}
|
||||||
|
</fieldset>
|
||||||
|
{/if}
|
||||||
|
{#if error}<p role="alert">{error}</p>{/if}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<style>
|
||||||
|
.background-settings { display: grid; gap: var(--rs-settings-gap); min-width: 0; }
|
||||||
|
p { margin: 0; color: var(--rs-text-dim); font-size: var(--rs-settings-description-size); line-height: 1.5; overflow-wrap: anywhere; }
|
||||||
|
.card { padding: 0 var(--rs-settings-row-padding); border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); background: var(--rs-bg-elevated); min-width: 0; }
|
||||||
|
.setting-row { display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: var(--rs-settings-gap); padding: var(--rs-settings-row-padding) 0; min-width: 0; }
|
||||||
|
.card > * + * { border-top: 1px solid var(--rs-border); }
|
||||||
|
.controls { display: flex; align-items: center; flex-wrap: wrap; gap: var(--rs-settings-gap); min-width: 0; max-width: 100%; }
|
||||||
|
.folder-controls { flex: 1 1 320px; justify-content: flex-end; }
|
||||||
|
.folder-controls input { flex: 1 1 160px; min-width: 120px; width: 0; }
|
||||||
|
input:not([type=checkbox]):not([type=range]), button { min-height: var(--rs-settings-control-height); box-sizing: border-box; padding: 4px 8px; border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); background: var(--rs-bg); color: var(--rs-text); font: inherit; }
|
||||||
|
button { display: inline-flex; align-items: center; gap: 6px; background: var(--rs-bg-elevated); cursor: pointer; }
|
||||||
|
button:hover { background: var(--rs-bg-active); }
|
||||||
|
button[aria-pressed="true"] { border-color: var(--rs-accent); }
|
||||||
|
button :global(svg) { width: 14px; height: 14px; flex-shrink: 0; fill: none; stroke: currentColor; stroke-width: 2; }
|
||||||
|
.picker { max-width: 100%; background: var(--rs-bg); }
|
||||||
|
input[type=number] { width: 88px; }
|
||||||
|
:is(button, input):focus-visible { outline: 2px solid var(--rs-focus); outline-offset: 2px; }
|
||||||
|
.actions { display: flex; flex-wrap: wrap; gap: var(--rs-settings-gap); padding: var(--rs-settings-row-padding) 0; }
|
||||||
|
.background-preview { height: 120px; margin-top: var(--rs-settings-row-padding); background-color: var(--rs-bg); background-repeat: no-repeat; border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); display: grid; place-items: center; }
|
||||||
|
.background-preview span { padding: 8px 14px; background: var(--rs-bg-elevated); border-radius: var(--rs-control-radius); }
|
||||||
|
.overlay-controls input[type=range] { width: 160px; max-width: 100%; min-width: 0; appearance: none; background: transparent; height: var(--rs-settings-control-height); margin: 0; cursor: pointer; }
|
||||||
|
.overlay-controls input[type=range]::-webkit-slider-runnable-track { height: 6px; background: var(--rs-bg-active); border: 1px solid var(--rs-text-dim); border-radius: var(--rs-control-radius); }
|
||||||
|
.overlay-controls input[type=range]::-webkit-slider-thumb { appearance: none; width: 18px; height: 18px; margin-top: -7px; background: var(--rs-accent); border: 2px solid var(--rs-text-strong); border-radius: 50%; }
|
||||||
|
.overlay-controls input[type=range]::-moz-range-track { height: 4px; background: var(--rs-bg-active); border: 1px solid var(--rs-text-dim); border-radius: var(--rs-control-radius); }
|
||||||
|
.overlay-controls input[type=range]::-moz-range-thumb { width: 14px; height: 14px; background: var(--rs-accent); border: 2px solid var(--rs-text-strong); border-radius: 50%; }
|
||||||
|
.overlay-controls input[type=range]:focus-visible { outline: 2px solid var(--rs-focus); outline-offset: 2px; border-radius: var(--rs-control-radius); }
|
||||||
|
.overlay-value { display: flex; align-items: center; gap: 4px; }
|
||||||
|
.overlay-value input { width: 64px; }
|
||||||
|
.targets { display: grid; gap: 2px; min-width: 0; margin: var(--rs-settings-gap) 0 0; padding: var(--rs-settings-row-padding); border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); background: var(--rs-bg-elevated); }
|
||||||
|
.targets legend { padding: 0 4px; color: var(--rs-text); }
|
||||||
|
.check { display: flex; align-items: center; gap: var(--rs-settings-gap); min-height: var(--rs-settings-control-height); overflow-wrap: anywhere; }
|
||||||
|
.check input { flex-shrink: 0; accent-color: var(--rs-accent); }
|
||||||
|
[role=alert] { color: var(--rs-error); }
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,227 @@
|
|||||||
|
<!--
|
||||||
|
The appearance of one image of the folder: fit, position, and overlay. It saves the sidecar file of the folder
|
||||||
|
(`.runestone-backgrounds.json`) only when the file did not change since the read. Then every window reads it again.
|
||||||
|
-->
|
||||||
|
<script lang="ts">
|
||||||
|
import { onDestroy, untrack } from "svelte";
|
||||||
|
import { t, tr } from "$lib/i18n";
|
||||||
|
import Icon from "$lib/ui/Icon.svelte";
|
||||||
|
import { showActionMenu } from "$lib/ui/managedActionMenu";
|
||||||
|
import { BACKGROUND_POSITIONS } from "$lib/theme/appearance";
|
||||||
|
import { normalizeLayout, type BackgroundSettings } from "../backgroundSettings";
|
||||||
|
import { folderHost, sendBackgroundCommand } from "./sources";
|
||||||
|
import { imageAppearance, imageFits, imageNames, parseImageSettings, sidecarName, type ImageAppearance, type ImageSettings } from "./imageSettings";
|
||||||
|
|
||||||
|
let { settings }: { settings: BackgroundSettings } = $props();
|
||||||
|
|
||||||
|
let names = $state<string[]>([]);
|
||||||
|
let selected = $state("");
|
||||||
|
let query = $state("");
|
||||||
|
let pickerOpen = $state(false);
|
||||||
|
let draft = $state<ImageAppearance>({ fit: "cover", position: "center", overlay: 0 });
|
||||||
|
let baseline = $state<ImageAppearance>({ fit: "cover", position: "center", overlay: 0 });
|
||||||
|
let saved = $state<ImageSettings>({ schema: 1, images: {} });
|
||||||
|
let source: string | null = null;
|
||||||
|
let url = $state("");
|
||||||
|
let portrait = false;
|
||||||
|
let loaded = $state(false);
|
||||||
|
let busy = $state(false);
|
||||||
|
let status = $state({ text: "", error: false });
|
||||||
|
let generation = 0;
|
||||||
|
let closed = false;
|
||||||
|
let closeMenu = () => {};
|
||||||
|
let trigger: HTMLButtonElement | undefined = $state();
|
||||||
|
let search: HTMLInputElement | undefined = $state();
|
||||||
|
const pickerId = $props.id();
|
||||||
|
|
||||||
|
const filtered = $derived(names.filter(name => name.toLocaleLowerCase().includes(query.trim().toLocaleLowerCase())));
|
||||||
|
const fitLabels = $derived<Record<string, string>>({ cover: $t("Fill"), contain: $t("Fit"), auto: $t("Actual size"), blurred: $t("Full image with blurred fill") });
|
||||||
|
const positionLabels = $derived([$t("Center"), $t("Top left"), $t("Top center"), $t("Top right"), $t("Center left"), $t("Center right"), $t("Bottom left"), $t("Bottom center"), $t("Bottom right")]);
|
||||||
|
const changed = $derived(draft.fit !== baseline.fit || draft.position !== baseline.position || draft.overlay !== baseline.overlay);
|
||||||
|
|
||||||
|
const report = (reason: unknown) => { if (!closed) status = { text: reason instanceof Error ? reason.message : String(reason), error: true }; };
|
||||||
|
|
||||||
|
/** The values that differ from the inherited appearance. Only these go to the file. */
|
||||||
|
function changes(): Partial<ImageAppearance> {
|
||||||
|
return {
|
||||||
|
...(draft.fit !== baseline.fit ? { fit: draft.fit } : {}),
|
||||||
|
...(draft.position !== baseline.position ? { position: draft.position } : {}),
|
||||||
|
...(draft.overlay !== baseline.overlay ? { overlay: draft.overlay } : {}),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async function load() {
|
||||||
|
const revision = ++generation;
|
||||||
|
loaded = false; pickerOpen = false; names = [];
|
||||||
|
if (url) URL.revokeObjectURL(url);
|
||||||
|
url = "";
|
||||||
|
try {
|
||||||
|
const [text, list] = await Promise.all([folderHost.readSidecar(), folderHost.list()]);
|
||||||
|
if (closed || revision !== generation) return;
|
||||||
|
saved = parseImageSettings(text); source = text;
|
||||||
|
names = imageNames(list);
|
||||||
|
if (!names.includes(selected)) selected = names[0] ?? "";
|
||||||
|
if (selected) await choose(selected);
|
||||||
|
else status = { text: tr("No supported images in this folder. Add PNG, JPEG, GIF, or WebP files."), error: false };
|
||||||
|
} catch (reason) { report(reason); }
|
||||||
|
}
|
||||||
|
|
||||||
|
async function choose(name: string) {
|
||||||
|
const revision = ++generation;
|
||||||
|
selected = name; loaded = false;
|
||||||
|
if (url) URL.revokeObjectURL(url);
|
||||||
|
url = "";
|
||||||
|
try {
|
||||||
|
const next = URL.createObjectURL(await folderHost.read(name));
|
||||||
|
try {
|
||||||
|
const image = new Image(); image.src = next; await image.decode();
|
||||||
|
if (closed || revision !== generation) { URL.revokeObjectURL(next); return; }
|
||||||
|
portrait = image.naturalHeight > image.naturalWidth;
|
||||||
|
} catch (error) { URL.revokeObjectURL(next); throw error; }
|
||||||
|
url = next;
|
||||||
|
draft = imageAppearance(normalizeLayout(settings), saved.images[name], portrait);
|
||||||
|
baseline = { ...draft };
|
||||||
|
loaded = true;
|
||||||
|
status = { text: saved.images[name] ? tr("Saved appearance.") : tr("Default appearance."), error: false };
|
||||||
|
} catch (reason) { report(reason); }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A change of the folder layout changes the inherited values. Keep the edits of the user. */
|
||||||
|
function inherit() {
|
||||||
|
if (!loaded) return;
|
||||||
|
const next = imageAppearance(normalizeLayout(settings), saved.images[selected], portrait);
|
||||||
|
if (next.fit === baseline.fit && next.position === baseline.position && next.overlay === baseline.overlay) return;
|
||||||
|
const edited = changes();
|
||||||
|
baseline = next;
|
||||||
|
draft = { ...next, ...edited };
|
||||||
|
}
|
||||||
|
|
||||||
|
async function write(reset: boolean) {
|
||||||
|
if (!loaded || busy) return;
|
||||||
|
const edited = changes();
|
||||||
|
if (!reset && !Object.keys(edited).length) return;
|
||||||
|
busy = true;
|
||||||
|
const revision = generation, name = selected;
|
||||||
|
try {
|
||||||
|
const next = structuredClone($state.snapshot(saved)) as ImageSettings;
|
||||||
|
if (reset) delete next.images[name]; else next.images[name] = { ...next.images[name], ...edited };
|
||||||
|
const contents = JSON.stringify(next, null, 2) + "\n";
|
||||||
|
await folderHost.writeSidecar(contents, source);
|
||||||
|
if (closed || revision !== generation) return;
|
||||||
|
source = contents; saved = next;
|
||||||
|
draft = imageAppearance(normalizeLayout(settings), saved.images[name], portrait);
|
||||||
|
baseline = { ...draft };
|
||||||
|
status = { text: reset ? tr("Default appearance restored.") : tr("Image appearance saved."), error: false };
|
||||||
|
await sendBackgroundCommand("reload");
|
||||||
|
} catch (reason) { report(reason); }
|
||||||
|
finally { busy = false; }
|
||||||
|
}
|
||||||
|
|
||||||
|
function menu(event: MouseEvent, field: "fit" | "position") {
|
||||||
|
closeMenu();
|
||||||
|
const anchor = event.currentTarget as HTMLButtonElement;
|
||||||
|
const bounds = anchor.getBoundingClientRect();
|
||||||
|
const values: readonly string[] = field === "fit" ? imageFits : BACKGROUND_POSITIONS;
|
||||||
|
closeMenu = showActionMenu({ x: bounds.left, y: bounds.bottom + 4, label: field === "fit" ? $t("Image fit") : $t("Position of this image"), parent: anchor.closest("dialog") ?? undefined,
|
||||||
|
items: values.map((value, index) => ({ label: field === "fit" ? fitLabels[value] : positionLabels[index], radio: true, checked: draft[field] === value,
|
||||||
|
run: () => { draft = { ...draft, [field]: value }; } })) }).close;
|
||||||
|
}
|
||||||
|
|
||||||
|
function overlay(input: HTMLInputElement) {
|
||||||
|
if (input.validity.valid && Number.isFinite(input.valueAsNumber)) draft = { ...draft, overlay: Math.round(Math.max(-100, Math.min(100, input.valueAsNumber))) / 100 };
|
||||||
|
}
|
||||||
|
|
||||||
|
function openPicker() {
|
||||||
|
if (pickerOpen) { pickerOpen = false; return; }
|
||||||
|
query = ""; pickerOpen = true;
|
||||||
|
queueMicrotask(() => search?.focus());
|
||||||
|
}
|
||||||
|
|
||||||
|
function pick(name: string) {
|
||||||
|
pickerOpen = false;
|
||||||
|
void choose(name).then(() => trigger?.focus());
|
||||||
|
}
|
||||||
|
|
||||||
|
function moveFocus(event: KeyboardEvent, list: HTMLElement) {
|
||||||
|
const rows = [...list.querySelectorAll<HTMLButtonElement>("button")];
|
||||||
|
if (!rows.length) return;
|
||||||
|
const index = rows.indexOf(document.activeElement as HTMLButtonElement);
|
||||||
|
const next = event.key === "Home" ? 0 : event.key === "End" ? rows.length - 1 : index < 0 ? (event.key === "ArrowDown" ? 0 : rows.length - 1) : Math.max(0, Math.min(rows.length - 1, index + (event.key === "ArrowDown" ? 1 : -1)));
|
||||||
|
event.preventDefault();
|
||||||
|
rows[next].focus();
|
||||||
|
}
|
||||||
|
|
||||||
|
$effect(() => { void settings.size; void settings.position; void settings.overlay; untrack(inherit); });
|
||||||
|
void load();
|
||||||
|
onDestroy(() => { closed = true; generation++; closeMenu(); if (url) URL.revokeObjectURL(url); });
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<details class="image-editor">
|
||||||
|
<summary>{$t("Per-image appearance")}</summary>
|
||||||
|
<p>{$t("Choose an image to change its fit, position, and overlay. Portrait images show in full over a blurred fill by default.")}</p>
|
||||||
|
<fieldset disabled={busy}>
|
||||||
|
<div class="row"><span>{$t("Image")}</span>
|
||||||
|
<button bind:this={trigger} class="choice" aria-label={$t("Image to change")} aria-expanded={pickerOpen} aria-controls={pickerId} disabled={!names.length} onclick={openPicker}>
|
||||||
|
<span class="name">{selected || $t("Choose an image")}</span><Icon icon="chevron-down" /></button></div>
|
||||||
|
{#if pickerOpen}
|
||||||
|
<!-- svelte-ignore a11y_no_static_element_interactions (Escape closes the picker.) -->
|
||||||
|
<div id={pickerId} class="rs-picker image-picker" onkeydown={event => { if (event.key === "Escape") { event.preventDefault(); event.stopPropagation(); pickerOpen = false; trigger?.focus(); } }}>
|
||||||
|
<input bind:this={search} type="search" aria-label={$t("Find an image")} placeholder={$t("Find an image")} bind:value={query}
|
||||||
|
onkeydown={event => { if (event.key === "ArrowDown" || event.key === "ArrowUp") moveFocus(event, event.currentTarget.nextElementSibling as HTMLElement); else if (event.key === "Enter" && filtered[0]) { event.preventDefault(); pick(filtered[0]); } }} />
|
||||||
|
<div class="options" role="listbox" aria-label={$t("Image files")} tabindex="-1"
|
||||||
|
onkeydown={event => { if (["ArrowDown", "ArrowUp", "Home", "End"].includes(event.key)) moveFocus(event, event.currentTarget); }}>
|
||||||
|
{#each filtered.slice(0, 100) as name (name)}
|
||||||
|
<button class="rs-picker-row" role="option" tabindex="-1" aria-selected={name === selected} onclick={() => pick(name)}>{name}</button>
|
||||||
|
{/each}
|
||||||
|
</div>
|
||||||
|
<p role="status">{!filtered.length ? $t("No matching images.") : filtered.length > 100 ? $t("{count} matches. Type more of the name to see other images.", { count: filtered.length }) : $t(filtered.length === 1 ? "{count} image." : "{count} images.", { count: filtered.length })}</p>
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
<div class="preview" role="img" aria-label={selected ? $t("Selected image preview: {name}", { name: selected }) : $t("Selected image preview")}>
|
||||||
|
{#if url}
|
||||||
|
{#if draft.fit === "blurred"}<span class="fill" style:background-image={`url("${url}")`}></span>{/if}
|
||||||
|
<span class="foreground" style:background-image={`url("${url}")`} style:background-size={draft.fit === "blurred" ? "contain" : draft.fit} style:background-position={draft.position}></span>
|
||||||
|
{/if}
|
||||||
|
<span class="shade" style:background={draft.overlay < 0 ? "white" : "black"} style:opacity={String(Math.abs(draft.overlay))}></span>
|
||||||
|
</div>
|
||||||
|
<div class="row"><span>{$t("Fit")}</span><button class="choice" aria-label={$t("Image fit")} aria-haspopup="menu" disabled={!loaded} onclick={event => menu(event, "fit")}>{fitLabels[draft.fit]}<Icon icon="chevron-down" /></button></div>
|
||||||
|
<div class="row"><span>{$t("Position")}</span><button class="choice" aria-label={$t("Position of this image")} aria-haspopup="menu" disabled={!loaded} onclick={event => menu(event, "position")}>{positionLabels[BACKGROUND_POSITIONS.indexOf(draft.position)]}<Icon icon="chevron-down" /></button></div>
|
||||||
|
<div class="row"><span>{$t("Overlay")}</span><div class="controls">
|
||||||
|
<input type="range" min="-100" max="100" aria-label={$t("Overlay of this image")} disabled={!loaded} value={Math.round(draft.overlay * 100)} oninput={event => overlay(event.currentTarget)} />
|
||||||
|
<input type="number" min="-100" max="100" step="1" required aria-label={$t("Overlay percentage of this image")} disabled={!loaded} value={Math.round(draft.overlay * 100)} oninput={event => overlay(event.currentTarget)} /><span>%</span>
|
||||||
|
</div></div>
|
||||||
|
<div class="controls">
|
||||||
|
<button disabled={!loaded || !changed} onclick={() => void write(false)}><Icon icon="save" />{$t("Save image appearance")}</button>
|
||||||
|
<button disabled={!loaded || !saved.images[selected]} onclick={() => void write(true)}><Icon icon="undo" />{$t("Reset image appearance")}</button>
|
||||||
|
<button onclick={() => void load()}><Icon icon="refresh" />{$t("Reload image settings")}</button>
|
||||||
|
</div>
|
||||||
|
</fieldset>
|
||||||
|
{#if status.text}<p role={status.error ? "alert" : "status"} class:error={status.error}>{status.text}</p>{/if}
|
||||||
|
</details>
|
||||||
|
|
||||||
|
<style>
|
||||||
|
.image-editor { display: grid; gap: var(--rs-settings-gap); min-width: 0; padding: var(--rs-settings-row-padding); border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); background: var(--rs-bg-elevated); }
|
||||||
|
summary { cursor: pointer; min-height: var(--rs-settings-control-height); line-height: var(--rs-settings-control-height); border-radius: var(--rs-control-radius); }
|
||||||
|
p { margin: 0; color: var(--rs-text-dim); font-size: var(--rs-settings-description-size); line-height: 1.5; overflow-wrap: anywhere; }
|
||||||
|
.error { color: var(--rs-error); }
|
||||||
|
fieldset { display: grid; gap: var(--rs-settings-gap); min-width: 0; margin: var(--rs-settings-gap) 0 0; padding: 0; border: 0; }
|
||||||
|
.row { display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: var(--rs-settings-gap); min-width: 0; }
|
||||||
|
.controls { display: flex; align-items: center; flex-wrap: wrap; gap: var(--rs-settings-gap); min-width: 0; }
|
||||||
|
button:not(.rs-picker-row), input:not([type=range]) { min-height: var(--rs-settings-control-height); box-sizing: border-box; padding: 4px 8px; border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); background: var(--rs-bg); color: var(--rs-text); font: inherit; }
|
||||||
|
button:not(.rs-picker-row) { display: inline-flex; align-items: center; gap: 6px; cursor: pointer; }
|
||||||
|
button:not(.rs-picker-row):hover:not(:disabled) { background: var(--rs-bg-active); }
|
||||||
|
button:disabled, input:disabled { opacity: .55; cursor: default; }
|
||||||
|
button :global(svg) { width: 14px; height: 14px; flex-shrink: 0; fill: none; stroke: currentColor; stroke-width: 2; }
|
||||||
|
:is(button, input, summary):focus-visible { outline: 2px solid var(--rs-focus); outline-offset: 2px; }
|
||||||
|
.choice { max-width: 100%; min-width: 0; }
|
||||||
|
.choice .name { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||||
|
input[type=number] { width: 72px; }
|
||||||
|
input[type=range] { width: 160px; max-width: 100%; accent-color: var(--rs-accent); }
|
||||||
|
.image-picker { display: grid; gap: var(--rs-settings-gap); width: 100%; min-width: 0; position: static; }
|
||||||
|
.image-picker input { width: 100%; min-width: 0; }
|
||||||
|
.options { display: grid; gap: 2px; max-height: 220px; overflow: auto; min-width: 0; }
|
||||||
|
.options button { justify-content: flex-start; text-align: left; overflow-wrap: anywhere; }
|
||||||
|
.preview { position: relative; width: 100%; height: 170px; overflow: hidden; border-radius: var(--rs-control-radius); background-color: var(--rs-bg-active); }
|
||||||
|
.fill, .foreground, .shade { position: absolute; inset: 0; background-repeat: no-repeat; pointer-events: none; }
|
||||||
|
.fill { inset: -24px; filter: blur(18px); background-size: cover; background-position: center; }
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,83 @@
|
|||||||
|
// The blurred fill of a portrait image. One worker does the decode, the resize, and the filter away from the
|
||||||
|
// input and paint work of the window. It lives as long as the Background instance.
|
||||||
|
import { tr } from "../../i18n/index.ts";
|
||||||
|
|
||||||
|
const workerSource = `
|
||||||
|
self.onmessage = async ({ data: { id, url, width, height } }) => {
|
||||||
|
let image;
|
||||||
|
try {
|
||||||
|
const source = await (await fetch(url)).blob();
|
||||||
|
image = await createImageBitmap(source, { resizeWidth: width, resizeHeight: height, resizeQuality: 'high' });
|
||||||
|
const canvas = new OffscreenCanvas(width, height);
|
||||||
|
const context = canvas.getContext('2d');
|
||||||
|
context.filter = 'blur(24px)';
|
||||||
|
context.drawImage(image, -48, -48, width + 96, height + 96);
|
||||||
|
self.postMessage({ id, blob: await canvas.convertToBlob({ type: 'image/png' }) });
|
||||||
|
} catch (error) {
|
||||||
|
self.postMessage({ id, error: error instanceof Error ? error.message : String(error) });
|
||||||
|
} finally { image?.close(); }
|
||||||
|
};`;
|
||||||
|
|
||||||
|
/** The size of the blurred copy. Its long side is at most 1024 pixels. */
|
||||||
|
export function blurSize(width: number, height: number): { width: number; height: number } {
|
||||||
|
const scale = Math.min(1, 1024 / Math.max(width, height, 1));
|
||||||
|
return { width: Math.max(1, Math.round(width * scale)), height: Math.max(1, Math.round(height * scale)) };
|
||||||
|
}
|
||||||
|
|
||||||
|
export class BlurWorker {
|
||||||
|
private worker?: Worker;
|
||||||
|
private workerUrl?: string;
|
||||||
|
private serial = 0;
|
||||||
|
private pending = new Map<number, { resolve: (blob: Blob) => void; reject: (error: Error) => void; timer: ReturnType<typeof setTimeout> }>();
|
||||||
|
|
||||||
|
/** A blob URL of the blurred copy of the image at `url`. The caller releases it. */
|
||||||
|
async blur(url: string, width: number, height: number): Promise<string> {
|
||||||
|
const size = blurSize(width, height);
|
||||||
|
if (typeof Worker === "undefined" || typeof OffscreenCanvas === "undefined") return URL.createObjectURL(await this.inWindow(url, size));
|
||||||
|
const worker = this.start();
|
||||||
|
const id = ++this.serial;
|
||||||
|
const blob = await new Promise<Blob>((resolve, reject) => {
|
||||||
|
const timer = setTimeout(() => { this.pending.delete(id); reject(new Error(tr("The blurred image took too long to load."))); }, 10000);
|
||||||
|
this.pending.set(id, { resolve, reject, timer });
|
||||||
|
worker.postMessage({ id, url, ...size });
|
||||||
|
});
|
||||||
|
return URL.createObjectURL(blob);
|
||||||
|
}
|
||||||
|
|
||||||
|
private start(): Worker {
|
||||||
|
if (this.worker) return this.worker;
|
||||||
|
this.workerUrl = URL.createObjectURL(new Blob([workerSource], { type: "text/javascript" }));
|
||||||
|
const worker = this.worker = new Worker(this.workerUrl);
|
||||||
|
worker.onmessage = ({ data }) => {
|
||||||
|
const request = this.pending.get(data?.id);
|
||||||
|
if (!request) return;
|
||||||
|
this.pending.delete(data.id); clearTimeout(request.timer);
|
||||||
|
if (data.blob instanceof Blob) request.resolve(data.blob);
|
||||||
|
else request.reject(new Error(data.error || tr("Cannot create the blurred image.")));
|
||||||
|
};
|
||||||
|
worker.onerror = () => this.fail(new Error(tr("Cannot create the blurred image.")));
|
||||||
|
return worker;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A fallback for a window without OffscreenCanvas. */
|
||||||
|
private async inWindow(url: string, size: { width: number; height: number }): Promise<Blob> {
|
||||||
|
const image = new Image(); image.src = url; await image.decode();
|
||||||
|
const canvas = document.createElement("canvas");
|
||||||
|
canvas.width = size.width; canvas.height = size.height;
|
||||||
|
const context = canvas.getContext("2d")!;
|
||||||
|
context.filter = "blur(24px)";
|
||||||
|
context.drawImage(image, -48, -48, size.width + 96, size.height + 96);
|
||||||
|
return new Promise<Blob>((resolve, reject) => canvas.toBlob(value => value ? resolve(value) : reject(new Error(tr("Cannot create the blurred image."))), "image/png"));
|
||||||
|
}
|
||||||
|
|
||||||
|
private fail(error: Error) {
|
||||||
|
for (const request of this.pending.values()) { clearTimeout(request.timer); request.reject(error); }
|
||||||
|
this.pending.clear();
|
||||||
|
// A failed worker starts again at the next request.
|
||||||
|
this.worker?.terminate(); this.worker = undefined;
|
||||||
|
if (this.workerUrl) URL.revokeObjectURL(this.workerUrl);
|
||||||
|
this.workerUrl = undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
dispose() { this.fail(new Error(tr("This feature is off."))); }
|
||||||
|
}
|
||||||
@@ -0,0 +1,337 @@
|
|||||||
|
// The Background engine: it shows the images of a source as background frames, one after the other.
|
||||||
|
// It comes from the engine of the Background Slideshow plugin, with these changes for the open card
|
||||||
|
// "Lag before image transition": the next image loads and decodes before its fade, the blurred fills of the
|
||||||
|
// last images stay in a cache, and the folder list and the sidecar are read again only after a settings change,
|
||||||
|
// on window focus, or after every 10 images.
|
||||||
|
import { tr } from "../../i18n/index.ts";
|
||||||
|
import type { BackgroundFrame } from "../../plugins/backgroundContracts.ts";
|
||||||
|
import type { BackgroundLayout } from "../backgroundSettings.ts";
|
||||||
|
import { imageAppearance, imageNames, parseImageSettings, sequence, type ImageAppearance, type ImageSettings } from "./imageSettings.ts";
|
||||||
|
|
||||||
|
/** The time of the fade from one image to the next. */
|
||||||
|
export const transitionMs = 2000;
|
||||||
|
/** The folder list and the sidecar are read again after this number of images. */
|
||||||
|
export const RESCAN_SLIDES = 10;
|
||||||
|
/** The number of blurred fills that stay in the cache. */
|
||||||
|
export const BLUR_CACHE = 3;
|
||||||
|
/** The shortest wait before a new try after an error. */
|
||||||
|
export const RETRY_MS = 5000;
|
||||||
|
|
||||||
|
/** Where the images come from: the image folder of the host, or the one saved image. */
|
||||||
|
export interface ImageSource {
|
||||||
|
/** A different key means a different folder or image. The engine then starts again. */
|
||||||
|
readonly key: string;
|
||||||
|
/** True for a folder: the images change on a timer, and the sidecar and the portrait default apply. */
|
||||||
|
readonly timed: boolean;
|
||||||
|
/** The image names. */
|
||||||
|
list(): Promise<string[]>;
|
||||||
|
read(name: string): Promise<Blob>;
|
||||||
|
/** The text of the sidecar file, or null. */
|
||||||
|
sidecar(): Promise<string | null>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface LoadedImage { url: string; width: number; height: number }
|
||||||
|
|
||||||
|
/** The browser services of the engine. Tests replace them. */
|
||||||
|
export interface Runtime {
|
||||||
|
/** Make a blob URL and decode the image before it shows. */
|
||||||
|
load(blob: Blob): Promise<LoadedImage>;
|
||||||
|
/** Make the blurred fill of a loaded image. The engine releases the URL. */
|
||||||
|
blur(image: LoadedImage): Promise<string>;
|
||||||
|
release(url: string): void;
|
||||||
|
later(callback: () => void, milliseconds: number): unknown;
|
||||||
|
cancel(timer: unknown): void;
|
||||||
|
random(): number;
|
||||||
|
now(): number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Frames { set(target: string, frame: BackgroundFrame | null): void }
|
||||||
|
|
||||||
|
export interface EngineSettings extends BackgroundLayout {
|
||||||
|
seconds: number;
|
||||||
|
order: "name" | "random";
|
||||||
|
paused: boolean;
|
||||||
|
targets: string[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Status { message: string; image: string | null; count: number; error: boolean }
|
||||||
|
|
||||||
|
interface Shown { name: string; key: string; image: LoadedImage; appearance: ImageAppearance; blurred?: string }
|
||||||
|
interface Prepared { name: string; key: string; image: LoadedImage }
|
||||||
|
|
||||||
|
function toFrame(shown: Shown): BackgroundFrame {
|
||||||
|
const frame: BackgroundFrame = { url: shown.image.url, overlay: shown.appearance.overlay, position: shown.appearance.position,
|
||||||
|
size: shown.appearance.fit === "blurred" ? "contain" : shown.appearance.fit };
|
||||||
|
if (shown.blurred) frame.blurredUrl = shown.blurred;
|
||||||
|
return frame;
|
||||||
|
}
|
||||||
|
|
||||||
|
const sameAppearance = (a: ImageAppearance, b: ImageAppearance) => a.fit === b.fit && a.position === b.position && a.overlay === b.overlay;
|
||||||
|
|
||||||
|
export class Slideshow {
|
||||||
|
status: Status = { message: "", image: null, count: 0, error: false };
|
||||||
|
private source: ImageSource | null = null;
|
||||||
|
private settings: EngineSettings | null = null;
|
||||||
|
private revision = 0;
|
||||||
|
private stopped = false;
|
||||||
|
private timer: unknown;
|
||||||
|
/** When the current timer fires, or null without a timer. */
|
||||||
|
private due: number | null = null;
|
||||||
|
private names: string[] | null = null;
|
||||||
|
private imageSettings: ImageSettings = { schema: 1, images: {} };
|
||||||
|
private sidecarError = "";
|
||||||
|
private stale = true;
|
||||||
|
private slides = 0;
|
||||||
|
private shown: Shown | null = null;
|
||||||
|
/** The image that the current frame fades from. */
|
||||||
|
private previous: Shown | null = null;
|
||||||
|
private targets = new Set<string>();
|
||||||
|
/** The blurred fills, oldest first. */
|
||||||
|
private blurs = new Map<string, string>();
|
||||||
|
private prepared: { name: string; work: Promise<Prepared | null>; discarded: boolean } | null = null;
|
||||||
|
/** Changes at each `clear`, so that a late blurred fill of an old image does not enter the cache. */
|
||||||
|
private epoch = 0;
|
||||||
|
private listeners = new Set<() => void>();
|
||||||
|
private frames: Frames;
|
||||||
|
private runtime: Runtime;
|
||||||
|
|
||||||
|
constructor(frames: Frames, runtime: Runtime) { this.frames = frames; this.runtime = runtime; }
|
||||||
|
|
||||||
|
subscribe(listener: () => void) { this.listeners.add(listener); return () => { this.listeners.delete(listener); }; }
|
||||||
|
private notify() { for (const listener of [...this.listeners]) listener(); }
|
||||||
|
|
||||||
|
/** Use a new source or new settings. The current image stays when the source is the same and still has it. */
|
||||||
|
configure(source: ImageSource | null, settings: EngineSettings): Promise<void> {
|
||||||
|
if (this.stopped) return Promise.resolve();
|
||||||
|
if (source?.key !== this.source?.key) {
|
||||||
|
this.clear();
|
||||||
|
this.names = null;
|
||||||
|
}
|
||||||
|
this.source = source;
|
||||||
|
this.settings = { ...settings, targets: [...settings.targets] };
|
||||||
|
this.stale = true;
|
||||||
|
return this.update(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Read the list and the sidecar again before the next image, for example after a window focus. */
|
||||||
|
invalidate() { this.stale = true; }
|
||||||
|
|
||||||
|
/** Read the list and the sidecar again now, and apply them to the current image. */
|
||||||
|
reload = () => { this.stale = true; return this.update(false); };
|
||||||
|
|
||||||
|
/** Show the next image now. */
|
||||||
|
next = () => this.update(true);
|
||||||
|
|
||||||
|
dispose() {
|
||||||
|
if (this.stopped) return;
|
||||||
|
this.stopped = true; this.revision++;
|
||||||
|
this.runtime.cancel(this.timer); this.timer = undefined;
|
||||||
|
this.clear(); this.listeners.clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
private async update(advance: boolean): Promise<void> {
|
||||||
|
if (this.stopped) return;
|
||||||
|
const revision = ++this.revision;
|
||||||
|
const remaining = this.due === null ? null : Math.max(0, this.due - this.runtime.now());
|
||||||
|
this.runtime.cancel(this.timer); this.timer = undefined; this.due = null;
|
||||||
|
const valid = () => !this.stopped && revision === this.revision;
|
||||||
|
const source = this.source, settings = this.settings;
|
||||||
|
try {
|
||||||
|
if (!source || !settings) { this.clear(); this.setStatus(tr("Choose a folder or an image to show a background.")); return; }
|
||||||
|
if (!settings.targets.length) { this.clear(); this.setStatus(tr("Select where to show the background.")); return; }
|
||||||
|
if (this.stale || !this.names) {
|
||||||
|
const [list, sidecar] = await Promise.all([source.list(), source.timed ? source.sidecar() : Promise.resolve(null)]);
|
||||||
|
if (!valid()) return;
|
||||||
|
this.names = source.timed ? imageNames(list) : [...list];
|
||||||
|
try { this.imageSettings = parseImageSettings(sidecar); this.sidecarError = ""; }
|
||||||
|
catch (reason) { this.imageSettings = { schema: 1, images: {} }; this.sidecarError = reason instanceof Error ? reason.message : String(reason); }
|
||||||
|
this.stale = false; this.slides = 0;
|
||||||
|
if (this.prepared && !this.names.includes(this.prepared.name)) this.discardPrepared();
|
||||||
|
}
|
||||||
|
const names = this.names;
|
||||||
|
this.status.count = names.length;
|
||||||
|
if (!names.length) throw new Error(tr("No supported images in this folder. Add PNG, JPEG, GIF, or WebP files."));
|
||||||
|
const shown = this.shown;
|
||||||
|
if (shown && names.includes(shown.name) && (!advance || names.length === 1)) {
|
||||||
|
await this.reapply(shown, settings, valid);
|
||||||
|
if (!valid()) return;
|
||||||
|
this.schedule(remaining ?? settings.seconds * 1000, revision);
|
||||||
|
this.prepare();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let failures = 0;
|
||||||
|
const order = sequence(names, shown?.name ?? null, settings.order, this.runtime.random);
|
||||||
|
const candidates = this.prepared && order.includes(this.prepared.name) ? [this.prepared.name, ...order.filter(name => name !== this.prepared!.name)] : order;
|
||||||
|
for (const name of candidates) {
|
||||||
|
let loaded: Prepared | null = null;
|
||||||
|
let next: Shown;
|
||||||
|
try {
|
||||||
|
loaded = await this.load(name);
|
||||||
|
if (!valid()) { if (loaded) this.runtime.release(loaded.image.url); return; }
|
||||||
|
if (!loaded) throw new Error(tr("The image cannot be displayed."));
|
||||||
|
next = { ...loaded, appearance: this.appearanceOf(name, loaded.image, settings) };
|
||||||
|
if (next.appearance.fit === "blurred") {
|
||||||
|
next.blurred = await this.blurOf(loaded);
|
||||||
|
if (!valid()) { this.runtime.release(loaded.image.url); return; }
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
if (loaded) this.runtime.release(loaded.image.url);
|
||||||
|
if (!valid()) return;
|
||||||
|
failures++; continue;
|
||||||
|
}
|
||||||
|
this.publish(next, settings, true);
|
||||||
|
const message = failures ? tr("{name}: skipped {count} unreadable images.", { name, count: failures }) : name;
|
||||||
|
this.status = { image: name, count: names.length, error: !!this.sidecarError, message: this.sidecarError ? `${message} ${this.sidecarError}` : message };
|
||||||
|
this.notify();
|
||||||
|
if (++this.slides >= RESCAN_SLIDES) this.stale = true;
|
||||||
|
this.schedule(settings.seconds * 1000, revision);
|
||||||
|
this.prepare();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
throw new Error(tr("No readable images in this folder. Check the image files."));
|
||||||
|
} catch (error) {
|
||||||
|
if (!valid()) return;
|
||||||
|
this.clear();
|
||||||
|
this.status = { ...this.status, image: null, error: true, message: error instanceof Error ? error.message : String(error) };
|
||||||
|
this.notify();
|
||||||
|
if (source?.timed && settings) this.schedule(Math.max(RETRY_MS, settings.seconds * 1000), revision, true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private setStatus(message: string) {
|
||||||
|
this.status = { message, image: null, count: 0, error: false };
|
||||||
|
this.notify();
|
||||||
|
}
|
||||||
|
|
||||||
|
private appearanceOf(name: string, image: LoadedImage, settings: EngineSettings): ImageAppearance {
|
||||||
|
if (!this.source?.timed) return { fit: settings.size, position: settings.position, overlay: settings.overlay };
|
||||||
|
return imageAppearance(settings, this.imageSettings.images[name], image.height > image.width);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The image of `name`: the prepared image when it matches, or a new read. */
|
||||||
|
private async load(name: string): Promise<Prepared | null> {
|
||||||
|
const prepared = this.prepared;
|
||||||
|
if (prepared?.name === name) {
|
||||||
|
this.prepared = null;
|
||||||
|
const result = await prepared.work.catch(() => null);
|
||||||
|
if (result) return result;
|
||||||
|
}
|
||||||
|
const source = this.source!;
|
||||||
|
const blob = await source.read(name);
|
||||||
|
const image = await this.runtime.load(blob);
|
||||||
|
return { name, key: `${source.key}\n${name}\n${blob.size}`, image };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Load and decode the next image of a timed source now, so that its fade starts on time. */
|
||||||
|
private prepare() {
|
||||||
|
const source = this.source, settings = this.settings, names = this.names, shown = this.shown;
|
||||||
|
if (!source?.timed || !settings || settings.paused || !names || names.length < 2 || !shown || this.prepared) return;
|
||||||
|
const name = sequence(names, shown.name, settings.order, this.runtime.random)[0];
|
||||||
|
const entry: { name: string; work: Promise<Prepared | null>; discarded: boolean } = { name, work: Promise.resolve(null), discarded: false };
|
||||||
|
entry.work = (async (): Promise<Prepared | null> => {
|
||||||
|
const blob = await source.read(name);
|
||||||
|
const image = await this.runtime.load(blob);
|
||||||
|
// A prepared image that nobody wants any more goes away at once.
|
||||||
|
if (this.stopped || entry.discarded) { this.runtime.release(image.url); return null; }
|
||||||
|
const result = { name, key: `${source.key}\n${name}\n${blob.size}`, image };
|
||||||
|
const appearance = imageAppearance(settings, this.imageSettings.images[name], image.height > image.width);
|
||||||
|
if (appearance.fit === "blurred") await this.blurOf(result).catch(() => undefined);
|
||||||
|
return result;
|
||||||
|
})();
|
||||||
|
entry.work.catch(() => undefined);
|
||||||
|
this.prepared = entry;
|
||||||
|
}
|
||||||
|
|
||||||
|
private discardPrepared() {
|
||||||
|
const prepared = this.prepared;
|
||||||
|
this.prepared = null;
|
||||||
|
if (!prepared) return;
|
||||||
|
prepared.discarded = true;
|
||||||
|
void prepared.work.then(result => { if (result) this.runtime.release(result.image.url); }, () => undefined);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The blurred fill of an image, from the cache when possible. */
|
||||||
|
private async blurOf(image: Prepared): Promise<string> {
|
||||||
|
const cached = this.blurs.get(image.key);
|
||||||
|
if (cached) { this.blurs.delete(image.key); this.blurs.set(image.key, cached); return cached; }
|
||||||
|
const epoch = this.epoch;
|
||||||
|
const url = await this.runtime.blur(image.image);
|
||||||
|
if (this.stopped || epoch !== this.epoch) { this.runtime.release(url); throw new Error(tr("The background changed.")); }
|
||||||
|
const again = this.blurs.get(image.key);
|
||||||
|
if (again) { this.runtime.release(url); return again; }
|
||||||
|
this.blurs.set(image.key, url);
|
||||||
|
this.trimBlurs(url);
|
||||||
|
return url;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Release the oldest blurred fills beyond the cache size. Fills that a frame shows stay. */
|
||||||
|
private trimBlurs(keep?: string) {
|
||||||
|
const used = new Set([this.shown?.blurred, this.previous?.blurred, keep]);
|
||||||
|
for (const [key, url] of this.blurs) {
|
||||||
|
if (this.blurs.size <= BLUR_CACHE) break;
|
||||||
|
if (used.has(url)) continue;
|
||||||
|
this.blurs.delete(key); this.runtime.release(url);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Apply new settings or new image settings to the image that shows, without a fade. */
|
||||||
|
private async reapply(shown: Shown, settings: EngineSettings, valid: () => boolean) {
|
||||||
|
const appearance = this.appearanceOf(shown.name, shown.image, settings);
|
||||||
|
const sameTargets = settings.targets.length === this.targets.size && settings.targets.every(target => this.targets.has(target));
|
||||||
|
const needsBlur = appearance.fit === "blurred" && !shown.blurred;
|
||||||
|
if (sameTargets && sameAppearance(appearance, shown.appearance) && !needsBlur) return;
|
||||||
|
const next: Shown = { ...shown, appearance, blurred: undefined };
|
||||||
|
if (appearance.fit === "blurred") {
|
||||||
|
next.blurred = await this.blurOf(shown);
|
||||||
|
if (!valid()) return;
|
||||||
|
}
|
||||||
|
this.publish(next, settings, false);
|
||||||
|
this.notify();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Show `next` on every target. With `fade`, the frame fades from the image that showed before. */
|
||||||
|
private publish(next: Shown, settings: EngineSettings, fade: boolean) {
|
||||||
|
const old = this.shown;
|
||||||
|
const frame = toFrame(next);
|
||||||
|
if (fade && old) { frame.previous = toFrame(old); frame.transitionMs = transitionMs; }
|
||||||
|
try {
|
||||||
|
for (const target of this.targets) if (!settings.targets.includes(target)) this.frames.set(target, null);
|
||||||
|
// Track the new targets before the frames go out, so that a cleanup also clears a partial publish.
|
||||||
|
for (const target of settings.targets) this.targets.add(target);
|
||||||
|
for (const target of settings.targets) this.frames.set(target, frame);
|
||||||
|
} catch (error) {
|
||||||
|
if (next.image !== old?.image) this.runtime.release(next.image.url);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
this.targets = new Set(settings.targets);
|
||||||
|
// Keep the image of the fade until the next frame replaces it.
|
||||||
|
const release = this.previous;
|
||||||
|
if (release && release.image !== next.image && release.image !== old?.image) this.runtime.release(release.image.url);
|
||||||
|
this.previous = fade && old && old.image !== next.image ? old : null;
|
||||||
|
if (!fade && old && old.image !== next.image) this.runtime.release(old.image.url);
|
||||||
|
this.shown = next;
|
||||||
|
this.trimBlurs();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Remove the frames of every target and release every image. */
|
||||||
|
private clear() {
|
||||||
|
for (const target of this.targets) { try { this.frames.set(target, null); } catch { /* The window can close before the cleanup. */ } }
|
||||||
|
this.targets.clear();
|
||||||
|
const images = new Set([this.shown?.image.url, this.previous?.image.url]);
|
||||||
|
for (const url of images) if (url) this.runtime.release(url);
|
||||||
|
for (const url of this.blurs.values()) this.runtime.release(url);
|
||||||
|
this.blurs.clear();
|
||||||
|
this.epoch++;
|
||||||
|
this.discardPrepared();
|
||||||
|
this.shown = null; this.previous = null;
|
||||||
|
this.status = { ...this.status, image: null };
|
||||||
|
}
|
||||||
|
|
||||||
|
private schedule(milliseconds: number, revision: number, retry = false) {
|
||||||
|
const settings = this.settings;
|
||||||
|
if (this.stopped || this.revision !== revision || !this.source?.timed || !settings) return;
|
||||||
|
if (settings.paused && !retry) return;
|
||||||
|
this.due = this.runtime.now() + milliseconds;
|
||||||
|
this.timer = this.runtime.later(() => { this.timer = undefined; this.due = null; void this.update(true); }, milliseconds);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,57 @@
|
|||||||
|
// The per-image settings: the sidecar file `.runestone-backgrounds.json` in the image folder.
|
||||||
|
// The Background Slideshow plugin used the same file, so the settings of each image stay.
|
||||||
|
import { BACKGROUND_POSITIONS } from "../../theme/appearance.ts";
|
||||||
|
import { tr } from "../../i18n/index.ts";
|
||||||
|
import type { BackgroundLayout, BackgroundPosition } from "../backgroundSettings.ts";
|
||||||
|
|
||||||
|
export const sidecarName = ".runestone-backgrounds.json";
|
||||||
|
/** `blurred` shows the full image over a blurred copy that fills the view. Portrait images use it by default. */
|
||||||
|
export const imageFits = ["cover", "contain", "auto", "blurred"] as const;
|
||||||
|
export type ImageFit = typeof imageFits[number];
|
||||||
|
export interface ImageAppearance { fit: ImageFit; position: BackgroundPosition; overlay: number }
|
||||||
|
/** Unknown keys of the file and of each image stay when RuneStone saves the file. */
|
||||||
|
export interface ImageSettings { schema: 1; images: Record<string, Partial<ImageAppearance>>; [key: string]: unknown }
|
||||||
|
|
||||||
|
/** Read the sidecar text. `null` (no file) gives empty settings. Invalid settings throw an error. */
|
||||||
|
export function parseImageSettings(source: string | null): ImageSettings {
|
||||||
|
if (source === null) return { schema: 1, images: {} };
|
||||||
|
const value = JSON.parse(source);
|
||||||
|
if (!value || value.schema !== 1 || !value.images || typeof value.images !== "object" || Array.isArray(value.images)) {
|
||||||
|
throw new Error(tr("The image settings file must use schema 1 and an images object."));
|
||||||
|
}
|
||||||
|
for (const [name, raw] of Object.entries(value.images)) {
|
||||||
|
const appearance = raw as Partial<ImageAppearance>;
|
||||||
|
if (!name || /[\\/]/.test(name) || !appearance || typeof appearance !== "object" || Array.isArray(appearance)
|
||||||
|
|| ("fit" in appearance && !imageFits.includes(appearance.fit!))
|
||||||
|
|| ("position" in appearance && !BACKGROUND_POSITIONS.includes(appearance.position!))
|
||||||
|
|| ("overlay" in appearance && (typeof appearance.overlay !== "number" || !Number.isFinite(appearance.overlay) || Math.abs(appearance.overlay) > 1))) {
|
||||||
|
throw new Error(tr("Invalid image settings for {name}.", { name }));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The appearance of one image: the folder layout, the portrait default, then the saved values of the image. */
|
||||||
|
export function imageAppearance(layout: BackgroundLayout, override: Partial<ImageAppearance> | undefined, portrait: boolean): ImageAppearance {
|
||||||
|
return { fit: portrait ? "blurred" : layout.size, position: layout.position, overlay: layout.overlay, ...override };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The supported image names, without duplicates, in natural order. */
|
||||||
|
export function imageNames(names: readonly string[]): string[] {
|
||||||
|
return [...new Set(names.filter(name => !/[\\/]/.test(name) && /\.(png|jpe?g|gif|webp)$/i.test(name)))]
|
||||||
|
.sort((a, b) => a.localeCompare(b, "en", { numeric: true, sensitivity: "base" }) || a.localeCompare(b, "en"));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The order of the next images after `current`. A random order puts the current image last. */
|
||||||
|
export function sequence(names: readonly string[], current: string | null, order: "name" | "random", random = Math.random): string[] {
|
||||||
|
if (order === "name") {
|
||||||
|
const index = current === null ? -1 : names.indexOf(current);
|
||||||
|
return [...names.slice(index + 1), ...names.slice(0, index + 1)];
|
||||||
|
}
|
||||||
|
const rest = names.filter(name => name !== current);
|
||||||
|
for (let i = rest.length - 1; i > 0; i--) {
|
||||||
|
const j = Math.min(i, Math.max(0, Math.floor(random() * (i + 1))));
|
||||||
|
[rest[i], rest[j]] = [rest[j], rest[i]];
|
||||||
|
}
|
||||||
|
return current && names.includes(current) ? [...rest, current] : rest;
|
||||||
|
}
|
||||||
@@ -0,0 +1,84 @@
|
|||||||
|
// The Background feature. `loader.ts` imports this module when a folder or an image is selected (`launch.ts`),
|
||||||
|
// at a palette command, or when Appearance → Background shows its settings.
|
||||||
|
// It shows the images through `backgroundHub`, so the workarea, browser tabs, and Project Management boards get the frames.
|
||||||
|
import { mount, unmount } from "svelte";
|
||||||
|
import { tr } from "../../i18n/index.ts";
|
||||||
|
import { backgroundHub } from "../../plugins/backgrounds.ts";
|
||||||
|
import { readAppearance } from "../../theme/appearance.ts";
|
||||||
|
import { hasImage, normalizeLayout, onBackgroundChange, readBackground, writeBackground } from "../backgroundSettings.ts";
|
||||||
|
import type { FeatureContext, FeatureInstance } from "../types.ts";
|
||||||
|
import { BlurWorker } from "./blur.ts";
|
||||||
|
import { Slideshow, type ImageSource } from "./engine.ts";
|
||||||
|
import { browserRuntime, folderHost, folderSource, imageSource, onBackgroundCommand, sendBackgroundCommand } from "./sources.ts";
|
||||||
|
import BackgroundSettings from "./BackgroundSettings.svelte";
|
||||||
|
|
||||||
|
export function start(_context: FeatureContext): FeatureInstance {
|
||||||
|
const owner = Symbol("background");
|
||||||
|
const blur = new BlurWorker();
|
||||||
|
const engine = new Slideshow({ set: (target, frame) => backgroundHub.set(owner, target, frame) }, browserRuntime(blur));
|
||||||
|
/** The host folder for display. `undefined` until the first read. */
|
||||||
|
let folder: string | null | undefined;
|
||||||
|
let generation = 0;
|
||||||
|
let disposed = false;
|
||||||
|
/** The last source and settings. A change of another appearance setting, such as the theme, gives the same value. */
|
||||||
|
let applied = "";
|
||||||
|
|
||||||
|
/** Give the engine the current source and settings. `reread` asks the host for its folder again. */
|
||||||
|
async function apply(reread: boolean) {
|
||||||
|
const run = ++generation;
|
||||||
|
const settings = readBackground();
|
||||||
|
const appearance = readAppearance();
|
||||||
|
let source: ImageSource | null = null;
|
||||||
|
let layout = normalizeLayout(settings);
|
||||||
|
if (settings.source === "folder") {
|
||||||
|
if (reread || folder === undefined) {
|
||||||
|
try { folder = await folderHost.current(); } catch { folder = null; }
|
||||||
|
if (disposed || run !== generation) return;
|
||||||
|
}
|
||||||
|
source = folder ? folderSource(folder) : null;
|
||||||
|
} else if (settings.source === "image" && hasImage(appearance)) {
|
||||||
|
source = imageSource(appearance.newTabBackground!);
|
||||||
|
layout = normalizeLayout(appearance.newTabBackground);
|
||||||
|
}
|
||||||
|
const next = { ...settings, ...layout };
|
||||||
|
const signature = JSON.stringify([source?.key ?? null, next]);
|
||||||
|
if (!reread && signature === applied) return;
|
||||||
|
applied = signature;
|
||||||
|
await engine.configure(source, next);
|
||||||
|
}
|
||||||
|
|
||||||
|
const stopSettings = onBackgroundChange(() => { void apply(false); });
|
||||||
|
const stopCommands = onBackgroundCommand(command => {
|
||||||
|
if (command === "next") void engine.next();
|
||||||
|
else { engine.invalidate(); void apply(true); }
|
||||||
|
});
|
||||||
|
// Another window or program can change the folder. A focus reads the folder, the list, and the sidecar again.
|
||||||
|
const focus = () => { engine.invalidate(); void apply(true); };
|
||||||
|
window.addEventListener("focus", focus);
|
||||||
|
void apply(true);
|
||||||
|
|
||||||
|
return {
|
||||||
|
mount() { throw new Error(tr("This view is unavailable.")); },
|
||||||
|
async run(command) {
|
||||||
|
if (command === "next") await sendBackgroundCommand("next");
|
||||||
|
else if (command === "pause") {
|
||||||
|
const settings = readBackground();
|
||||||
|
await writeBackground({ ...settings, paused: !settings.paused });
|
||||||
|
} else throw new Error(tr("This command is unavailable."));
|
||||||
|
},
|
||||||
|
dispose() {
|
||||||
|
disposed = true; generation++;
|
||||||
|
stopSettings(); stopCommands();
|
||||||
|
window.removeEventListener("focus", focus);
|
||||||
|
engine.dispose();
|
||||||
|
blur.dispose();
|
||||||
|
backgroundHub.removeOwner(owner);
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The settings of Appearance → Background. They work also in a window where Background does not run. */
|
||||||
|
export function mountSettings(element: HTMLElement) {
|
||||||
|
const component = mount(BackgroundSettings, { target: element });
|
||||||
|
return () => { void unmount(component); };
|
||||||
|
}
|
||||||
@@ -0,0 +1,108 @@
|
|||||||
|
// The image sources of Background, the host folder commands (`src-tauri/src/backgrounds.rs`), the browser runtime of the
|
||||||
|
// engine, and the commands that reach the Background instance of every window.
|
||||||
|
import { invoke, isTauri } from "@tauri-apps/api/core";
|
||||||
|
import { emit, listen } from "@tauri-apps/api/event";
|
||||||
|
import { tr } from "../../i18n/index.ts";
|
||||||
|
import { readBackgroundImage } from "../../theme/backgroundImages.ts";
|
||||||
|
import type { Appearance } from "../../theme/appearance.ts";
|
||||||
|
import type { BlurWorker } from "./blur.ts";
|
||||||
|
import type { ImageSource, LoadedImage, Runtime } from "./engine.ts";
|
||||||
|
|
||||||
|
const types: Record<string, string> = { png: "image/png", jpg: "image/jpeg", jpeg: "image/jpeg", gif: "image/gif", webp: "image/webp" };
|
||||||
|
const typeOf = (name: string) => types[name.split(".").pop()!.toLowerCase()] ?? "application/octet-stream";
|
||||||
|
|
||||||
|
/** The host commands of the image folder. The host keeps the folder, so no command takes a path. */
|
||||||
|
export const folderHost = {
|
||||||
|
/** Show the folder dialog. Returns the chosen folder for display, or null after Cancel. */
|
||||||
|
choose: (title: string) => invoke<string | null>("background_choose_folder", { title }),
|
||||||
|
/** The current folder for display, or null. */
|
||||||
|
current: () => invoke<string | null>("background_folder"),
|
||||||
|
clear: () => invoke<void>("background_clear_folder"),
|
||||||
|
list: () => invoke<string[]>("background_list"),
|
||||||
|
read: async (name: string): Promise<Blob> => {
|
||||||
|
const bytes = await invoke<ArrayBuffer | Uint8Array | number[]>("background_read", { name });
|
||||||
|
return new Blob([bytes instanceof ArrayBuffer ? bytes : Uint8Array.from(bytes)], { type: typeOf(name) });
|
||||||
|
},
|
||||||
|
readSidecar: () => invoke<string | null>("background_read_sidecar"),
|
||||||
|
writeSidecar: (contents: string, expected: string | null) => invoke<void>("background_write_sidecar", { contents, expected }),
|
||||||
|
};
|
||||||
|
|
||||||
|
/** The images of the host folder. `folder` is the path for display. It makes the key, so another folder starts again. */
|
||||||
|
export function folderSource(folder: string): ImageSource {
|
||||||
|
return { key: `folder:${folder}`, timed: true, list: folderHost.list, read: folderHost.read, sidecar: folderHost.readSidecar };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The saved image of Appearance, from IndexedDB or from an old data URL. */
|
||||||
|
export async function readSavedImage(background: NonNullable<Appearance["newTabBackground"]>): Promise<Blob> {
|
||||||
|
if (background.imageId) {
|
||||||
|
const blob = await readBackgroundImage(background.imageId);
|
||||||
|
if (!blob) throw new Error(tr("The saved background image is missing. Choose the image again."));
|
||||||
|
return blob;
|
||||||
|
}
|
||||||
|
const image = background.image ?? "";
|
||||||
|
const [header, data] = image.split(",");
|
||||||
|
const bytes = Uint8Array.from(atob(data ?? ""), character => character.charCodeAt(0));
|
||||||
|
return new Blob([bytes], { type: header.slice(5, header.indexOf(";")) });
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A short hash of a data URL, so that another old image gets another key. */
|
||||||
|
function hash(text: string): string {
|
||||||
|
let value = 0x811c9dc5;
|
||||||
|
for (let index = 0; index < text.length; index++) value = Math.imul(value ^ text.charCodeAt(index), 0x01000193);
|
||||||
|
return (value >>> 0).toString(16);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The one saved image. It has no timer. */
|
||||||
|
export function imageSource(background: NonNullable<Appearance["newTabBackground"]>): ImageSource {
|
||||||
|
const id = background.imageId ?? `data:${background.image?.length ?? 0}:${hash(background.image ?? "")}`;
|
||||||
|
return { key: `image:${id}`, timed: false, list: async () => ["image"], read: () => readSavedImage(background), sidecar: async () => null };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Make a blob URL and decode the image before it shows, so the fade does not wait for the decode. */
|
||||||
|
export async function loadImage(blob: Blob): Promise<LoadedImage> {
|
||||||
|
const url = URL.createObjectURL(blob);
|
||||||
|
try {
|
||||||
|
const image = new Image();
|
||||||
|
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||||
|
image.src = url;
|
||||||
|
await Promise.race([image.decode(), new Promise<never>((_, reject) => { timer = setTimeout(() => reject(new Error(tr("The image took too long to load."))), 10000); })])
|
||||||
|
.finally(() => clearTimeout(timer));
|
||||||
|
return { url, width: image.naturalWidth, height: image.naturalHeight };
|
||||||
|
} catch (error) { URL.revokeObjectURL(url); throw error; }
|
||||||
|
}
|
||||||
|
|
||||||
|
export function browserRuntime(blur: BlurWorker): Runtime {
|
||||||
|
return {
|
||||||
|
load: loadImage,
|
||||||
|
blur: image => blur.blur(image.url, image.width, image.height),
|
||||||
|
release: url => URL.revokeObjectURL(url),
|
||||||
|
later: (callback, milliseconds) => setTimeout(callback, milliseconds),
|
||||||
|
cancel: timer => clearTimeout(timer as ReturnType<typeof setTimeout>),
|
||||||
|
random: Math.random,
|
||||||
|
now: () => Date.now(),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** `next` shows the next image. `reload` reads the folder, the list, and the sidecar again. */
|
||||||
|
export type BackgroundCommand = "next" | "reload";
|
||||||
|
const EVENT = "background-command";
|
||||||
|
|
||||||
|
/** Send a command to the Background instance of every window, this window too. */
|
||||||
|
export async function sendBackgroundCommand(command: BackgroundCommand): Promise<void> {
|
||||||
|
if (isTauri()) await emit(EVENT, command);
|
||||||
|
else window.dispatchEvent(new CustomEvent(EVENT, { detail: command }));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Receive the commands of every window. Returns the function that stops it. */
|
||||||
|
export function onBackgroundCommand(listener: (command: BackgroundCommand) => void): () => void {
|
||||||
|
const accept = (value: unknown) => { if (value === "next" || value === "reload") listener(value); };
|
||||||
|
if (!isTauri()) {
|
||||||
|
const handle = (event: Event) => accept((event as CustomEvent).detail);
|
||||||
|
window.addEventListener(EVENT, handle);
|
||||||
|
return () => window.removeEventListener(EVENT, handle);
|
||||||
|
}
|
||||||
|
let stopped = false;
|
||||||
|
let off: (() => void) | undefined;
|
||||||
|
void listen<unknown>(EVENT, event => accept(event.payload)).then(unlisten => { if (stopped) unlisten(); else off = unlisten; }, () => undefined);
|
||||||
|
return () => { stopped = true; off?.(); };
|
||||||
|
}
|
||||||
@@ -0,0 +1,119 @@
|
|||||||
|
// The settings of the Background feature: the `background` section of the settings file.
|
||||||
|
// This file is in the main bundle, because the launch rule and the first-start migration need it without the feature code.
|
||||||
|
// The image source keeps its image and its layout in `appearance.newTabBackground`, so an older version still shows it.
|
||||||
|
// The host keeps the image folder itself (`src-tauri/src/backgrounds.rs`). The interface never sends a folder path.
|
||||||
|
import { onSettingsChange, readSection, writeSection } from "../settings/store.ts";
|
||||||
|
import { BACKGROUND_POSITIONS, BACKGROUND_SIZES, readAppearance, type Appearance } from "../theme/appearance.ts";
|
||||||
|
import type { LegacyPlugin } from "./migration.ts";
|
||||||
|
|
||||||
|
export const BACKGROUND_SOURCES = ["folder", "image", "none"] as const;
|
||||||
|
export type BackgroundSource = typeof BACKGROUND_SOURCES[number];
|
||||||
|
export type BackgroundPosition = typeof BACKGROUND_POSITIONS[number];
|
||||||
|
export type BackgroundSize = typeof BACKGROUND_SIZES[number];
|
||||||
|
/** The views that show the background: the workspace, all Project Management boards, or one board. */
|
||||||
|
export const BACKGROUND_TARGET = /^(?:app|pm-all|pm-board:[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$/i;
|
||||||
|
|
||||||
|
export interface BackgroundLayout {
|
||||||
|
/** From -1 (white) to 1 (black). */
|
||||||
|
overlay: number;
|
||||||
|
position: BackgroundPosition;
|
||||||
|
size: BackgroundSize;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface BackgroundSettings extends BackgroundLayout {
|
||||||
|
source: BackgroundSource;
|
||||||
|
/** The time of each image of a folder, from 1 to 86,400 seconds. */
|
||||||
|
seconds: number;
|
||||||
|
order: "name" | "random";
|
||||||
|
/** A paused folder keeps its current image. */
|
||||||
|
paused: boolean;
|
||||||
|
targets: string[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export const DEFAULT_BACKGROUND: Readonly<BackgroundSettings> = Object.freeze({
|
||||||
|
source: "none", seconds: 60, order: "name", paused: false, targets: ["app"], overlay: 0, position: "center", size: "cover",
|
||||||
|
});
|
||||||
|
|
||||||
|
function record(value: unknown): Record<string, unknown> {
|
||||||
|
return value && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : {};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The folder layout fields from any value. Invalid fields take the defaults. */
|
||||||
|
export function normalizeLayout(value: unknown): BackgroundLayout {
|
||||||
|
const raw = record(value);
|
||||||
|
return {
|
||||||
|
overlay: typeof raw.overlay === "number" && Number.isFinite(raw.overlay) ? Math.max(-1, Math.min(1, raw.overlay)) : 0,
|
||||||
|
position: BACKGROUND_POSITIONS.includes(raw.position as BackgroundPosition) ? raw.position as BackgroundPosition : "center",
|
||||||
|
size: BACKGROUND_SIZES.includes(raw.size as BackgroundSize) ? raw.size as BackgroundSize : "cover",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Valid settings from any value. Invalid fields take the defaults. */
|
||||||
|
export function normalizeBackground(value: unknown): BackgroundSettings {
|
||||||
|
const raw = record(value);
|
||||||
|
return {
|
||||||
|
source: BACKGROUND_SOURCES.includes(raw.source as BackgroundSource) ? raw.source as BackgroundSource : "none",
|
||||||
|
seconds: typeof raw.seconds === "number" && Number.isFinite(raw.seconds) ? Math.max(1, Math.min(86400, Math.round(raw.seconds))) : 60,
|
||||||
|
order: raw.order === "random" ? "random" : "name",
|
||||||
|
paused: raw.paused === true,
|
||||||
|
targets: Array.isArray(raw.targets)
|
||||||
|
? [...new Set(raw.targets.filter((target): target is string => typeof target === "string" && BACKGROUND_TARGET.test(target)))]
|
||||||
|
: ["app"],
|
||||||
|
...normalizeLayout(raw),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function readBackground(): BackgroundSettings {
|
||||||
|
return normalizeBackground(readSection("background"));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Save the settings. Keys of a newer version stay. */
|
||||||
|
export function writeBackground(next: BackgroundSettings): Promise<void> {
|
||||||
|
return writeSection("background", { ...record(readSection("background")), ...normalizeBackground(next) });
|
||||||
|
}
|
||||||
|
|
||||||
|
/** True when the appearance has a saved background image. */
|
||||||
|
export function hasImage(appearance: Appearance = readAppearance()): boolean {
|
||||||
|
return !!(appearance.newTabBackground?.image || appearance.newTabBackground?.imageId);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** True when Background has something to show: a folder, or an image that exists. */
|
||||||
|
export function hasBackgroundSource(settings: BackgroundSettings = readBackground(), appearance: Appearance = readAppearance()): boolean {
|
||||||
|
return settings.source === "folder" || (settings.source === "image" && hasImage(appearance));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Run `listener` after each change of the background or appearance settings. Returns the function that stops it. */
|
||||||
|
export function onBackgroundChange(listener: () => void): () => void {
|
||||||
|
const stops = [onSettingsChange("background", listener), onSettingsChange("appearance", listener)];
|
||||||
|
return () => stops.forEach(stop => stop());
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The host side of the first-start migration of the `background` section. */
|
||||||
|
export interface BackgroundMigrationHost {
|
||||||
|
/** True when the settings file has no `background` section. */
|
||||||
|
missing(): boolean;
|
||||||
|
/** True when the appearance has a saved background image. */
|
||||||
|
hasImage(): boolean;
|
||||||
|
/** Copy the folder of the old plugin grant to the host. True when the host has a folder after the call. */
|
||||||
|
migrateFolder(): Promise<boolean>;
|
||||||
|
write(value: BackgroundSettings): Promise<void>;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Make the `background` section from the old Background Slideshow plugin and the old background image.
|
||||||
|
* The source is the folder when the plugin was installed, enabled, and on, and its folder migrated.
|
||||||
|
* Otherwise it is the image when one exists. The kept plugin settings give the sequence, the targets, and the layout.
|
||||||
|
*/
|
||||||
|
export async function migrateBackground(legacy: LegacyPlugin | undefined, host: BackgroundMigrationHost): Promise<BackgroundSettings> {
|
||||||
|
const kept = record(legacy?.settings);
|
||||||
|
// Migrate the folder whenever a grant exists, so that a later choice of Folder brings it back.
|
||||||
|
let folder = false;
|
||||||
|
if (typeof kept.grant === "string" && kept.grant) {
|
||||||
|
try { folder = await host.migrateFolder(); } catch (reason) { console.error("RuneStone could not take the old background folder.", reason); }
|
||||||
|
}
|
||||||
|
const slideshow = !!legacy?.installed && legacy.enabled && kept.enabled === true && folder;
|
||||||
|
const copied = Object.fromEntries(["seconds", "order", "targets", "overlay", "position", "size"].filter(key => key in kept).map(key => [key, kept[key]]));
|
||||||
|
const value = normalizeBackground({ ...copied, source: slideshow ? "folder" : host.hasImage() ? "image" : "none", paused: false });
|
||||||
|
await host.write(value);
|
||||||
|
return value;
|
||||||
|
}
|
||||||
@@ -1,10 +1,11 @@
|
|||||||
// The native features of RuneStone. Each feature has an off switch in Settings → Features.
|
// 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.
|
// This file is in the main bundle, so it holds only small static data: names, views, commands, and document types.
|
||||||
// The code of a feature loads with a dynamic import at first need (see `loader.ts`), and never while its switch is off.
|
// 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 { message, tr } from "../i18n/index.ts";
|
||||||
import type { PluginView } from "../plugins/sdk.ts";
|
import type { PluginCommand, PluginDocumentType, PluginView } from "../plugins/sdk.ts";
|
||||||
|
import { identifyPdf } from "./pdfDocument.ts";
|
||||||
|
|
||||||
export type FeatureId = "git";
|
export type FeatureId = "git" | "background" | "terminal" | "pdf" | "pm";
|
||||||
|
|
||||||
/** A view of a feature. The workbench shows it as a tab or in the side pane, as it shows a plugin view. */
|
/** 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 {
|
export interface FeatureViewInfo {
|
||||||
@@ -15,15 +16,47 @@ export interface FeatureViewInfo {
|
|||||||
icon?: PluginView["icon"];
|
icon?: PluginView["icon"];
|
||||||
/** Show a navigation button for the view. */
|
/** Show a navigation button for the view. */
|
||||||
navigation?: boolean;
|
navigation?: boolean;
|
||||||
|
/** True when a launch, such as a ribbon button, asks the feature which view to open (`FeatureInstance.launch`). */
|
||||||
|
launch?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A family of editor views whose IDs follow a pattern, for example one tab for each board. The session answers for each
|
||||||
|
* matching ID before the feature module loads, so a tab transfer from another window can restore it.
|
||||||
|
* The feature gives the real title later (`FeatureContext.setViewTitle`).
|
||||||
|
*/
|
||||||
|
export interface FeatureViewPattern {
|
||||||
|
/** Matches the whole view ID. */
|
||||||
|
match: RegExp;
|
||||||
|
/** The title until the feature gives one. */
|
||||||
|
title: () => string;
|
||||||
|
icon?: PluginView["icon"];
|
||||||
}
|
}
|
||||||
|
|
||||||
/** A command of a feature. The command palette lists it. */
|
/** A command of a feature. The command palette lists it. */
|
||||||
export interface FeatureCommandInfo {
|
export interface FeatureCommandInfo {
|
||||||
id: string;
|
id: string;
|
||||||
title: () => string;
|
title: () => string;
|
||||||
icon?: PluginView["icon"];
|
icon?: PluginCommand["icon"];
|
||||||
/** The view that the command opens. */
|
/** The view that the command opens. Without a view, the command loads the feature and calls `FeatureInstance.run`. */
|
||||||
view: string;
|
view?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A document type of a feature. The file tree marks the files of the type, and a click opens them in a tab,
|
||||||
|
* without the feature code. The first tab of the type loads the feature and calls `FeatureInstance.mountDocument`.
|
||||||
|
*/
|
||||||
|
export interface FeatureDocumentInfo {
|
||||||
|
id: string;
|
||||||
|
/** Returns the title in the current language. The file tree shows it as the tooltip of the file icon. */
|
||||||
|
title: () => string;
|
||||||
|
icon: NonNullable<PluginDocumentType["icon"]>;
|
||||||
|
/** Lowercase file extensions without the dot. */
|
||||||
|
extensions: readonly string[];
|
||||||
|
/** "binary" when `identify` needs no file contents. */
|
||||||
|
content: "text" | "binary";
|
||||||
|
/** The document ID of a file, or null when the file is not of this type. */
|
||||||
|
identify(path: string, source: string): { id: string } | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface FeatureEntry {
|
export interface FeatureEntry {
|
||||||
@@ -37,8 +70,13 @@ export interface FeatureEntry {
|
|||||||
keywords: string;
|
keywords: string;
|
||||||
/** The switch for a user who never installed the old package. */
|
/** The switch for a user who never installed the old package. */
|
||||||
defaultOn: boolean;
|
defaultOn: boolean;
|
||||||
|
/** True when the first start gives the switch the state of the old package. False when every user gets `defaultOn`. */
|
||||||
|
followsPackage: boolean;
|
||||||
views: readonly FeatureViewInfo[];
|
views: readonly FeatureViewInfo[];
|
||||||
|
/** Editor views with IDs that follow a pattern. */
|
||||||
|
viewPatterns?: readonly FeatureViewPattern[];
|
||||||
commands: readonly FeatureCommandInfo[];
|
commands: readonly FeatureCommandInfo[];
|
||||||
|
documentTypes: readonly FeatureDocumentInfo[];
|
||||||
}
|
}
|
||||||
|
|
||||||
export const FEATURES: readonly FeatureEntry[] = [
|
export const FEATURES: readonly FeatureEntry[] = [
|
||||||
@@ -46,13 +84,66 @@ export const FEATURES: readonly FeatureEntry[] = [
|
|||||||
id: "git", owner: "runestone.git", name: message("Git"),
|
id: "git", owner: "runestone.git", name: message("Git"),
|
||||||
description: message("Review changes, stage files, commit, and see the commit graph of the workspace repository."),
|
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",
|
keywords: "git source control commit stage diff graph branch push pull blame",
|
||||||
defaultOn: true,
|
defaultOn: true, followsPackage: true,
|
||||||
views: [
|
views: [
|
||||||
{ id: "source-control", title: () => tr("Source control"), placement: "sidebar", icon: "git", navigation: true },
|
{ id: "source-control", title: () => tr("Source control"), placement: "sidebar", icon: "git", navigation: true },
|
||||||
{ id: "diff", title: () => tr("Git diff"), placement: "editor", icon: "git" },
|
{ id: "diff", title: () => tr("Git diff"), placement: "editor", icon: "git" },
|
||||||
{ id: "graph", title: () => tr("Git graph"), 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" }],
|
commands: [{ id: "graph", title: () => tr("Show Git graph"), icon: "git", view: "graph" }],
|
||||||
|
documentTypes: [],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
// Background replaces the Background Slideshow plugin and the background image of Appearance. Its settings are in
|
||||||
|
// Appearance → Background. It loads at the start only when a folder or an image is selected (see `launch.ts`).
|
||||||
|
id: "background", owner: "runestone.bg-slideshow", name: message("Background"),
|
||||||
|
description: message("Show a folder of images as a slideshow, or one image, behind the workspace and the boards."),
|
||||||
|
keywords: "background image wallpaper slideshow folder picture photo overlay blur",
|
||||||
|
defaultOn: true, followsPackage: false,
|
||||||
|
views: [],
|
||||||
|
commands: [
|
||||||
|
{ id: "next", title: () => tr("Next background image"), icon: "image" },
|
||||||
|
{ id: "pause", title: () => tr("Pause background"), icon: "pause" },
|
||||||
|
],
|
||||||
|
documentTypes: [],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
// Terminal replaces the Terminal plugin. Its panel is not a view: the workbench and the terminal window show it
|
||||||
|
// (`src/lib/features/TerminalHost.svelte`), and the first use loads the module. Its settings are in Settings → Terminal.
|
||||||
|
id: "terminal", owner: "runestone.terminal", name: message("Terminal"),
|
||||||
|
description: message("Run shells, tasks, and the active file in a panel below the editor or in a separate window."),
|
||||||
|
keywords: "terminal shell console powershell bash cmd command prompt task run pty xterm",
|
||||||
|
defaultOn: true, followsPackage: true,
|
||||||
|
views: [],
|
||||||
|
commands: [],
|
||||||
|
documentTypes: [],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
// PDF Viewer replaces the PDF Viewer plugin. It has no view: its document type opens each PDF file in its own tab.
|
||||||
|
// The file tree marks PDF files without the module. The first PDF tab loads the module and PDF.js.
|
||||||
|
id: "pdf", owner: "runestone.pdf-viewer", name: message("PDF Viewer"),
|
||||||
|
description: message("Read PDF files of the workspace in tabs, with page controls, zoom, rotation, and text selection."),
|
||||||
|
keywords: "pdf document viewer page zoom rotate password pdf.js",
|
||||||
|
defaultOn: true, followsPackage: true,
|
||||||
|
views: [],
|
||||||
|
commands: [],
|
||||||
|
documentTypes: [
|
||||||
|
{ id: "pdf", title: () => tr("PDF document"), icon: "file", extensions: ["pdf"], content: "binary", identify: identifyPdf },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
// Project Management replaces the Project Management plugin. It reads only `.runestone/pm/` in the workspace, so the
|
||||||
|
// file tree reads no Markdown file for it. Its ribbon button opens `planning`: the default board of the workspace, or
|
||||||
|
// All tasks. Each board has its own tab, `board-<hex of the board ID>`, as in the plugin, so tab transfers between
|
||||||
|
// the plugin and the feature work. Its settings are in Settings → Project Management (`ProjectManagementSettings.svelte`).
|
||||||
|
id: "pm", owner: "runestone.pm", name: message("Project Management"),
|
||||||
|
description: message("Plan work on Kanban boards, in All tasks, and on Gantt and calendar views. The cards stay in the workspace."),
|
||||||
|
keywords: "project management kanban board card task list gantt calendar label priority backlog todo plan",
|
||||||
|
defaultOn: true, followsPackage: true,
|
||||||
|
views: [{ id: "planning", title: () => tr("Project Management"), placement: "editor", icon: "kanban", launch: true }],
|
||||||
|
viewPatterns: [{ match: /^board-(?:[0-9a-f]{2})+$/, title: () => tr("Project Management"), icon: "kanban" }],
|
||||||
|
commands: [],
|
||||||
|
documentTypes: [],
|
||||||
},
|
},
|
||||||
];
|
];
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,32 @@
|
|||||||
|
// Launch rules: a feature with a rule starts its instance as soon as the rule wants it, without a view or a command.
|
||||||
|
// A feature without a rule loads at first need. `syncFeatures` in `src/lib/plugins/external.ts` applies the rules.
|
||||||
|
import type { FeatureId } from "./catalog.ts";
|
||||||
|
import { hasBackgroundSource, onBackgroundChange } from "./backgroundSettings.ts";
|
||||||
|
|
||||||
|
export interface LaunchRule {
|
||||||
|
/** True when the feature also runs in browser windows. Other features stay out of them. */
|
||||||
|
browserWindow: boolean;
|
||||||
|
/** True when the rule also starts the feature in the settings window. */
|
||||||
|
settingsWindow: boolean;
|
||||||
|
/** True when the instance must run now. */
|
||||||
|
wanted(): boolean;
|
||||||
|
/** Run `listener` after each change that can change `wanted`. Returns the function that stops it. */
|
||||||
|
subscribe(listener: () => void): () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const LAUNCH_RULES: Partial<Record<FeatureId, LaunchRule>> = {
|
||||||
|
// Background starts at the start of a window when a folder or an image is selected, and at once when the user selects one.
|
||||||
|
// The settings window shows the settings only, so the slideshow does not run there.
|
||||||
|
background: { browserWindow: true, settingsWindow: false, wanted: () => hasBackgroundSource(), subscribe: onBackgroundChange },
|
||||||
|
};
|
||||||
|
|
||||||
|
/** True when a feature runs in a window of this kind. */
|
||||||
|
export function runsInWindow(id: FeatureId, window: { browserWindow: boolean }): boolean {
|
||||||
|
return !window.browserWindow || !!LAUNCH_RULES[id]?.browserWindow;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** True when the launch rule of a feature wants its instance now in a window of this kind. */
|
||||||
|
export function launchWanted(id: FeatureId, window: { settingsWindow: boolean }): boolean {
|
||||||
|
const rule = LAUNCH_RULES[id];
|
||||||
|
return !!rule && (!window.settingsWindow || rule.settingsWindow) && rule.wanted();
|
||||||
|
}
|
||||||
@@ -6,6 +6,10 @@ import type { FeatureModule } from "./types.ts";
|
|||||||
|
|
||||||
const imports: Record<FeatureId, () => Promise<FeatureModule>> = {
|
const imports: Record<FeatureId, () => Promise<FeatureModule>> = {
|
||||||
git: () => import("./git/index.ts"),
|
git: () => import("./git/index.ts"),
|
||||||
|
background: () => import("./background/index.ts"),
|
||||||
|
terminal: () => import("./terminal/index.ts"),
|
||||||
|
pdf: () => import("./pdf/index.ts"),
|
||||||
|
pm: () => import("./pm/index.ts"),
|
||||||
};
|
};
|
||||||
|
|
||||||
const modules = new Map<FeatureId, Promise<FeatureModule>>();
|
const modules = new Map<FeatureId, Promise<FeatureModule>>();
|
||||||
|
|||||||
@@ -1,9 +1,17 @@
|
|||||||
// The first start of a version with a new native feature. The switch takes the state of the old plugin package.
|
// The first start of a version with a new native feature. The switch takes the state of the old plugin package,
|
||||||
|
// or the default of the feature when the feature does not follow its package (`followsPackage`).
|
||||||
// `features_legacy` in `src-tauri/src/features.rs` reads the old package state and its kept settings. It changes nothing.
|
// `features_legacy` in `src-tauri/src/features.rs` reads the old package state and its kept settings. It changes nothing.
|
||||||
|
// The first start also makes the `background` section from the old Background Slideshow settings (`backgroundSettings.ts`),
|
||||||
|
// the `terminal` section from the localStorage key of the Terminal plugin (`terminalSettings.ts`), and the
|
||||||
|
// `projectManagement` section and the tab view states from the kept Project Management settings (`pmSettings.ts`).
|
||||||
import { invoke, isTauri } from "@tauri-apps/api/core";
|
import { invoke, isTauri } from "@tauri-apps/api/core";
|
||||||
import { readSection, writeSection } from "../settings/store.ts";
|
import { readSection, writeSection } from "../settings/store.ts";
|
||||||
import { FEATURES, type FeatureEntry, type FeatureId } from "./catalog.ts";
|
import { readAppearance } from "../theme/appearance.ts";
|
||||||
|
import { FEATURES, featureEntry, type FeatureEntry, type FeatureId } from "./catalog.ts";
|
||||||
import { storedSwitches } from "./state.ts";
|
import { storedSwitches } from "./state.ts";
|
||||||
|
import { hasImage, migrateBackground, writeBackground, type BackgroundMigrationHost } from "./backgroundSettings.ts";
|
||||||
|
import { LEGACY_TERMINAL_KEY, migrateTerminal, writeTerminal, type TerminalMigrationHost } from "./terminalSettings.ts";
|
||||||
|
import { migrateProjectManagement, writeProjectManagement, type ProjectManagementMigrationHost } from "./pmSettings.ts";
|
||||||
|
|
||||||
/** What the host reports about one old plugin package. */
|
/** What the host reports about one old plugin package. */
|
||||||
export interface LegacyPlugin {
|
export interface LegacyPlugin {
|
||||||
@@ -14,9 +22,9 @@ export interface LegacyPlugin {
|
|||||||
settings: unknown;
|
settings: unknown;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** An installed package gives its enabled state. Without a package, the default of the feature applies. */
|
/** An installed package gives its enabled state. Without a package, or for a feature that does not follow its package, the default applies. */
|
||||||
export function legacySwitch(entry: FeatureEntry, legacy: LegacyPlugin | undefined): boolean {
|
export function legacySwitch(entry: FeatureEntry, legacy: LegacyPlugin | undefined): boolean {
|
||||||
return legacy?.installed ? legacy.enabled : entry.defaultOn;
|
return entry.followsPackage && legacy?.installed ? legacy.enabled : entry.defaultOn;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface MigrationHost {
|
export interface MigrationHost {
|
||||||
@@ -31,24 +39,57 @@ const desktopHost: MigrationHost = {
|
|||||||
legacy: ids => invoke<LegacyPlugin[]>("features_legacy", { ids }),
|
legacy: ids => invoke<LegacyPlugin[]>("features_legacy", { ids }),
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const desktopBackground: BackgroundMigrationHost = {
|
||||||
|
missing: () => readSection("background") === undefined,
|
||||||
|
hasImage: () => hasImage(readAppearance()),
|
||||||
|
migrateFolder: async () => !!await invoke<string | null>("background_migrate"),
|
||||||
|
write: writeBackground,
|
||||||
|
};
|
||||||
|
|
||||||
|
const desktopProjectManagement: ProjectManagementMigrationHost = {
|
||||||
|
missing: () => readSection("projectManagement") === undefined,
|
||||||
|
write: writeProjectManagement,
|
||||||
|
get storage() { return localStorage; },
|
||||||
|
};
|
||||||
|
|
||||||
|
const desktopTerminal: TerminalMigrationHost = {
|
||||||
|
missing: () => readSection("terminal") === undefined,
|
||||||
|
legacy: () => localStorage.getItem(LEGACY_TERMINAL_KEY),
|
||||||
|
write: writeTerminal,
|
||||||
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Give each feature without a stored switch the state of its old package. It runs before the first render.
|
* Give each feature without a stored switch the state of its old package, and make a missing `background`, `terminal`,
|
||||||
* When the host cannot report the packages, nothing is written, so the next start tries again.
|
* or `projectManagement` section.
|
||||||
|
* It runs before the first render. When the host cannot report the packages, nothing is written, so the next start tries again.
|
||||||
|
* The `terminal` section needs no package report, so it migrates also then.
|
||||||
*/
|
*/
|
||||||
export async function migrateFeatures(host: MigrationHost = desktopHost): Promise<FeatureId[]> {
|
export async function migrateFeatures(host: MigrationHost = desktopHost, background: BackgroundMigrationHost = desktopBackground,
|
||||||
|
terminal: TerminalMigrationHost = desktopTerminal, projectManagement: ProjectManagementMigrationHost = desktopProjectManagement): Promise<FeatureId[]> {
|
||||||
|
try { await migrateTerminal(terminal); }
|
||||||
|
catch (reason) { console.error("RuneStone could not copy the old terminal settings.", reason); }
|
||||||
const current = host.read();
|
const current = host.read();
|
||||||
const stored = storedSwitches(current);
|
const stored = storedSwitches(current);
|
||||||
const missing = FEATURES.filter(entry => stored[entry.id] === undefined);
|
const missing = FEATURES.filter(entry => stored[entry.id] === undefined);
|
||||||
if (!missing.length) return [];
|
const backgroundOwner = featureEntry("background").owner;
|
||||||
|
const backgroundMissing = background.missing();
|
||||||
|
const pmOwner = featureEntry("pm").owner;
|
||||||
|
const pmMissing = projectManagement.missing();
|
||||||
|
const owners = [...new Set([...missing.map(entry => entry.owner), ...backgroundMissing ? [backgroundOwner] : [], ...pmMissing ? [pmOwner] : []])];
|
||||||
|
if (!owners.length) return [];
|
||||||
let legacy: LegacyPlugin[];
|
let legacy: LegacyPlugin[];
|
||||||
try { legacy = await host.legacy(missing.map(entry => entry.owner)); }
|
try { legacy = await host.legacy(owners); }
|
||||||
catch (reason) {
|
catch (reason) {
|
||||||
console.error("RuneStone could not read the old plugin packages. The feature defaults apply.", reason);
|
console.error("RuneStone could not read the old plugin packages. The feature defaults apply.", reason);
|
||||||
return [];
|
return [];
|
||||||
}
|
}
|
||||||
|
if (missing.length) {
|
||||||
const next: Record<string, unknown> = current && typeof current === "object" && !Array.isArray(current) ? { ...current as Record<string, unknown> } : {};
|
const next: Record<string, unknown> = current && typeof current === "object" && !Array.isArray(current) ? { ...current as Record<string, unknown> } : {};
|
||||||
for (const entry of missing) next[entry.id] = legacySwitch(entry, legacy.find(item => item.id === entry.owner));
|
for (const entry of missing) next[entry.id] = legacySwitch(entry, legacy.find(item => item.id === entry.owner));
|
||||||
await host.write(next);
|
await host.write(next);
|
||||||
|
}
|
||||||
|
if (backgroundMissing) await migrateBackground(legacy.find(item => item.id === backgroundOwner), background);
|
||||||
|
if (pmMissing) await migrateProjectManagement(legacy.find(item => item.id === pmOwner), projectManagement);
|
||||||
return missing.map(entry => entry.id);
|
return missing.map(entry => entry.id);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,239 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
// One PDF tab: the toolbar, the status line, the password form, and one page with its text layer.
|
||||||
|
// The document and its worker live as long as the tab. `close` releases both.
|
||||||
|
import { onMount } from "svelte";
|
||||||
|
import { message, t } from "$lib/i18n";
|
||||||
|
import IconButton from "$lib/ui/IconButton.svelte";
|
||||||
|
import type { PluginDocumentContext } from "$lib/plugins/sdk";
|
||||||
|
import { openPdf, TextLayer, type OpenPdf, type PDFDocumentProxy, type RenderTask } from "./engine";
|
||||||
|
import { MAX_ZOOM, MIN_ZOOM, RESIZE_SETTLE_MS, ZOOM_STEP, nextRotation, outputScale, pageNumber, zoomLevel } from "./model";
|
||||||
|
|
||||||
|
let { file, readBytes }: { file: PluginDocumentContext; readBytes: (path: string) => Promise<Uint8Array> } = $props();
|
||||||
|
|
||||||
|
type Status = { key: string; values?: Record<string, string | number>; alert?: boolean };
|
||||||
|
|
||||||
|
let page = $state(1);
|
||||||
|
let count = $state(0);
|
||||||
|
let zoom = $state(1);
|
||||||
|
let rotation = $state(0);
|
||||||
|
let fit = $state(true);
|
||||||
|
let status = $state<Status>({ key: message("Loading PDF…") });
|
||||||
|
let asking = $state<"needed" | "incorrect" | null>(null);
|
||||||
|
let reloading = $state(false);
|
||||||
|
let failed = $state(false);
|
||||||
|
let scroller: HTMLDivElement;
|
||||||
|
let sheet: HTMLDivElement;
|
||||||
|
let pageInput: HTMLInputElement;
|
||||||
|
let passwordInput: HTMLInputElement | undefined = $state();
|
||||||
|
|
||||||
|
let disposed = false;
|
||||||
|
let pdf: PDFDocumentProxy | undefined;
|
||||||
|
let opened: OpenPdf | undefined;
|
||||||
|
let answer: ((password: string) => void) | undefined;
|
||||||
|
let render: RenderTask | undefined;
|
||||||
|
let text: TextLayer | undefined;
|
||||||
|
let revision = 0;
|
||||||
|
let queue: Promise<void> = Promise.resolve();
|
||||||
|
let loading: Promise<void> = Promise.resolve();
|
||||||
|
let closing: Promise<void> | undefined;
|
||||||
|
|
||||||
|
const ready = $derived(count > 0);
|
||||||
|
|
||||||
|
function fail(reason: unknown) {
|
||||||
|
if (disposed) return;
|
||||||
|
failed = true;
|
||||||
|
status = { key: message("Cannot display this PDF. {reason}"), values: { reason: reason instanceof Error ? reason.message : String(reason) }, alert: true };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Draw the current page again. A newer request cancels the older one. */
|
||||||
|
function schedule() {
|
||||||
|
const request = ++revision;
|
||||||
|
render?.cancel(); text?.cancel();
|
||||||
|
if (pdf && !disposed) status = { key: message("Loading page {page}…"), values: { page } };
|
||||||
|
queue = queue.then(async () => {
|
||||||
|
if (disposed || request !== revision || !pdf || scroller.clientWidth === 0) return;
|
||||||
|
const pdfPage = await pdf.getPage(page);
|
||||||
|
if (disposed || request !== revision) return;
|
||||||
|
const angle = (pdfPage.rotate + rotation) % 360;
|
||||||
|
if (fit) zoom = zoomLevel((scroller.clientWidth - 32) / pdfPage.getViewport({ scale: 1, rotation: angle }).width);
|
||||||
|
const viewport = pdfPage.getViewport({ scale: zoom, rotation: angle });
|
||||||
|
const scale = outputScale(viewport.width, viewport.height, window.devicePixelRatio);
|
||||||
|
const canvas = document.createElement("canvas");
|
||||||
|
canvas.width = Math.max(1, Math.floor(viewport.width * scale));
|
||||||
|
canvas.height = Math.max(1, Math.floor(viewport.height * scale));
|
||||||
|
canvas.style.width = `${viewport.width}px`;
|
||||||
|
canvas.style.height = `${viewport.height}px`;
|
||||||
|
canvas.setAttribute("role", "img");
|
||||||
|
// The measurement tool and the smoke tests find the page by this English name. Keep "PDF page N".
|
||||||
|
canvas.setAttribute("aria-label", $t("PDF page {page}", { page }));
|
||||||
|
const layer = document.createElement("div");
|
||||||
|
layer.className = "textLayer";
|
||||||
|
sheet.style.width = `${viewport.width}px`;
|
||||||
|
sheet.style.height = `${viewport.height}px`;
|
||||||
|
sheet.style.setProperty("--total-scale-factor", String(zoom));
|
||||||
|
sheet.replaceChildren(canvas, layer);
|
||||||
|
render = pdfPage.render({ canvas, viewport, transform: scale === 1 ? undefined : [scale, 0, 0, scale, 0, 0] });
|
||||||
|
await render.promise;
|
||||||
|
if (disposed || request !== revision) return;
|
||||||
|
text = new TextLayer({ textContentSource: pdfPage.streamTextContent(), container: layer, viewport });
|
||||||
|
await text.render();
|
||||||
|
if (disposed || request !== revision) return;
|
||||||
|
status = { key: message("Page {page} of {count}"), values: { page, count } };
|
||||||
|
pdfPage.cleanup();
|
||||||
|
}).catch(reason => { if (!disposed && request === revision) fail(reason); });
|
||||||
|
}
|
||||||
|
|
||||||
|
function go(value: number) {
|
||||||
|
if (!pdf) return;
|
||||||
|
page = pageNumber(value, pdf.numPages);
|
||||||
|
pageInput.value = String(page);
|
||||||
|
scroller.scrollTop = 0;
|
||||||
|
schedule();
|
||||||
|
}
|
||||||
|
|
||||||
|
function setZoom(value: number) { fit = false; zoom = zoomLevel(value); schedule(); }
|
||||||
|
|
||||||
|
async function load() {
|
||||||
|
failed = false;
|
||||||
|
status = { key: message("Loading PDF…") };
|
||||||
|
const bytes = await readBytes(file.path);
|
||||||
|
if (disposed) return;
|
||||||
|
opened = openPdf(bytes, (reason, next) => {
|
||||||
|
if (disposed) return;
|
||||||
|
answer = next;
|
||||||
|
asking = reason;
|
||||||
|
status = reason === "incorrect" ? { key: message("Incorrect password. Try again.") } : { key: message("This PDF needs a password.") };
|
||||||
|
queueMicrotask(() => passwordInput?.focus());
|
||||||
|
});
|
||||||
|
pdf = await opened.promise;
|
||||||
|
if (disposed) return;
|
||||||
|
page = pageNumber(page, pdf.numPages);
|
||||||
|
count = pdf.numPages;
|
||||||
|
schedule();
|
||||||
|
}
|
||||||
|
|
||||||
|
async function release() {
|
||||||
|
revision++;
|
||||||
|
render?.cancel(); text?.cancel();
|
||||||
|
await queue;
|
||||||
|
const current = opened;
|
||||||
|
opened = undefined; pdf = undefined; answer = undefined; asking = null; count = 0;
|
||||||
|
sheet?.replaceChildren();
|
||||||
|
await current?.close();
|
||||||
|
}
|
||||||
|
|
||||||
|
async function reload() {
|
||||||
|
if (reloading || disposed) return;
|
||||||
|
reloading = true;
|
||||||
|
try {
|
||||||
|
await loading;
|
||||||
|
await release();
|
||||||
|
if (!disposed) await (loading = load());
|
||||||
|
} catch (reason) { fail(reason); }
|
||||||
|
finally { reloading = false; }
|
||||||
|
}
|
||||||
|
|
||||||
|
function unlock(event: SubmitEvent) {
|
||||||
|
event.preventDefault();
|
||||||
|
if (!passwordInput || !answer) return;
|
||||||
|
const value = passwordInput.value;
|
||||||
|
passwordInput.value = "";
|
||||||
|
asking = null;
|
||||||
|
status = { key: message("Loading PDF…") };
|
||||||
|
const next = answer;
|
||||||
|
answer = undefined;
|
||||||
|
next(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
function pageKey(event: KeyboardEvent) {
|
||||||
|
if (event.ctrlKey || event.metaKey || event.altKey || !ready) return;
|
||||||
|
if (event.key === "PageDown" || event.key === "PageUp") {
|
||||||
|
event.preventDefault();
|
||||||
|
go(page + (event.key === "PageDown" ? 1 : -1));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Stop the drawing, release the document, and stop its worker. The host calls it before it removes the tab. */
|
||||||
|
export function close(): Promise<void> {
|
||||||
|
if (closing) return closing;
|
||||||
|
disposed = true;
|
||||||
|
closing = release().then(() => loading).catch(() => {});
|
||||||
|
return closing;
|
||||||
|
}
|
||||||
|
|
||||||
|
onMount(() => {
|
||||||
|
loading = load().catch(fail);
|
||||||
|
// A fit-width page follows the width of the tab. The first size draws at once. Later sizes wait until the size settles.
|
||||||
|
let width = 0;
|
||||||
|
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||||
|
const observer = new ResizeObserver(() => {
|
||||||
|
const next = scroller.clientWidth;
|
||||||
|
if (next === 0 || next === width) return;
|
||||||
|
const first = width === 0;
|
||||||
|
width = next;
|
||||||
|
clearTimeout(timer);
|
||||||
|
if (!fit) return;
|
||||||
|
if (first) schedule();
|
||||||
|
else timer = setTimeout(schedule, RESIZE_SETTLE_MS);
|
||||||
|
});
|
||||||
|
observer.observe(scroller);
|
||||||
|
return () => { observer.disconnect(); clearTimeout(timer); void close(); };
|
||||||
|
});
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<section class="pdf-viewer" aria-label={$t("PDF Viewer")}>
|
||||||
|
<div class="toolbar" role="group" aria-label={$t("PDF controls")}>
|
||||||
|
<IconButton icon="up" label={$t("Previous page")} disabled={!ready || page <= 1} onclick={() => go(page - 1)} />
|
||||||
|
<input bind:this={pageInput} class="page" type="number" min="1" max={Math.max(count, 1)} value={page} disabled={!ready}
|
||||||
|
aria-label={$t("Page number")} onchange={event => { if (Number(event.currentTarget.value) !== page) go(Number(event.currentTarget.value)); }}
|
||||||
|
onkeydown={event => { if (event.key === "Enter") go(Number(event.currentTarget.value)); }} />
|
||||||
|
<span class="count">/ {ready ? count : "—"}</span>
|
||||||
|
<IconButton icon="down" label={$t("Next page")} disabled={!ready || page >= count} onclick={() => go(page + 1)} />
|
||||||
|
<span class="separator" aria-hidden="true"></span>
|
||||||
|
<IconButton icon="zoom-out" label={$t("Zoom out")} disabled={!ready || zoom <= MIN_ZOOM} onclick={() => setZoom(zoom / ZOOM_STEP)} />
|
||||||
|
<span class="zoom">{ready ? `${Math.round(zoom * 100)}%` : "—"}</span>
|
||||||
|
<IconButton icon="zoom-in" label={$t("Zoom in")} disabled={!ready || zoom >= MAX_ZOOM} onclick={() => setZoom(zoom * ZOOM_STEP)} />
|
||||||
|
<IconButton icon="fit-width" label={$t("Fit width")} active={fit && ready} disabled={!ready} onclick={() => { fit = true; schedule(); }} />
|
||||||
|
<IconButton icon="rotate" label={$t("Rotate clockwise")} disabled={!ready} onclick={() => { rotation = nextRotation(rotation); schedule(); }} />
|
||||||
|
<IconButton icon="refresh" label={$t("Reload PDF")} disabled={reloading || (!ready && !failed)} onclick={() => void reload()} />
|
||||||
|
</div>
|
||||||
|
<p class="status" class:alert={status.alert} role={status.alert ? "alert" : "status"} aria-live={status.alert ? "assertive" : "polite"}>{$t(status.key, status.values)}</p>
|
||||||
|
{#if asking}
|
||||||
|
<form class="password" onsubmit={unlock}>
|
||||||
|
<label>{$t("PDF password")} <input bind:this={passwordInput} type="password" autocomplete="off" /></label>
|
||||||
|
<button class="text-button" type="submit">{$t("Unlock")}</button>
|
||||||
|
</form>
|
||||||
|
{/if}
|
||||||
|
<!-- The page area takes focus for Page Up and Page Down. -->
|
||||||
|
<!-- svelte-ignore a11y_no_noninteractive_tabindex, a11y_no_noninteractive_element_interactions -->
|
||||||
|
<div bind:this={scroller} class="scroll" tabindex="0" role="region" aria-label={$t("PDF page. Use Page Up and Page Down to change pages.")} onkeydown={pageKey}>
|
||||||
|
<div bind:this={sheet} class="sheet"></div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<style>
|
||||||
|
.pdf-viewer { display: flex; flex-direction: column; height: 100%; min-height: 240px; min-width: 0; color: var(--rs-text); font-size: 13px; }
|
||||||
|
.toolbar { display: flex; flex-wrap: wrap; align-items: center; gap: 2px; padding: 4px 8px; border-bottom: 1px solid var(--rs-border); }
|
||||||
|
.page { box-sizing: border-box; width: 64px; height: 28px; margin-left: 4px; padding: 2px 4px; border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); background: var(--rs-bg); color: var(--rs-text); font: inherit; text-align: right; }
|
||||||
|
.page:disabled { color: var(--rs-text-dim); }
|
||||||
|
.count { margin: 0 4px; color: var(--rs-text-dim); white-space: nowrap; }
|
||||||
|
.separator { width: 1px; height: 18px; margin: 0 4px; background: var(--rs-border); }
|
||||||
|
.zoom { min-width: 44px; color: var(--rs-text-dim); text-align: center; white-space: nowrap; }
|
||||||
|
.status { margin: 0; padding: 4px 12px; font-size: 12px; color: var(--rs-text-dim); overflow-wrap: anywhere; }
|
||||||
|
.status.alert { color: var(--rs-error); }
|
||||||
|
.password { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; padding: 8px 12px; }
|
||||||
|
.password input { box-sizing: border-box; height: 28px; margin-left: 4px; padding: 2px 6px; border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); background: var(--rs-bg); color: var(--rs-text); font: inherit; }
|
||||||
|
.text-button { min-height: 28px; padding: 3px 10px; border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); background: var(--rs-bg-elevated); color: var(--rs-text); font: inherit; }
|
||||||
|
.text-button:hover { background: var(--rs-bg-active); }
|
||||||
|
.scroll { flex: 1; min-height: 0; overflow: auto; padding: 16px; }
|
||||||
|
.scroll:focus-visible { outline-offset: -2px; }
|
||||||
|
/* A PDF page is paper: white in both themes. */
|
||||||
|
.sheet { position: relative; margin: 0 auto; background: white; box-shadow: 0 2px 10px #0003; }
|
||||||
|
.sheet :global(canvas) { display: block; }
|
||||||
|
/* The text layer geometry follows the viewer styles of PDF.js 6 (Apache-2.0). See THIRD_PARTY_NOTICES.md. */
|
||||||
|
.sheet :global(.textLayer) { position: absolute; inset: 0; overflow: clip; text-align: initial; line-height: 1; letter-spacing: normal; word-spacing: normal; text-size-adjust: none; forced-color-adjust: none; transform-origin: 0 0; --min-font-size: 1; --text-scale-factor: calc(var(--total-scale-factor) * var(--min-font-size)); --min-font-size-inv: calc(1 / var(--min-font-size)); }
|
||||||
|
.sheet :global(.textLayer :is(span, br)) { position: absolute; color: transparent; white-space: pre; cursor: text; transform-origin: 0 0; user-select: text; }
|
||||||
|
.sheet :global(.textLayer > :not(.markedContent)), .sheet :global(.markedContent span:not(.markedContent)) { z-index: 1; --font-height: 0; font-size: calc(var(--text-scale-factor) * var(--font-height)); --scale-x: 1; --rotate: 0deg; transform: rotate(var(--rotate)) scaleX(var(--scale-x)) scale(var(--min-font-size-inv)); }
|
||||||
|
.sheet :global(.markedContent) { display: contents; }
|
||||||
|
.sheet :global(.textLayer ::selection) { background: color-mix(in srgb, var(--rs-selection) 65%, transparent); color: transparent; }
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,69 @@
|
|||||||
|
/// <reference types="vite/client" />
|
||||||
|
// PDF.js for the PDF Viewer feature. The worker, the character maps, the standard fonts, and the WebAssembly image
|
||||||
|
// decoders come from the app (`'self'`) as Vite assets, so a PDF never causes a network request.
|
||||||
|
// Each open document has its own worker. `close` stops it.
|
||||||
|
// The reference to the Vite types serves the unit test type check, which reaches this file through `loader.ts`.
|
||||||
|
import { getDocument, PDFWorker, PasswordResponses, type PDFDocumentLoadingTask, type PDFDocumentProxy } from "pdfjs-dist/build/pdf.min.mjs";
|
||||||
|
import workerUrl from "pdfjs-dist/build/pdf.worker.min.mjs?url";
|
||||||
|
|
||||||
|
export { TextLayer, type PDFDocumentProxy, type RenderTask } from "pdfjs-dist/build/pdf.min.mjs";
|
||||||
|
|
||||||
|
// `build.assetsInlineLimit` in vite.config.js keeps these files out of the code, so each one is a file of the app.
|
||||||
|
// The JPEG 2000 and JBIG2 decoders are the only WebAssembly files that PDF.js asks for with `useWorkerFetch: false`.
|
||||||
|
// The viewer runs no PDF scripts (quickjs) and uses no ICC color profiles (qcms), as the PDF Viewer plugin did.
|
||||||
|
const assets = import.meta.glob<string>([
|
||||||
|
"/node_modules/pdfjs-dist/cmaps/*.bcmap",
|
||||||
|
"/node_modules/pdfjs-dist/standard_fonts/*.{pfb,ttf}",
|
||||||
|
"/node_modules/pdfjs-dist/wasm/{jbig2,openjpeg}.wasm",
|
||||||
|
], { query: "?url", import: "default", eager: true });
|
||||||
|
|
||||||
|
const folders: Record<string, string> = { cMapUrl: "cmaps", standardFontDataUrl: "standard_fonts", wasmUrl: "wasm" };
|
||||||
|
|
||||||
|
/** The app URL of a PDF.js data file, or undefined for an unknown kind or file. */
|
||||||
|
export function assetUrl(kind: string, filename: string): string | undefined {
|
||||||
|
const folder = folders[kind];
|
||||||
|
if (!folder || !/^[\w.-]+$/.test(filename)) return undefined;
|
||||||
|
return assets[`/node_modules/pdfjs-dist/${folder}/${filename}`];
|
||||||
|
}
|
||||||
|
|
||||||
|
/** PDF.js asks the window for its data files (`useWorkerFetch: false`). This class reads them from the app. */
|
||||||
|
class AppBinaryDataFactory {
|
||||||
|
async fetch({ kind, filename }: { kind: string; filename: string }): Promise<Uint8Array> {
|
||||||
|
const url = assetUrl(kind, filename);
|
||||||
|
if (!url) throw new Error(`PDF.js has no data file ${filename}.`);
|
||||||
|
const response = await fetch(url);
|
||||||
|
if (!response.ok) throw new Error(`PDF.js could not read ${filename}: ${response.status}.`);
|
||||||
|
return new Uint8Array(await response.arrayBuffer());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface OpenPdf {
|
||||||
|
/** Resolves with the document after the password, if the file needs one. */
|
||||||
|
promise: Promise<PDFDocumentProxy>;
|
||||||
|
/** Stop the load or release the document, and stop the worker. Later calls return the same promise. */
|
||||||
|
close(): Promise<void>;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Open the bytes of a PDF in a new worker. PDF.js calls `onPassword` for a protected file, with "incorrect" after a
|
||||||
|
* wrong password. The viewer calls `answer` with the next password.
|
||||||
|
*/
|
||||||
|
export function openPdf(data: Uint8Array, onPassword: (reason: "needed" | "incorrect", answer: (password: string) => void) => void): OpenPdf {
|
||||||
|
const port = new Worker(workerUrl, { type: "module", name: "PDF.js" });
|
||||||
|
const worker = PDFWorker.create({ port });
|
||||||
|
const task: PDFDocumentLoadingTask = getDocument({
|
||||||
|
data, worker, useWorkerFetch: false, BinaryDataFactory: AppBinaryDataFactory,
|
||||||
|
useSystemFonts: false, isImageDecoderSupported: false, enableXfa: false,
|
||||||
|
});
|
||||||
|
task.onPassword = (answer: (password: string) => void, reason: number) => {
|
||||||
|
onPassword(reason === PasswordResponses.INCORRECT_PASSWORD ? "incorrect" : "needed", answer);
|
||||||
|
};
|
||||||
|
let closing: Promise<void> | undefined;
|
||||||
|
return {
|
||||||
|
promise: task.promise,
|
||||||
|
close: () => closing ??= (async () => {
|
||||||
|
try { await task.destroy(); }
|
||||||
|
finally { worker.destroy(); port.terminate(); }
|
||||||
|
})(),
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
// The PDF Viewer feature. `loader.ts` imports this module when the first PDF tab opens. The file tree marks PDF files
|
||||||
|
// before that, through the document type of the catalog (`../pdfDocument.ts`).
|
||||||
|
// Each tab reads its file with `workspace_read_bytes` (64 MiB at most) and has its own PDF.js worker.
|
||||||
|
import { flushSync, mount, unmount } from "svelte";
|
||||||
|
import { tr } from "../../i18n/index.ts";
|
||||||
|
import { workspaceReadBytes } from "../../workspace/api.ts";
|
||||||
|
import type { FeatureContext, FeatureInstance } from "../types.ts";
|
||||||
|
import PdfViewer from "./PdfViewer.svelte";
|
||||||
|
|
||||||
|
export function start(_context: FeatureContext): FeatureInstance {
|
||||||
|
const tabs = new Set<() => Promise<void>>();
|
||||||
|
let stopped = false;
|
||||||
|
return {
|
||||||
|
mount() { throw new Error(tr("This view is unavailable.")); },
|
||||||
|
mountDocument(type, element, file) {
|
||||||
|
if (type !== "pdf") throw new Error(tr("This view is unavailable."));
|
||||||
|
if (stopped) throw new Error(tr("This feature is off."));
|
||||||
|
const viewer = mount(PdfViewer, { target: element, props: { file, readBytes: workspaceReadBytes } });
|
||||||
|
flushSync();
|
||||||
|
let closing: Promise<void> | undefined;
|
||||||
|
// Release the document and stop its worker first. Then remove the component.
|
||||||
|
const dispose = () => closing ??= viewer.close().then(() => unmount(viewer)).finally(() => { tabs.delete(dispose); });
|
||||||
|
tabs.add(dispose);
|
||||||
|
return dispose;
|
||||||
|
},
|
||||||
|
/** The host closes the PDF tabs first. Close what is left, so no worker stays. */
|
||||||
|
async dispose() {
|
||||||
|
stopped = true;
|
||||||
|
await Promise.allSettled([...tabs].map(dispose => dispose()));
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
// The limits of the PDF Viewer: page numbers, zoom, and the size of the page canvas.
|
||||||
|
|
||||||
|
export const MIN_ZOOM = 0.25;
|
||||||
|
export const MAX_ZOOM = 4;
|
||||||
|
/** Each zoom step multiplies or divides the zoom by this factor. */
|
||||||
|
export const ZOOM_STEP = 1.25;
|
||||||
|
/** A redraw after a resize waits until the size did not change for this time. */
|
||||||
|
export const RESIZE_SETTLE_MS = 150;
|
||||||
|
|
||||||
|
/** A whole page number from 1 to `count`. A value that is not a number gives page 1. */
|
||||||
|
export function pageNumber(value: number, count: number): number {
|
||||||
|
return Math.max(1, Math.min(count, Number.isFinite(value) ? Math.trunc(value) : 1));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A zoom factor from 0.25 to 4. A value that is not a finite number gives 1. */
|
||||||
|
export function zoomLevel(value: number): number {
|
||||||
|
return Math.max(MIN_ZOOM, Math.min(MAX_ZOOM, Number.isFinite(value) ? value : 1));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The next clockwise rotation in degrees: 0, 90, 180, or 270. */
|
||||||
|
export function nextRotation(rotation: number): number {
|
||||||
|
return (rotation + 90) % 360;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The pixel scale of the page canvas. It follows the device pixel ratio up to 2, and keeps each side at most
|
||||||
|
* 8192 pixels and the area at most 16 million pixels, so a large page does not use too much memory.
|
||||||
|
*/
|
||||||
|
export function outputScale(width: number, height: number, deviceScale: number): number {
|
||||||
|
return Math.min(deviceScale || 1, 2, 8192 / width, 8192 / height, Math.sqrt(16_000_000 / (width * height)));
|
||||||
|
}
|
||||||
Vendored
+4
@@ -0,0 +1,4 @@
|
|||||||
|
// The minified build of PDF.js has the same exports as the package entry.
|
||||||
|
declare module "pdfjs-dist/build/pdf.min.mjs" {
|
||||||
|
export * from "pdfjs-dist";
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
// The document identification of the PDF Viewer feature. It is in the main bundle, because the file tree marks
|
||||||
|
// PDF files before the feature module loads. The document ID is the workspace path, so two files never share a tab.
|
||||||
|
|
||||||
|
/** The document ID of a PDF file: its path with forward slashes. Any letter case of the extension matches. */
|
||||||
|
export function identifyPdf(path: string): { id: string } | null {
|
||||||
|
return /\.pdf$/i.test(path) ? { id: path.replaceAll("\\", "/") } : null;
|
||||||
|
}
|
||||||
@@ -0,0 +1,133 @@
|
|||||||
|
// The Project Management feature. `loader.ts` imports this module at the first use: the ribbon button, a board tab,
|
||||||
|
// or a tab transfer from another window. The views are `planning` (All tasks) and `board-<hex of the board ID>`.
|
||||||
|
// The storage code (`storage/`) and the domain code (`model/`) use no host module, so the skill helper can bundle them.
|
||||||
|
import { invoke } from "@tauri-apps/api/core";
|
||||||
|
import { backgroundHub } from "../../plugins/backgrounds.ts";
|
||||||
|
import { onProjectManagementChange, readProjectManagement, readViewStates, writeProjectManagement, writeViewStates } from "../pmSettings.ts";
|
||||||
|
import type { FeatureContext, FeatureInstance } from "../types.ts";
|
||||||
|
import { boardKey, isManagedBoard, readCatalog } from "./storage/catalog.ts";
|
||||||
|
import { findLegacy, hasLegacy, type LegacyContent } from "./storage/legacy.ts";
|
||||||
|
import { isHiddenCard } from "./storage/persistence.ts";
|
||||||
|
import { message } from "./storage/message.ts";
|
||||||
|
import type { BoardReference } from "./storage/board.ts";
|
||||||
|
import { TaskStore } from "./model/store.ts";
|
||||||
|
import { hostMenus } from "./ui/host.ts";
|
||||||
|
import { mountPM, parseViewState, type PMViewState } from "./ui/ui.ts";
|
||||||
|
import { hostWorkspace } from "./workspace.ts";
|
||||||
|
import { boardOfView, boardViewId, PLANNING } from "./views.ts";
|
||||||
|
|
||||||
|
export function start(context: FeatureContext): FeatureInstance {
|
||||||
|
const workspace = hostWorkspace(context.onWorkspaceChange);
|
||||||
|
const preferences = readProjectManagement();
|
||||||
|
const stopPreferences = onProjectManagementChange(() => Object.assign(preferences, readProjectManagement()));
|
||||||
|
const states = new Map<string, PMViewState>(Object.entries(readViewStates()).map(([key, value]) => [key, parseViewState(value)]));
|
||||||
|
const dirty = new Set<string>();
|
||||||
|
let saveTimer: ReturnType<typeof setTimeout> | undefined;
|
||||||
|
let disposed = false;
|
||||||
|
const mounted = new Set<() => void>();
|
||||||
|
/** The legacy data of each workspace root. A migration reads it again. */
|
||||||
|
const legacy = new Map<string, Promise<LegacyContent>>();
|
||||||
|
|
||||||
|
const flush = () => {
|
||||||
|
clearTimeout(saveTimer);
|
||||||
|
if (!dirty.size) return;
|
||||||
|
writeViewStates(Object.fromEntries([...dirty].map(key => [key, structuredClone(states.get(key))])));
|
||||||
|
dirty.clear();
|
||||||
|
};
|
||||||
|
const persist = (id: string) => {
|
||||||
|
if (disposed) return;
|
||||||
|
dirty.add(id);
|
||||||
|
clearTimeout(saveTimer);
|
||||||
|
saveTimer = setTimeout(flush, 200);
|
||||||
|
};
|
||||||
|
const root = () => invoke<string | null>("workspace_last_path").catch(() => null);
|
||||||
|
const legacyContent = async (fresh = false) => {
|
||||||
|
const key = await root() ?? "";
|
||||||
|
if (fresh) legacy.delete(key);
|
||||||
|
let pending = legacy.get(key);
|
||||||
|
if (!pending) {
|
||||||
|
pending = findLegacy(workspace, () => { if (disposed) throw new Error(message("Project Management is off.")); });
|
||||||
|
pending.catch(() => legacy.delete(key));
|
||||||
|
legacy.set(key, pending);
|
||||||
|
}
|
||||||
|
return pending;
|
||||||
|
};
|
||||||
|
/** Copy the legacy boards, the root label file, and every legacy task note to `.runestone/pm/`, with backups. */
|
||||||
|
const migrate = async () => {
|
||||||
|
const store = new TaskStore(workspace, undefined, { legacy: true });
|
||||||
|
try {
|
||||||
|
await store.reload();
|
||||||
|
const cards = store.tasks.filter(task => !isHiddenCard(task.path)).map(task => task.id);
|
||||||
|
return await store.migrateStorage(cards);
|
||||||
|
} finally {
|
||||||
|
store.dispose();
|
||||||
|
void legacyContent(true).catch(() => undefined);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const openBoard = async (path: string, from?: string) => {
|
||||||
|
const snapshot = await readCatalog(workspace);
|
||||||
|
const board = isManagedBoard(path) ? snapshot.value.boards.find(item => boardKey(item.value.id) === path) : undefined;
|
||||||
|
if (!board) throw new Error(message("This board is unavailable. Refresh Project Management."));
|
||||||
|
const id = boardViewId(board.value.id);
|
||||||
|
context.setViewTitle(id, board.name);
|
||||||
|
if (from) context.replaceView(from, id); else context.openView(id);
|
||||||
|
};
|
||||||
|
|
||||||
|
function mountView(view: string, element: HTMLElement) {
|
||||||
|
const boardId = view === PLANNING ? null : boardOfView(view);
|
||||||
|
if (view !== PLANNING && !boardId) throw new Error(message("This view is unavailable."));
|
||||||
|
const reference: BoardReference | undefined = boardId ? { id: boardId, path: boardKey(boardId) } : undefined;
|
||||||
|
if (!states.has(view)) states.set(view, {});
|
||||||
|
const store = new TaskStore(workspace, reference, { legacy: false });
|
||||||
|
if (boardId) {
|
||||||
|
void readCatalog(workspace).then(snapshot => {
|
||||||
|
const board = snapshot.value.boards.find(item => item.value.id === boardId);
|
||||||
|
if (board && !disposed) context.setViewTitle(view, board.name);
|
||||||
|
}, () => undefined);
|
||||||
|
}
|
||||||
|
const cleanup = mountPM(element, store, {
|
||||||
|
ui: hostMenus,
|
||||||
|
backgrounds: backgroundHub,
|
||||||
|
state: states.get(view),
|
||||||
|
stateChanged: () => persist(view),
|
||||||
|
preferences,
|
||||||
|
savePreferences: value => writeProjectManagement(value),
|
||||||
|
openBoard: (path, replace) => openBoard(path, replace ? view : undefined),
|
||||||
|
openAll: replace => { if (replace) context.replaceView(view, PLANNING); else context.openView(PLANNING); },
|
||||||
|
boardRenamed: name => { if (boardId) context.setViewTitle(view, name); },
|
||||||
|
boardDeleted: () => { if (boardId) context.closeView(view); },
|
||||||
|
watch: workspace.watch,
|
||||||
|
legacy: { find: legacyContent, has: hasLegacy, migrate },
|
||||||
|
});
|
||||||
|
mounted.add(cleanup);
|
||||||
|
return () => { mounted.delete(cleanup); cleanup(); };
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
mount: mountView,
|
||||||
|
async launch(view) {
|
||||||
|
if (view !== PLANNING) { context.openView(view); return; }
|
||||||
|
// The default board of the workspace is in the catalog. A missing, archived, or damaged default opens All tasks.
|
||||||
|
try {
|
||||||
|
const { value } = await readCatalog(workspace);
|
||||||
|
const board = value.boards.find(item => item.value.id === value.defaultBoardId && !item.archived);
|
||||||
|
if (board) { await openBoard(boardKey(board.value.id)); return; }
|
||||||
|
} catch { /* All tasks shows the storage problem. */ }
|
||||||
|
context.openView(PLANNING);
|
||||||
|
},
|
||||||
|
saveTabState: view => structuredClone(states.get(view) ?? {}),
|
||||||
|
restoreTabState(view, value) {
|
||||||
|
if (view !== PLANNING && !boardOfView(view)) throw new Error(message("This view is unavailable."));
|
||||||
|
states.set(view, parseViewState(value));
|
||||||
|
persist(view);
|
||||||
|
},
|
||||||
|
dispose() {
|
||||||
|
disposed = true;
|
||||||
|
flush();
|
||||||
|
stopPreferences();
|
||||||
|
for (const cleanup of [...mounted]) cleanup();
|
||||||
|
mounted.clear();
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,77 @@
|
|||||||
|
import { defaultBoard, type BoardDocument, type BoardList } from "../storage/board.ts";
|
||||||
|
import type { Task } from "./model.ts";
|
||||||
|
import { message } from "../storage/message.ts";
|
||||||
|
|
||||||
|
export interface TaskColumn {
|
||||||
|
list?: BoardList;
|
||||||
|
tasks: Task[];
|
||||||
|
allowCreate?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Merge equal list names without changing the cards' board placements. */
|
||||||
|
export function allTaskColumns(boards: BoardDocument[], tasks: Task[]): TaskColumn[] {
|
||||||
|
const active = boards.filter(board => !board.archived);
|
||||||
|
const columns = new Map<string, TaskColumn>();
|
||||||
|
const assigned = new Set<string>();
|
||||||
|
const append = (list: BoardList | undefined, members: Task[], allowCreate = false) => {
|
||||||
|
const key = list ? `list:${list.name.trim().toLowerCase()}` : "unlisted";
|
||||||
|
let column = columns.get(key);
|
||||||
|
if (!column) {
|
||||||
|
column = { list: list ? { id: allowCreate ? list.id : key, name: list.name, status: list.status, collapsed: false } : undefined, tasks: [], allowCreate };
|
||||||
|
columns.set(key, column);
|
||||||
|
}
|
||||||
|
const included = new Set(column.tasks.map(task => task.id));
|
||||||
|
for (const task of members) if (!included.has(task.id)) {
|
||||||
|
column.tasks.push(task);
|
||||||
|
included.add(task.id);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
for (const board of active) {
|
||||||
|
const members = tasks.filter(task => Object.hasOwn(task.placements ?? {}, board.id));
|
||||||
|
for (const task of members) assigned.add(task.id);
|
||||||
|
for (const list of board.value.lists)
|
||||||
|
append(list, members.filter(task => task.placements![board.id].listId === list.id));
|
||||||
|
const unlisted = members.filter(task => !board.value.lists.some(list => list.id === task.placements![board.id].listId));
|
||||||
|
if (unlisted.length) append(undefined, unlisted);
|
||||||
|
}
|
||||||
|
const standalone = tasks.filter(task => !assigned.has(task.id));
|
||||||
|
if (standalone.length || !active.length) {
|
||||||
|
for (const list of defaultBoard("all-tasks").lists)
|
||||||
|
append(list, standalone.filter(task => task.status === list.status), true);
|
||||||
|
}
|
||||||
|
return [...columns.values()];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface TaskBoardGroup {
|
||||||
|
boardIds: string[];
|
||||||
|
name: string;
|
||||||
|
tasks: Task[];
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Keep shared cards once and name every board represented in this column. */
|
||||||
|
export function allTaskGroups(boards: BoardDocument[], column: TaskColumn): TaskBoardGroup[] {
|
||||||
|
const active = boards.filter(board => !board.archived);
|
||||||
|
const groups = new Map<string, TaskBoardGroup>();
|
||||||
|
for (const task of column.tasks) {
|
||||||
|
const owners = active.filter(board => {
|
||||||
|
const placement = task.placements?.[board.id];
|
||||||
|
if (!placement) return false;
|
||||||
|
const list = board.value.lists.find(list => list.id === placement.listId);
|
||||||
|
return column.list
|
||||||
|
? list?.name.trim().toLowerCase() === column.list.name.trim().toLowerCase()
|
||||||
|
: !list;
|
||||||
|
});
|
||||||
|
const boardIds = owners.map(board => board.id);
|
||||||
|
const key = JSON.stringify(boardIds);
|
||||||
|
let group = groups.get(key);
|
||||||
|
if (!group) {
|
||||||
|
group = { boardIds, name: owners.length ? owners.map(board => board.name).join(" · ") : message("No active board"), tasks: [] };
|
||||||
|
groups.set(key, group);
|
||||||
|
}
|
||||||
|
group.tasks.push(task);
|
||||||
|
}
|
||||||
|
return [...groups.values()].sort((a, b) => {
|
||||||
|
const order = (group: TaskBoardGroup) => group.boardIds.length ? active.findIndex(board => board.id === group.boardIds[0]) : active.length;
|
||||||
|
return order(a) - order(b);
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
export const backgroundPositions = ["center", "top left", "top", "top right", "left", "right", "bottom left", "bottom", "bottom right"] as const;
|
||||||
|
export const backgroundSizes = ["cover", "contain", "auto"] as const;
|
||||||
|
export interface BackgroundAppearance { overlay: number; position: typeof backgroundPositions[number]; size: typeof backgroundSizes[number] }
|
||||||
|
export function parseBackground(value: unknown): BackgroundAppearance {
|
||||||
|
const raw = value as Partial<BackgroundAppearance> | null;
|
||||||
|
return { overlay: typeof raw?.overlay === "number" && Number.isFinite(raw.overlay) ? Math.max(-1, Math.min(1, raw.overlay)) : 0,
|
||||||
|
position: backgroundPositions.includes(raw?.position as any) ? raw!.position! : "center",
|
||||||
|
size: backgroundSizes.includes(raw?.size as any) ? raw!.size! : "cover" };
|
||||||
|
}
|
||||||
|
export function backgroundOverlay(value: number) {
|
||||||
|
const color = value < 0 ? `rgba(255,255,255,${-value})` : `rgba(0,0,0,${value})`;
|
||||||
|
return `linear-gradient(${color}, ${color})`;
|
||||||
|
}
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
export function headingEdit(value: string, selectionStart: number, selectionEnd: number) {
|
||||||
|
const start = selectionStart === 0 ? 0 : value.lastIndexOf("\n", selectionStart - 1) + 1;
|
||||||
|
const last = selectionEnd > selectionStart && value[selectionEnd - 1] === "\n"
|
||||||
|
? selectionEnd - 1 : selectionEnd;
|
||||||
|
const next = value.indexOf("\n", last);
|
||||||
|
const end = next < 0 ? value.length : next;
|
||||||
|
const edits: { start: number; removed: number; added: number }[] = [];
|
||||||
|
let offset = start;
|
||||||
|
const text = value.slice(start, end).split("\n").map(line => {
|
||||||
|
const prefix = /^( {0,3})(#{1,6})(?:[\t ]+|$)/.exec(line);
|
||||||
|
const removed = prefix?.[0].length ?? 0;
|
||||||
|
const replacement = `${prefix?.[1] ?? ""}## `;
|
||||||
|
edits.push({ start: offset, removed, added: replacement.length });
|
||||||
|
offset += line.length + 1;
|
||||||
|
return replacement + line.slice(removed);
|
||||||
|
}).join("\n");
|
||||||
|
const position = (original: number) => {
|
||||||
|
let result = original;
|
||||||
|
for (const edit of edits) {
|
||||||
|
if (original < edit.start) break;
|
||||||
|
result += original < edit.start + edit.removed
|
||||||
|
? edit.added - (original - edit.start) : edit.added - edit.removed;
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
};
|
||||||
|
return { start, end, text, selectionStart: position(selectionStart), selectionEnd: position(selectionEnd) };
|
||||||
|
}
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
import MarkdownIt from "markdown-it";
|
||||||
|
import { imagePath } from "../storage/images.ts";
|
||||||
|
|
||||||
|
const markdown = new MarkdownIt({ html: false, linkify: false, breaks: true });
|
||||||
|
markdown.validateLink = (url) => /^(https?:|mailto:|#|pm-image:)/i.test(url);
|
||||||
|
markdown.renderer.rules.link_open = (tokens, index, options, _env, self) => {
|
||||||
|
const token = tokens[index];
|
||||||
|
const href = String(token.attrGet("href") ?? "");
|
||||||
|
if (!/^(https?:|mailto:|#)/i.test(href)) token.attrs = [];
|
||||||
|
else {
|
||||||
|
token.attrSet("target", "_blank");
|
||||||
|
token.attrSet("rel", "noopener noreferrer");
|
||||||
|
}
|
||||||
|
return self.renderToken(tokens, index, options);
|
||||||
|
};
|
||||||
|
// Image sources come only from the validated workspace image store, never from Markdown URLs.
|
||||||
|
markdown.renderer.rules.image = (tokens, index) => {
|
||||||
|
const token = tokens[index];
|
||||||
|
const id = String(token.attrGet("src") ?? "").replace(/^pm-image:/, "");
|
||||||
|
const name = markdown.utils.escapeHtml(token.content || "Image");
|
||||||
|
try {
|
||||||
|
imagePath(id);
|
||||||
|
return `<img data-pm-image="${id}" alt="${name}">`;
|
||||||
|
} catch {
|
||||||
|
return `<span class="pm-muted">Image: ${name} (use Add image to import)</span>`;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
export function renderMarkdown(source: string): string {
|
||||||
|
return markdown.render(source);
|
||||||
|
}
|
||||||
@@ -0,0 +1,255 @@
|
|||||||
|
import { message } from "../storage/message.ts";
|
||||||
|
|
||||||
|
export const statuses = ["todo", "doing", "done"] as const;
|
||||||
|
export type Status = (typeof statuses)[number];
|
||||||
|
export const priorities = ["highest", "high", "medium", "low", "lowest"] as const;
|
||||||
|
export type PriorityLevels = 2 | 3 | 5;
|
||||||
|
export function availablePriorities(levels: PriorityLevels): readonly Priority[] {
|
||||||
|
return levels === 2 ? ["high", "low"] : levels === 3 ? ["high", "medium", "low"] : priorities;
|
||||||
|
}
|
||||||
|
export type Priority = (typeof priorities)[number];
|
||||||
|
export const priorityNames: Record<Priority, string> = {
|
||||||
|
highest: message("Highest"),
|
||||||
|
high: message("High"),
|
||||||
|
medium: message("Medium"),
|
||||||
|
low: message("Low"),
|
||||||
|
lowest: message("Lowest"),
|
||||||
|
};
|
||||||
|
export const statusNames: Record<Status, string> = {
|
||||||
|
todo: message("To do"),
|
||||||
|
doing: message("In progress"),
|
||||||
|
done: message("Done"),
|
||||||
|
};
|
||||||
|
export const cardColors = {
|
||||||
|
red: "#df7373",
|
||||||
|
orange: "#d99554",
|
||||||
|
amber: "#dda83e",
|
||||||
|
yellow: "#c5ae4f",
|
||||||
|
lime: "#a4bd58",
|
||||||
|
green: "#63ad84",
|
||||||
|
teal: "#4cafa6",
|
||||||
|
cyan: "#53b8cf",
|
||||||
|
blue: "#729fe0",
|
||||||
|
indigo: "#8790df",
|
||||||
|
purple: "#ac89d8",
|
||||||
|
magenta: "#cb75c8",
|
||||||
|
pink: "#d784b0",
|
||||||
|
brown: "#b48b68",
|
||||||
|
slate: "#8398ae",
|
||||||
|
gray: "#a4a6ad",
|
||||||
|
} as const;
|
||||||
|
export interface Plan {
|
||||||
|
start: string;
|
||||||
|
end: string;
|
||||||
|
}
|
||||||
|
export interface Session {
|
||||||
|
id: string;
|
||||||
|
start: string;
|
||||||
|
end: string;
|
||||||
|
timeZone: string;
|
||||||
|
}
|
||||||
|
export interface TaskFields {
|
||||||
|
createdAt?: string;
|
||||||
|
title?: string;
|
||||||
|
order?: string;
|
||||||
|
color?: string;
|
||||||
|
assignees?: string[];
|
||||||
|
customFields?: { name: string; value: string }[];
|
||||||
|
listId?: string | null;
|
||||||
|
placements?: Record<string, { listId: string | null; order?: string }>;
|
||||||
|
status: Status;
|
||||||
|
tags: string[];
|
||||||
|
labels?: string[];
|
||||||
|
priority?: Priority | null;
|
||||||
|
coverImage?: string | null;
|
||||||
|
attachments?: { id: string; name: string }[];
|
||||||
|
subtasks?: { id: string; title: string; done: boolean; taskId?: string }[];
|
||||||
|
links?: { taskId: string; relation: "relates" | "blocks" | "blocked-by" }[];
|
||||||
|
due?: { date: string };
|
||||||
|
plan?: Plan;
|
||||||
|
sessions: Session[];
|
||||||
|
archived: boolean;
|
||||||
|
}
|
||||||
|
export interface Task extends TaskFields {
|
||||||
|
id: string;
|
||||||
|
path: string;
|
||||||
|
title: string;
|
||||||
|
body: string;
|
||||||
|
source: string;
|
||||||
|
}
|
||||||
|
export interface Entry {
|
||||||
|
name: string;
|
||||||
|
rel_path: string;
|
||||||
|
kind: string;
|
||||||
|
}
|
||||||
|
export interface Workspace {
|
||||||
|
list(path?: string): Promise<Entry[]>;
|
||||||
|
listMarkdown?(): Promise<string[]>;
|
||||||
|
read(path: string): Promise<string>;
|
||||||
|
readMany?(paths: string[]): Promise<{ path: string; source?: string; error?: string }[]>;
|
||||||
|
readOptional?(path: string): Promise<string | null>;
|
||||||
|
write(path: string, contents: string, expected: string): Promise<void>;
|
||||||
|
create?(path: string, contents: string): Promise<void>;
|
||||||
|
subscribe?(listener: () => void): () => void;
|
||||||
|
}
|
||||||
|
export function validDate(value: unknown): value is string {
|
||||||
|
if (typeof value !== "string" || !/^\d{4}-\d{2}-\d{2}$/.test(value))
|
||||||
|
return false;
|
||||||
|
const date = new Date(`${value}T00:00:00Z`);
|
||||||
|
return !isNaN(date.getTime()) && date.toISOString().slice(0, 10) === value;
|
||||||
|
}
|
||||||
|
export function addDays(value: string, days: number): string {
|
||||||
|
if (!validDate(value)) throw new Error(message("Enter a valid calendar date."));
|
||||||
|
const date = new Date(`${value}T12:00:00Z`);
|
||||||
|
date.setUTCDate(date.getUTCDate() + days);
|
||||||
|
return date.toISOString().slice(0, 10);
|
||||||
|
}
|
||||||
|
export function dayDistance(start: string, end: string): number {
|
||||||
|
return Math.round(
|
||||||
|
(Date.parse(`${end}T12:00:00Z`) - Date.parse(`${start}T12:00:00Z`)) /
|
||||||
|
86_400_000,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
export function localDay(date = new Date()): string {
|
||||||
|
return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")}`;
|
||||||
|
}
|
||||||
|
export function localTime(instant: string): string {
|
||||||
|
const date = new Date(instant);
|
||||||
|
return `${localDay(date)}T${String(date.getHours()).padStart(2, "0")}:${String(date.getMinutes()).padStart(2, "0")}`;
|
||||||
|
}
|
||||||
|
export function localInstant(value: string): string {
|
||||||
|
const date = new Date(value);
|
||||||
|
if (isNaN(date.getTime()) || localTime(date.toISOString()) !== value)
|
||||||
|
throw new Error(message("Enter an existing local date and time."));
|
||||||
|
return date.toISOString();
|
||||||
|
}
|
||||||
|
export function validateFields(fields: TaskFields): void {
|
||||||
|
if (fields.createdAt !== undefined && (typeof fields.createdAt !== "string" ||
|
||||||
|
!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/.test(fields.createdAt) ||
|
||||||
|
!validDate(fields.createdAt.slice(0, 10)) || !Number.isFinite(Date.parse(fields.createdAt))))
|
||||||
|
throw new Error(message("The card creation timestamp is invalid."));
|
||||||
|
if (fields.attachments !== undefined && (!Array.isArray(fields.attachments) || fields.attachments.some(item => !item || typeof item.id !== "string" || !/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/.test(item.id) || typeof item.name !== "string" || !item.name.trim() || item.name.length > 255) || new Set(fields.attachments.map(item => item.id)).size !== fields.attachments.length))
|
||||||
|
throw new Error(message("Each image attachment needs a unique image ID and a name of 1 to 255 characters."));
|
||||||
|
if (fields.priority !== undefined && fields.priority !== null && !priorities.includes(fields.priority))
|
||||||
|
throw new Error(message("Choose a supported priority or No priority."));
|
||||||
|
if (fields.coverImage != null && !/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/.test(fields.coverImage))
|
||||||
|
throw new Error(message("Choose an image from this card."));
|
||||||
|
if (fields.subtasks !== undefined && (!Array.isArray(fields.subtasks) || fields.subtasks.some(item => !item || typeof item.id !== "string" || !item.id || typeof item.title !== "string" || !item.title.trim() || item.title.length > 200 || typeof item.done !== "boolean" || (item.taskId !== undefined && (typeof item.taskId !== "string" || !item.taskId))) || new Set(fields.subtasks.map(item => item.id)).size !== fields.subtasks.length))
|
||||||
|
throw new Error(message("Each subtask needs a unique ID, a title, and a completion state."));
|
||||||
|
if (fields.links !== undefined && (!Array.isArray(fields.links) || fields.links.some(item => !item || typeof item.taskId !== "string" || !item.taskId || !["relates", "blocks", "blocked-by"].includes(item.relation)) || new Set(fields.links.map(item => item.taskId)).size !== fields.links.length))
|
||||||
|
throw new Error(message("Choose each linked card once and select its relationship."));
|
||||||
|
if (
|
||||||
|
fields.title !== undefined &&
|
||||||
|
(typeof fields.title !== "string" ||
|
||||||
|
!fields.title.trim() ||
|
||||||
|
fields.title.length > 100 ||
|
||||||
|
/[\x00-\x1f]/.test(fields.title))
|
||||||
|
)
|
||||||
|
throw new Error(message("Enter a card title of 1 to 100 characters."));
|
||||||
|
const validOrder = (value: unknown) =>
|
||||||
|
value === undefined ||
|
||||||
|
(typeof value === "string" && /^[0-9a-z]*[1-9a-z]$/.test(value));
|
||||||
|
if (!validOrder(fields.order))
|
||||||
|
throw new Error(message("The card order is invalid. Refresh the board."));
|
||||||
|
if (fields.placements !== undefined) {
|
||||||
|
if (
|
||||||
|
!fields.placements ||
|
||||||
|
typeof fields.placements !== "object" ||
|
||||||
|
Array.isArray(fields.placements)
|
||||||
|
)
|
||||||
|
throw new Error(message("Board placements must be a mapping."));
|
||||||
|
for (const [id, placement] of Object.entries(fields.placements)) {
|
||||||
|
if (
|
||||||
|
!id.trim() ||
|
||||||
|
!placement ||
|
||||||
|
typeof placement !== "object" ||
|
||||||
|
Array.isArray(placement) ||
|
||||||
|
(placement.listId !== null &&
|
||||||
|
(typeof placement.listId !== "string" || !placement.listId)) ||
|
||||||
|
!validOrder(placement.order)
|
||||||
|
)
|
||||||
|
throw new Error(message("Each board placement needs a board ID and a valid list ID."));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (
|
||||||
|
fields.color !== undefined &&
|
||||||
|
(typeof fields.color !== "string" ||
|
||||||
|
!Object.hasOwn(cardColors, fields.color))
|
||||||
|
)
|
||||||
|
throw new Error(message("Choose a supported card color."));
|
||||||
|
if (
|
||||||
|
fields.assignees !== undefined &&
|
||||||
|
(!Array.isArray(fields.assignees) ||
|
||||||
|
fields.assignees.some((name) => typeof name !== "string" || !name.trim()))
|
||||||
|
)
|
||||||
|
throw new Error(message("Assignments must contain names."));
|
||||||
|
if (fields.customFields !== undefined) {
|
||||||
|
if (
|
||||||
|
!Array.isArray(fields.customFields) ||
|
||||||
|
fields.customFields.some(
|
||||||
|
(field) =>
|
||||||
|
!field ||
|
||||||
|
typeof field.name !== "string" ||
|
||||||
|
!field.name.trim() ||
|
||||||
|
typeof field.value !== "string",
|
||||||
|
)
|
||||||
|
)
|
||||||
|
throw new Error(message("Each custom field needs a name and a text value."));
|
||||||
|
const names = fields.customFields.map((field) =>
|
||||||
|
field.name.trim().toLocaleLowerCase(),
|
||||||
|
);
|
||||||
|
if (new Set(names).size !== names.length)
|
||||||
|
throw new Error(message("Use a different name for each custom field."));
|
||||||
|
}
|
||||||
|
if (
|
||||||
|
fields.listId !== undefined &&
|
||||||
|
fields.listId !== null &&
|
||||||
|
(typeof fields.listId !== "string" || !fields.listId)
|
||||||
|
)
|
||||||
|
throw new Error(message("The task has an invalid list ID."));
|
||||||
|
if (!statuses.includes(fields.status))
|
||||||
|
throw new Error(message("Choose a supported task status."));
|
||||||
|
if (
|
||||||
|
!Array.isArray(fields.tags) ||
|
||||||
|
fields.tags.some((tag) => typeof tag !== "string")
|
||||||
|
)
|
||||||
|
throw new Error(message("Tags must be text."));
|
||||||
|
if (
|
||||||
|
fields.labels !== undefined &&
|
||||||
|
(!Array.isArray(fields.labels) ||
|
||||||
|
fields.labels.some(
|
||||||
|
(id) => typeof id !== "string" || !/^[a-zA-Z0-9_-]{1,100}$/.test(id),
|
||||||
|
) ||
|
||||||
|
new Set(fields.labels).size !== fields.labels.length)
|
||||||
|
)
|
||||||
|
throw new Error(message("Labels must contain unique saved label IDs."));
|
||||||
|
if (fields.due && !validDate(fields.due.date))
|
||||||
|
throw new Error(message("Enter a valid deadline date."));
|
||||||
|
if (
|
||||||
|
fields.plan &&
|
||||||
|
(!validDate(fields.plan.start) ||
|
||||||
|
!validDate(fields.plan.end) ||
|
||||||
|
fields.plan.end <= fields.plan.start)
|
||||||
|
) {
|
||||||
|
throw new Error(message("The planned end must follow the start."));
|
||||||
|
}
|
||||||
|
const ids = new Set<string>();
|
||||||
|
for (const session of fields.sessions) {
|
||||||
|
const instant =
|
||||||
|
/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/;
|
||||||
|
if (
|
||||||
|
!session.id ||
|
||||||
|
ids.has(session.id) ||
|
||||||
|
!instant.test(session.start) ||
|
||||||
|
!instant.test(session.end) ||
|
||||||
|
!validDate(session.start.slice(0, 10)) ||
|
||||||
|
!validDate(session.end.slice(0, 10)) ||
|
||||||
|
!Number.isFinite(Date.parse(session.start)) ||
|
||||||
|
!Number.isFinite(Date.parse(session.end)) ||
|
||||||
|
Date.parse(session.end) <= Date.parse(session.start)
|
||||||
|
)
|
||||||
|
throw new Error(message("Each session needs a unique ID and a valid time range."));
|
||||||
|
new Intl.DateTimeFormat("en", { timeZone: session.timeZone }).format();
|
||||||
|
ids.add(session.id);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,880 @@
|
|||||||
|
import { readTask, editTask, adoptNote, split } from "../storage/notes.ts";
|
||||||
|
import { createCard, readCards, cardOrigin, cardPath, fileIssue, migrateCards, parseCard, prepareCards } from "../storage/cards.ts";
|
||||||
|
import { cardsFolder, cardsMarker, isHiddenCard, readOptional, saveDocument, storageRoot } from "../storage/persistence.ts";
|
||||||
|
import { deletedCardsPath, readDeletedCards, recordCardDeletion } from "../storage/deleted-cards.ts";
|
||||||
|
import { mapConcurrent, markdownPaths, readSources } from "../storage/scan.ts";
|
||||||
|
import type { Task, TaskFields, Workspace } from "./model.ts";
|
||||||
|
import { cardOrder, compareCards, orderBetween } from "../storage/order.ts";
|
||||||
|
import { LabelStore, labelsPath, parseLabels, type LabelSnapshot, type SavedLabel } from "../storage/labels.ts";
|
||||||
|
import {
|
||||||
|
catalogPath,
|
||||||
|
readCatalog,
|
||||||
|
managedDocuments,
|
||||||
|
isManagedBoard,
|
||||||
|
createBoard,
|
||||||
|
} from "../storage/catalog.ts";
|
||||||
|
import { migrateStorage } from "../storage/migration.ts";
|
||||||
|
import { format, message } from "../storage/message.ts";
|
||||||
|
import {
|
||||||
|
BoardStore,
|
||||||
|
boardDocument,
|
||||||
|
type BoardDocument,
|
||||||
|
type BoardReference,
|
||||||
|
} from "../storage/board.ts";
|
||||||
|
|
||||||
|
const workspaceTasks = new WeakMap<Workspace, Task[]>();
|
||||||
|
|
||||||
|
export interface TaskStoreOptions {
|
||||||
|
/**
|
||||||
|
* True (the default) also reads the visible Markdown notes of the legacy format: boards and task notes in the workspace.
|
||||||
|
* The migration and the read-only skill helper use it. False reads only `.runestone/pm/`, and a save, a delete,
|
||||||
|
* or a move reads only the changed files again. The native feature of RuneStone uses false.
|
||||||
|
*/
|
||||||
|
legacy?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
const errorMessage = (error: unknown) => error instanceof Error ? error.message : String(error);
|
||||||
|
/** The issue of a task ID that more than one note uses. `adopt()` looks for this issue. */
|
||||||
|
const duplicateTaskIssue = (id: string) =>
|
||||||
|
format(message("Duplicate task ID {id}: resolve the copied notes before editing them."), { id });
|
||||||
|
|
||||||
|
/** The files of `.runestone/pm/` that the hidden mode reads, with the problem of each file. */
|
||||||
|
interface HiddenState {
|
||||||
|
cards: Map<string, Task>;
|
||||||
|
cardIssues: Map<string, string>;
|
||||||
|
cardsError: string;
|
||||||
|
catalog: { source: string | null; boards: BoardDocument[]; error: string };
|
||||||
|
labels: { snapshot?: LabelSnapshot; error: string };
|
||||||
|
deleted: { ids: Set<string>; error: string };
|
||||||
|
}
|
||||||
|
|
||||||
|
export class TaskStore {
|
||||||
|
tasks: Task[] = [];
|
||||||
|
boards: BoardDocument[] = [];
|
||||||
|
legacyBoards: BoardDocument[] = [];
|
||||||
|
issues: string[] = [];
|
||||||
|
private queue: Promise<unknown> = Promise.resolve();
|
||||||
|
private disposed = false;
|
||||||
|
private loaded = false;
|
||||||
|
private revision = 0;
|
||||||
|
private hidden?: HiddenState;
|
||||||
|
readonly legacy: boolean;
|
||||||
|
readonly workspace: Workspace;
|
||||||
|
readonly board: BoardStore;
|
||||||
|
readonly labels: LabelStore;
|
||||||
|
constructor(workspace: Workspace, board?: BoardReference, options: TaskStoreOptions = {}) {
|
||||||
|
this.workspace = workspace;
|
||||||
|
this.legacy = options.legacy ?? true;
|
||||||
|
this.tasks = workspaceTasks.get(workspace) ?? [];
|
||||||
|
this.board = new BoardStore(workspace, board);
|
||||||
|
this.labels = new LabelStore(workspace);
|
||||||
|
}
|
||||||
|
get scopedTasks() {
|
||||||
|
const id = this.board.reference?.id;
|
||||||
|
return id
|
||||||
|
? this.board.available
|
||||||
|
? this.tasks.filter((task) => Object.hasOwn(task.placements ?? {}, id))
|
||||||
|
: []
|
||||||
|
: this.tasks;
|
||||||
|
}
|
||||||
|
dispose() {
|
||||||
|
this.disposed = true;
|
||||||
|
}
|
||||||
|
private check() {
|
||||||
|
if (this.disposed)
|
||||||
|
throw new Error(message("The Project Management view is closed. Reopen it before saving."));
|
||||||
|
}
|
||||||
|
/** Read all Project Management data again. */
|
||||||
|
async reload(): Promise<void> {
|
||||||
|
if (this.legacy) return this.reloadLegacy();
|
||||||
|
this.check();
|
||||||
|
const revision = ++this.revision;
|
||||||
|
const previous = this.hidden?.cards ?? new Map(this.tasks.map((task) => [task.path, task]));
|
||||||
|
const state: HiddenState = {
|
||||||
|
cards: new Map(), cardIssues: new Map(), cardsError: "",
|
||||||
|
catalog: { source: null, boards: [], error: "" }, labels: { error: "" }, deleted: { ids: new Set(), error: "" },
|
||||||
|
};
|
||||||
|
try {
|
||||||
|
// Direct reads are necessary because the host hides .runestone from root listings.
|
||||||
|
if ((await readOptional(this.workspace, cardsMarker)) !== null) {
|
||||||
|
const paths = (await this.workspace.list(cardsFolder))
|
||||||
|
.filter((entry) => entry.kind !== "folder" && isHiddenCard(entry.rel_path)).map((entry) => entry.rel_path);
|
||||||
|
const sources = await readSources(this.workspace, paths);
|
||||||
|
for (const path of paths) this.acceptCard(state, path, sources.get(path)!, previous.get(path));
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
state.cardsError = errorMessage(error);
|
||||||
|
}
|
||||||
|
await Promise.all([this.readHiddenCatalog(state), this.readHiddenLabels(state), this.readHiddenDeleted(state)]);
|
||||||
|
this.check();
|
||||||
|
if (revision !== this.revision) return;
|
||||||
|
this.hidden = state;
|
||||||
|
this.publishHidden();
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* Read only the changed files of `.runestone/pm/` again, for example after a watcher event.
|
||||||
|
* Paths outside `.runestone/pm/` change nothing. A change of a folder, of the storage markers, or an unknown change
|
||||||
|
* (`undefined`) reads everything again. The legacy mode always reads everything again.
|
||||||
|
*/
|
||||||
|
reloadPaths(paths?: readonly string[]): Promise<void> {
|
||||||
|
return this.run(() => this.reloadFor(paths));
|
||||||
|
}
|
||||||
|
private async reloadFor(paths?: readonly string[]) {
|
||||||
|
if (this.legacy || !this.hidden || !paths) return this.reload();
|
||||||
|
const relevant = [...new Set(paths)].filter((path) => path === ".runestone" || path === storageRoot || path.startsWith(storageRoot + "/"));
|
||||||
|
// A folder or the card marker can change many cards at once.
|
||||||
|
if (relevant.some((path) => [".runestone", storageRoot, cardsFolder, cardsMarker].includes(path))) return this.reload();
|
||||||
|
const cards = relevant.filter((path) => isHiddenCard(path) && path.lastIndexOf("/") === cardsFolder.length);
|
||||||
|
const files = relevant.filter((path) => [catalogPath, labelsPath, deletedCardsPath].includes(path));
|
||||||
|
// Images, drafts, backups, and the Git exclusion change no card, board, or label.
|
||||||
|
if (!cards.length && !files.length) return;
|
||||||
|
this.check();
|
||||||
|
const state = this.hidden;
|
||||||
|
++this.revision;
|
||||||
|
const work: Promise<void>[] = [];
|
||||||
|
if (cards.length) work.push((async () => {
|
||||||
|
const sources = await readSources(this.workspace, cards);
|
||||||
|
for (const path of cards) {
|
||||||
|
const result = sources.get(path)!;
|
||||||
|
// A missing file is a deleted card. The host reports another read error for it.
|
||||||
|
if (result.source === undefined && (await readOptional(this.workspace, path)) === null) {
|
||||||
|
state.cards.delete(path);
|
||||||
|
state.cardIssues.delete(path);
|
||||||
|
} else this.acceptCard(state, path, result, state.cards.get(path));
|
||||||
|
}
|
||||||
|
})());
|
||||||
|
if (relevant.includes(catalogPath)) work.push(this.readHiddenCatalog(state));
|
||||||
|
if (relevant.includes(labelsPath)) work.push(this.readHiddenLabels(state));
|
||||||
|
if (relevant.includes(deletedCardsPath)) work.push(this.readHiddenDeleted(state));
|
||||||
|
await Promise.all(work);
|
||||||
|
this.check();
|
||||||
|
if (this.hidden === state) this.publishHidden();
|
||||||
|
}
|
||||||
|
private acceptCard(state: HiddenState, path: string, result: { source?: string; error?: string }, cached?: Task) {
|
||||||
|
try {
|
||||||
|
if (result.error || result.source === undefined) throw new Error(result.error ?? message("The card is unavailable."));
|
||||||
|
state.cards.set(path, cached?.source === result.source ? cached : parseCard(path, result.source));
|
||||||
|
state.cardIssues.delete(path);
|
||||||
|
} catch (error) {
|
||||||
|
state.cards.delete(path);
|
||||||
|
state.cardIssues.set(path, errorMessage(error));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
private async readHiddenCatalog(state: HiddenState) {
|
||||||
|
try {
|
||||||
|
const catalog = await readCatalog(this.workspace);
|
||||||
|
state.catalog = { source: catalog.source, boards: managedDocuments(catalog.value, catalog.source ?? ""), error: "" };
|
||||||
|
} catch (error) {
|
||||||
|
// Do not expose boards as writable when hidden storage cannot be read.
|
||||||
|
state.catalog = { source: null, boards: [], error: errorMessage(error) };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
private async readHiddenLabels(state: HiddenState) {
|
||||||
|
try { state.labels = { snapshot: await this.labels.read(), error: "" }; }
|
||||||
|
catch (error) { state.labels = { error: errorMessage(error) }; }
|
||||||
|
}
|
||||||
|
private async readHiddenDeleted(state: HiddenState) {
|
||||||
|
try { state.deleted = { ids: new Set((await readDeletedCards(this.workspace)).ids), error: "" }; }
|
||||||
|
catch (error) { state.deleted = { ids: new Set(), error: errorMessage(error) }; }
|
||||||
|
}
|
||||||
|
/** Make the public fields from the hidden files. One invalid card file hides all cards, as in the legacy mode. */
|
||||||
|
private publishHidden() {
|
||||||
|
const state = this.hidden!;
|
||||||
|
const issues: string[] = [...[...state.cardIssues].map(([path, issue]) => fileIssue(path, issue))];
|
||||||
|
if (state.cardsError) issues.push(format(message("Hidden cards: {error}"), { error: state.cardsError }));
|
||||||
|
if (state.catalog.error) issues.push(format(message("Hidden Project Management storage: {error}"), { error: state.catalog.error }));
|
||||||
|
if (state.labels.error) issues.push(format(message("Saved labels: {error}"), { error: state.labels.error }));
|
||||||
|
if (state.deleted.error) issues.push(format(message("Deleted cards: {error}"), { error: state.deleted.error }));
|
||||||
|
this.labels.load(state.labels.snapshot, state.labels.error);
|
||||||
|
const blocked = !!(state.cardsError || state.cardIssues.size || state.deleted.error);
|
||||||
|
this.tasks = blocked ? [] : [...state.cards.values()]
|
||||||
|
.filter((task) => !state.deleted.ids.has(task.id))
|
||||||
|
.sort((a, b) => a.title.localeCompare(b.title));
|
||||||
|
this.boards = [...state.catalog.boards].sort((a, b) => a.name.localeCompare(b.name));
|
||||||
|
this.legacyBoards = [];
|
||||||
|
if (this.board.reference) {
|
||||||
|
this.board.load(this.boards.find((board) => board.id === this.board.reference!.id));
|
||||||
|
if (!this.board.available)
|
||||||
|
issues.push(message("This board is missing, invalid, or duplicated. Task notes remain available in All tasks."));
|
||||||
|
}
|
||||||
|
this.issues = issues;
|
||||||
|
workspaceTasks.set(this.workspace, this.tasks);
|
||||||
|
this.loaded = true;
|
||||||
|
}
|
||||||
|
private async reloadLegacy(): Promise<void> {
|
||||||
|
this.check();
|
||||||
|
const revision = ++this.revision;
|
||||||
|
const tasks: Task[] = [],
|
||||||
|
issues: string[] = [];
|
||||||
|
const boards: BoardDocument[] = [];
|
||||||
|
const previous = new Map(this.tasks.map((task) => [task.path, task]));
|
||||||
|
const paths = await markdownPaths(this.workspace, () => this.check());
|
||||||
|
const sources = await readSources(this.workspace, paths);
|
||||||
|
const documents = await mapConcurrent(paths, async (path) => {
|
||||||
|
this.check();
|
||||||
|
try {
|
||||||
|
const result = sources.get(path)!;
|
||||||
|
if (result.error || result.source === undefined) throw new Error(result.error ?? message("The file is unavailable."));
|
||||||
|
const source = result.source;
|
||||||
|
const cached = previous.get(path);
|
||||||
|
if (cached?.source === source) return { task: cached };
|
||||||
|
const board = boardDocument(source, path);
|
||||||
|
return board ? { board } : { task: readTask(path, source) };
|
||||||
|
} catch (error) {
|
||||||
|
return { issue: fileIssue(path, errorMessage(error)) };
|
||||||
|
}
|
||||||
|
});
|
||||||
|
for (const document of documents) {
|
||||||
|
if (document.board) boards.push(document.board);
|
||||||
|
if (document.task) tasks.push(document.task);
|
||||||
|
if (document.issue) issues.push(document.issue);
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const hidden = await readCards(this.workspace, previous);
|
||||||
|
issues.push(...hidden.issues);
|
||||||
|
if (hidden.issues.length) tasks.length = 0;
|
||||||
|
for (const card of hidden.tasks) {
|
||||||
|
const originals = tasks.filter((task) => task.id === card.id);
|
||||||
|
const origin = originals.length ? cardOrigin(card.source) : undefined;
|
||||||
|
for (const original of originals) {
|
||||||
|
if (
|
||||||
|
origin?.path === original.path &&
|
||||||
|
origin.source === original.source
|
||||||
|
)
|
||||||
|
tasks.splice(tasks.indexOf(original), 1);
|
||||||
|
else
|
||||||
|
issues.push(format(
|
||||||
|
message("The original card differs from hidden storage: {path}. Preserve both versions."),
|
||||||
|
{ path: original.path },
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
tasks.push(...hidden.tasks);
|
||||||
|
} catch (error) {
|
||||||
|
issues.push(format(message("Hidden cards: {error}"), { error: errorMessage(error) }));
|
||||||
|
// Block legacy edits when the hidden store cannot be checked for migrated IDs.
|
||||||
|
tasks.length = 0;
|
||||||
|
}
|
||||||
|
let legacyBoards = [...boards];
|
||||||
|
try {
|
||||||
|
const catalog = await readCatalog(this.workspace);
|
||||||
|
for (let index = boards.length - 1; index >= 0; index--)
|
||||||
|
if (catalog.value.deletedBoardIds?.includes(boards[index].id))
|
||||||
|
boards.splice(index, 1);
|
||||||
|
legacyBoards = [...boards];
|
||||||
|
for (const managed of catalog.value.boards) {
|
||||||
|
const matches = boards.filter((board) => board.id === managed.value.id);
|
||||||
|
for (const board of matches) {
|
||||||
|
if (
|
||||||
|
managed.original?.path === board.path &&
|
||||||
|
managed.original.source === board.source
|
||||||
|
)
|
||||||
|
boards.splice(boards.indexOf(board), 1);
|
||||||
|
else
|
||||||
|
issues.push(format(
|
||||||
|
message("The legacy board differs from hidden storage: {path}. Preserve both versions before cleanup."),
|
||||||
|
{ path: board.path },
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
boards.push(...managedDocuments(catalog.value, catalog.source ?? ""));
|
||||||
|
} catch (error) {
|
||||||
|
issues.push(format(message("Hidden Project Management storage: {error}"), { error: errorMessage(error) }));
|
||||||
|
// Do not expose legacy boards as writable when hidden storage cannot be read.
|
||||||
|
boards.length = 0;
|
||||||
|
}
|
||||||
|
let labels: LabelSnapshot | undefined,
|
||||||
|
labelError = "";
|
||||||
|
try {
|
||||||
|
labels = await this.labels.read();
|
||||||
|
} catch (error) {
|
||||||
|
labelError = errorMessage(error);
|
||||||
|
issues.push(format(message("Saved labels: {error}"), { error: labelError }));
|
||||||
|
}
|
||||||
|
this.check();
|
||||||
|
if (revision !== this.revision) return;
|
||||||
|
this.labels.load(labels, labelError);
|
||||||
|
this.legacyBoards = legacyBoards;
|
||||||
|
const counts = new Map<string, number>();
|
||||||
|
for (const task of tasks)
|
||||||
|
counts.set(task.id, (counts.get(task.id) ?? 0) + 1);
|
||||||
|
for (const [id, count] of counts)
|
||||||
|
if (count > 1) issues.push(duplicateTaskIssue(id));
|
||||||
|
let deletedIds = new Set<string>();
|
||||||
|
try { deletedIds = new Set((await readDeletedCards(this.workspace)).ids); }
|
||||||
|
catch (error) {
|
||||||
|
issues.push(format(message("Deleted cards: {error}"), { error: errorMessage(error) }));
|
||||||
|
tasks.length = 0;
|
||||||
|
}
|
||||||
|
this.check();
|
||||||
|
if (revision !== this.revision) return;
|
||||||
|
this.tasks = tasks
|
||||||
|
.filter((task) => counts.get(task.id) === 1 && !deletedIds.has(task.id))
|
||||||
|
.sort((a, b) => a.title.localeCompare(b.title));
|
||||||
|
const boardCounts = new Map<string, number>();
|
||||||
|
for (const board of boards)
|
||||||
|
boardCounts.set(board.id, (boardCounts.get(board.id) ?? 0) + 1);
|
||||||
|
for (const [id, count] of boardCounts)
|
||||||
|
if (count > 1)
|
||||||
|
issues.push(format(message("Duplicate board ID {id}: resolve the copied boards before editing them."), { id }));
|
||||||
|
this.boards = boards
|
||||||
|
.filter((board) => boardCounts.get(board.id) === 1)
|
||||||
|
.sort((a, b) => a.name.localeCompare(b.name));
|
||||||
|
if (this.board.reference) {
|
||||||
|
this.board.load(
|
||||||
|
this.boards.find((board) => board.id === this.board.reference!.id),
|
||||||
|
);
|
||||||
|
if (!this.board.available)
|
||||||
|
issues.push(message("This board is missing, invalid, or duplicated. Task notes remain available in All tasks."));
|
||||||
|
}
|
||||||
|
this.issues = issues;
|
||||||
|
workspaceTasks.set(this.workspace, this.tasks);
|
||||||
|
this.loaded = true;
|
||||||
|
}
|
||||||
|
private run<T>(action: () => Promise<T>): Promise<T> {
|
||||||
|
const result = this.queue.then(() => {
|
||||||
|
this.check();
|
||||||
|
return action();
|
||||||
|
});
|
||||||
|
this.queue = result.catch(() => {});
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
save(
|
||||||
|
task: Task,
|
||||||
|
patch: Partial<TaskFields> & { body?: string },
|
||||||
|
applyListStatus = false,
|
||||||
|
): Promise<void> {
|
||||||
|
return this.run(() => this.saveTask(task, patch, applyListStatus));
|
||||||
|
}
|
||||||
|
deleteCard(task: Task): Promise<void> {
|
||||||
|
return this.run(async () => {
|
||||||
|
await this.reloadFor([task.path]);
|
||||||
|
const current = this.tasks.find(item => item.id === task.id && item.path === task.path);
|
||||||
|
if (!current || current.source !== task.source)
|
||||||
|
throw new Error(message("The card changed or is unavailable. Refresh before deleting it."));
|
||||||
|
await recordCardDeletion(this.workspace, task.id);
|
||||||
|
await this.reloadFor([deletedCardsPath]);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
unlinkIncoming(targetId: string, sources: Task[]): Promise<void> {
|
||||||
|
if (!sources.length) return Promise.resolve();
|
||||||
|
return this.run(async () => {
|
||||||
|
await this.reloadFor(sources.map(source => source.path));
|
||||||
|
const current = sources.map(source => {
|
||||||
|
const found = this.tasks.find(task => task.id === source.id && task.path === source.path);
|
||||||
|
if (found && !found.links?.some(link => link.taskId === targetId)) return undefined;
|
||||||
|
if (!found || found.source !== source.source)
|
||||||
|
throw new Error(message("A linked card changed. Refresh before removing its link."));
|
||||||
|
return found;
|
||||||
|
});
|
||||||
|
for (const source of current) {
|
||||||
|
if (!source) continue;
|
||||||
|
await this.saveTask(source, { links: source.links?.filter(link => link.taskId !== targetId) }, false, undefined, true);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
private async saveTask(
|
||||||
|
task: Task,
|
||||||
|
patch: Partial<TaskFields> & { body?: string },
|
||||||
|
applyListStatus: boolean,
|
||||||
|
beforeId?: string | null,
|
||||||
|
reloaded = false,
|
||||||
|
placementBoardId = this.board.reference?.id,
|
||||||
|
): Promise<void> {
|
||||||
|
if (!reloaded) await this.reloadFor([task.path]);
|
||||||
|
const current = this.tasks.find(
|
||||||
|
(item) => item.id === task.id && item.path === task.path,
|
||||||
|
);
|
||||||
|
if (!current || current.source !== task.source)
|
||||||
|
throw new Error(message("The task changed or has a duplicate ID. Cancel, refresh, and review the note before saving."));
|
||||||
|
const next = { ...patch };
|
||||||
|
if (Object.hasOwn(next, "listId")) {
|
||||||
|
if (this.board.archived)
|
||||||
|
throw new Error(message("Restore this board before moving cards."));
|
||||||
|
const listId = next.listId ?? null;
|
||||||
|
const list = this.board.value.lists.find((list) => list.id === listId);
|
||||||
|
if (listId !== null && !list)
|
||||||
|
throw new Error(message("This list no longer exists. Refresh the board."));
|
||||||
|
const previousList = this.board.listFor(task);
|
||||||
|
if (applyListStatus && listId !== (previousList?.id ?? null)) {
|
||||||
|
if (list?.status) next.status = list.status;
|
||||||
|
else if (previousList?.status === "done" && task.status === "done") next.status = "todo";
|
||||||
|
}
|
||||||
|
const id = this.board.reference?.id;
|
||||||
|
if (id) {
|
||||||
|
if (!this.board.available)
|
||||||
|
throw new Error(message("The board is unavailable. Reopen it before saving."));
|
||||||
|
const placement = { ...task.placements?.[id], listId };
|
||||||
|
if (
|
||||||
|
listId !== (this.board.listFor(task)?.id ?? null) ||
|
||||||
|
beforeId !== undefined
|
||||||
|
)
|
||||||
|
placement.order = this.position(task, listId, beforeId);
|
||||||
|
next.placements = { ...task.placements, [id]: placement };
|
||||||
|
} else if (
|
||||||
|
beforeId !== undefined ||
|
||||||
|
(list?.status && task.status !== list.status)
|
||||||
|
) {
|
||||||
|
next.order = this.position(task, listId, beforeId);
|
||||||
|
}
|
||||||
|
next.listId = undefined;
|
||||||
|
}
|
||||||
|
if (next.status !== undefined && next.status !== task.status) {
|
||||||
|
const placements = { ...(next.placements ?? task.placements) };
|
||||||
|
for (const board of this.boards) {
|
||||||
|
if (board.id === placementBoardId) continue;
|
||||||
|
const placement = placements[board.id];
|
||||||
|
const listId = board.value.defaults[next.status];
|
||||||
|
if (
|
||||||
|
!placement ||
|
||||||
|
listId === null ||
|
||||||
|
placement.listId === listId ||
|
||||||
|
!board.value.lists.some((list) => list.id === listId)
|
||||||
|
)
|
||||||
|
continue;
|
||||||
|
const cards = this.tasks
|
||||||
|
.filter(
|
||||||
|
(card) =>
|
||||||
|
card.id !== task.id &&
|
||||||
|
card.archived === task.archived &&
|
||||||
|
card.placements?.[board.id]?.listId === listId,
|
||||||
|
)
|
||||||
|
.sort((a, b) => compareCards(a, b, board.id));
|
||||||
|
const last = cards.at(-1);
|
||||||
|
placements[board.id] = {
|
||||||
|
...placement,
|
||||||
|
listId,
|
||||||
|
order: orderBetween(last ? cardOrder(last, board.id) : undefined),
|
||||||
|
};
|
||||||
|
next.placements = placements;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const source = editTask(task, next);
|
||||||
|
await saveDocument(this.workspace, task.path, source, task.source);
|
||||||
|
this.accept(task.path, source);
|
||||||
|
}
|
||||||
|
private accept(path: string, source: string) {
|
||||||
|
++this.revision;
|
||||||
|
if (this.hidden && isHiddenCard(path)) {
|
||||||
|
this.hidden.cards.set(path, readTask(path, source)!);
|
||||||
|
this.hidden.cardIssues.delete(path);
|
||||||
|
this.publishHidden();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
this.tasks = [
|
||||||
|
...this.tasks.filter((task) => task.path !== path),
|
||||||
|
readTask(path, source)!,
|
||||||
|
].sort((a, b) => a.title.localeCompare(b.title));
|
||||||
|
workspaceTasks.set(this.workspace, this.tasks);
|
||||||
|
}
|
||||||
|
cardsInList(listId: string | null, archived = false): Task[] {
|
||||||
|
return this.scopedTasks
|
||||||
|
.filter(
|
||||||
|
(task) =>
|
||||||
|
task.archived === archived &&
|
||||||
|
(this.board.listFor(task)?.id ?? null) === listId,
|
||||||
|
)
|
||||||
|
.sort((a, b) => compareCards(a, b, this.board.reference?.id));
|
||||||
|
}
|
||||||
|
archiveList(listId: string): Promise<void> {
|
||||||
|
return this.run(async () => {
|
||||||
|
await this.reloadFor(this.cardsInList(listId).map(task => task.path));
|
||||||
|
if (!this.board.editable || !this.board.value.lists.some((list) => list.id === listId))
|
||||||
|
throw new Error(message("The list is unavailable. Refresh the board."));
|
||||||
|
if (this.issues.length)
|
||||||
|
throw new Error(format(message("Resolve workspace issues before archiving cards: {issues}"), { issues: this.issues.join(" ") }));
|
||||||
|
for (const task of this.cardsInList(listId)) {
|
||||||
|
const source = editTask(task, { archived: true });
|
||||||
|
await saveDocument(this.workspace, task.path, source, task.source);
|
||||||
|
this.accept(task.path, source);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
private position(
|
||||||
|
task: Task | undefined,
|
||||||
|
listId: string | null,
|
||||||
|
beforeId?: string | null,
|
||||||
|
): string {
|
||||||
|
const cards = this.cardsInList(listId, task?.archived).filter(
|
||||||
|
(card) => card.id !== task?.id,
|
||||||
|
);
|
||||||
|
const index =
|
||||||
|
beforeId == null
|
||||||
|
? cards.length
|
||||||
|
: cards.findIndex((card) => card.id === beforeId);
|
||||||
|
if (index < 0) throw new Error(message("The target card moved. Refresh the board."));
|
||||||
|
const id = this.board.reference?.id;
|
||||||
|
return orderBetween(
|
||||||
|
index > 0 ? cardOrder(cards[index - 1], id) : undefined,
|
||||||
|
index < cards.length ? cardOrder(cards[index], id) : undefined,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
async createOrLink(title: string, fields: TaskFields): Promise<void> {
|
||||||
|
const path = title.trim().replaceAll("\\", "/").replace(/^\.\//, "");
|
||||||
|
if (!/\.(md|markdown|mdown)$/i.test(path)) return this.create(title, fields, "");
|
||||||
|
if (/^(?:[a-z]+:|\/)/i.test(path) || path.split("/").some(part => !part || part === "." || part === ".."))
|
||||||
|
throw new Error(message("Use a relative Markdown path inside this workspace."));
|
||||||
|
const added = await this.adopt(path);
|
||||||
|
const task = this.tasks.find(item => item.id === added.id && item.path === added.path);
|
||||||
|
if (!task) throw new Error(message("The linked card is unavailable. Refresh the board."));
|
||||||
|
if (this.board.reference) await this.moveTask(task, fields.listId ?? null);
|
||||||
|
}
|
||||||
|
create(title: string, fields: TaskFields, body: string, destinationId?: string): Promise<void> {
|
||||||
|
return this.run(async () => {
|
||||||
|
if (!this.workspace.create)
|
||||||
|
throw new Error(message("This RuneStone version cannot create plugin notes. Add an existing note or install the host bridge."));
|
||||||
|
if (!this.loaded) await this.reload();
|
||||||
|
++this.revision;
|
||||||
|
if (destinationId !== undefined) await this.reloadFor([catalogPath]);
|
||||||
|
const destination = destinationId === undefined ? undefined : this.boards.find(board => board.id === destinationId && !board.archived);
|
||||||
|
if (destinationId !== undefined && !destination) throw new Error(message("Choose an available, active board for this card."));
|
||||||
|
const id = destination?.id ?? this.board.reference?.id;
|
||||||
|
if (id && !destination && !this.board.available)
|
||||||
|
throw new Error(message("The board is unavailable. Reopen it before saving."));
|
||||||
|
// Named-board creation reads the current board without a workspace scan.
|
||||||
|
await this.board.reload();
|
||||||
|
if (this.board.archived)
|
||||||
|
throw new Error(message("Restore this board before adding cards."));
|
||||||
|
const targetBoard = destination?.value ?? this.board.value;
|
||||||
|
const listId =
|
||||||
|
fields.listId === undefined
|
||||||
|
? targetBoard.defaults[fields.status]
|
||||||
|
: fields.listId;
|
||||||
|
if (
|
||||||
|
id &&
|
||||||
|
listId !== null &&
|
||||||
|
!targetBoard.lists.some((list) => list.id === listId)
|
||||||
|
)
|
||||||
|
throw new Error(message("This list no longer exists. Refresh the board."));
|
||||||
|
const lastGlobalCard = this.tasks
|
||||||
|
.filter(
|
||||||
|
(task) =>
|
||||||
|
task.status === fields.status && task.archived === fields.archived,
|
||||||
|
)
|
||||||
|
.sort((a, b) => compareCards(a, b))
|
||||||
|
.at(-1);
|
||||||
|
const lastDestinationCard = destination && id
|
||||||
|
? this.tasks.filter(task => !task.archived && task.placements?.[id]?.listId === listId)
|
||||||
|
.sort((a, b) => compareCards(a, b, id)).at(-1)
|
||||||
|
: undefined;
|
||||||
|
const placementOrder = destination && id
|
||||||
|
? orderBetween(lastDestinationCard ? cardOrder(lastDestinationCard, id) : undefined)
|
||||||
|
: this.position(undefined, listId);
|
||||||
|
const note = await createCard(
|
||||||
|
this.workspace,
|
||||||
|
title,
|
||||||
|
{
|
||||||
|
...fields,
|
||||||
|
order:
|
||||||
|
fields.order ??
|
||||||
|
orderBetween(
|
||||||
|
lastGlobalCard ? cardOrder(lastGlobalCard) : undefined,
|
||||||
|
),
|
||||||
|
listId: undefined,
|
||||||
|
...(id
|
||||||
|
? {
|
||||||
|
placements: {
|
||||||
|
[id]: { listId, order: placementOrder },
|
||||||
|
},
|
||||||
|
}
|
||||||
|
: {}),
|
||||||
|
},
|
||||||
|
body,
|
||||||
|
);
|
||||||
|
this.accept(note.path, note.source);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
openSubtask(parentId: string, subtaskId: string): Promise<Task> {
|
||||||
|
return this.run(async () => {
|
||||||
|
await this.reloadFor([cardPath(parentId)]);
|
||||||
|
const parent = this.tasks.find(task => task.id === parentId);
|
||||||
|
const item = parent?.subtasks?.find(item => item.id === subtaskId);
|
||||||
|
if (!parent || !item) throw new Error(message("The subtask is unavailable. Refresh the board."));
|
||||||
|
if (item.taskId) {
|
||||||
|
const target = this.tasks.find(task => task.id === item.taskId);
|
||||||
|
if (!target) throw new Error(message("The subtask card is unavailable. Refresh the board."));
|
||||||
|
return target;
|
||||||
|
}
|
||||||
|
// A stable ID lets a retry recover after the child saves but the parent fails.
|
||||||
|
const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(JSON.stringify(["subtask", parent.id, item.id])));
|
||||||
|
const id = Array.from(new Uint8Array(digest), byte => byte.toString(16).padStart(2, "0")).join("");
|
||||||
|
let target = this.tasks.find(task => task.id === id);
|
||||||
|
if (!target) {
|
||||||
|
const placements = Object.fromEntries(Object.keys(parent.placements ?? {}).map(boardId => {
|
||||||
|
const board = this.boards.find(board => board.id === boardId);
|
||||||
|
return [boardId, { listId: board?.value.defaults[item.done ? "done" : "todo"] ?? null }];
|
||||||
|
}));
|
||||||
|
const note = await createCard(this.workspace, item.title, {
|
||||||
|
status: item.done ? "done" : "todo", tags: [], sessions: [], archived: false, placements,
|
||||||
|
}, "", id);
|
||||||
|
this.accept(note.path, note.source);
|
||||||
|
target = this.tasks.find(task => task.path === cardPath(id));
|
||||||
|
}
|
||||||
|
await this.saveTask(parent, { subtasks: parent.subtasks!.map(subtask => subtask.id === subtaskId ? { ...subtask, taskId: id } : subtask) }, false);
|
||||||
|
return target!;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
moveTask(
|
||||||
|
task: Task,
|
||||||
|
listId: string | null,
|
||||||
|
beforeId?: string | null,
|
||||||
|
): Promise<void> {
|
||||||
|
return this.run(() => this.saveTask(task, { listId }, true, beforeId));
|
||||||
|
}
|
||||||
|
removeFromBoard(task: Task): Promise<void> {
|
||||||
|
const id = this.board.reference?.id;
|
||||||
|
if (!id)
|
||||||
|
return Promise.reject(new Error(message("Open a board before removing a card.")));
|
||||||
|
const placements = { ...task.placements };
|
||||||
|
delete placements[id];
|
||||||
|
return this.save(task, { placements });
|
||||||
|
}
|
||||||
|
saveToBoard(task: Task, destinationId: string, listId: string | null, patch: Partial<TaskFields> & { body?: string }): Promise<void> {
|
||||||
|
return this.run(async () => {
|
||||||
|
await this.reloadFor([task.path]);
|
||||||
|
const destination = this.boards.find(board => board.id === destinationId);
|
||||||
|
if (!destination || destination.archived || (listId !== null && !destination.value.lists.some(list => list.id === listId)))
|
||||||
|
throw new Error(message("The destination board or list is unavailable. Refresh the board."));
|
||||||
|
if (this.board.reference && (!this.board.available || this.board.archived)) throw new Error(message("Open an available, active board before moving a card."));
|
||||||
|
const placements = { ...task.placements };
|
||||||
|
if (this.board.reference) delete placements[this.board.reference.id];
|
||||||
|
const last = this.tasks.filter(item => item.id !== task.id && item.placements?.[destinationId]?.listId === listId).sort((a, b) => compareCards(a, b, destinationId)).at(-1);
|
||||||
|
placements[destinationId] = { listId, order: orderBetween(last ? cardOrder(last, destinationId) : undefined) };
|
||||||
|
const { listId: ignoredList, status: ignoredStatus, ...details } = patch;
|
||||||
|
const destinationList = destination.value.lists.find(list => list.id === listId);
|
||||||
|
const previousList = destination.value.lists.find(list => list.id === task.placements?.[destinationId]?.listId);
|
||||||
|
const status = destinationList?.status ?? (previousList?.status === "done" && task.status === "done" ? "todo" : task.status);
|
||||||
|
await this.saveTask(task, { ...details, status, placements }, false, undefined, true, destinationId);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
transferTask(
|
||||||
|
task: Task,
|
||||||
|
destinationId: string,
|
||||||
|
listId: string | null,
|
||||||
|
): Promise<void> {
|
||||||
|
return this.run(async () => {
|
||||||
|
await this.reloadFor([task.path]);
|
||||||
|
const sourceId = this.board.reference?.id;
|
||||||
|
if (!sourceId || !this.board.available || this.board.archived)
|
||||||
|
throw new Error(message("Open an available, active board before moving a card."));
|
||||||
|
const current = this.tasks.find(
|
||||||
|
(item) => item.id === task.id && item.path === task.path,
|
||||||
|
);
|
||||||
|
if (!current || current.source !== task.source)
|
||||||
|
throw new Error(message("The card changed. Cancel, refresh, and review it before moving."));
|
||||||
|
if (!Object.hasOwn(current.placements ?? {}, sourceId))
|
||||||
|
throw new Error(message("This card no longer belongs to the source board."));
|
||||||
|
if (sourceId === destinationId)
|
||||||
|
throw new Error(message("Choose a different destination board."));
|
||||||
|
const destination = this.boards.find((board) => board.id === destinationId);
|
||||||
|
if (!destination || destination.archived)
|
||||||
|
throw new Error(message("The destination board is unavailable or archived. Choose another board."));
|
||||||
|
if (listId !== null && !destination.value.lists.some((list) => list.id === listId))
|
||||||
|
throw new Error(message("The destination list no longer exists. Choose another list."));
|
||||||
|
const last = this.tasks
|
||||||
|
.filter((card) => card.id !== task.id && card.archived === task.archived &&
|
||||||
|
Object.hasOwn(card.placements ?? {}, destinationId) &&
|
||||||
|
(destination.value.lists.some((list) => list.id === card.placements![destinationId].listId)
|
||||||
|
? card.placements![destinationId].listId : null) === listId)
|
||||||
|
.sort((a, b) => compareCards(a, b, destinationId)).at(-1);
|
||||||
|
const placements = { ...current.placements };
|
||||||
|
delete placements[sourceId];
|
||||||
|
placements[destinationId] = {
|
||||||
|
...placements[destinationId],
|
||||||
|
listId,
|
||||||
|
order: orderBetween(last ? cardOrder(last, destinationId) : undefined),
|
||||||
|
};
|
||||||
|
// One guarded write changes membership without synchronizing other boards.
|
||||||
|
const source = editTask(current, { placements });
|
||||||
|
await saveDocument(this.workspace, current.path, source, current.source);
|
||||||
|
this.accept(current.path, source);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
changeBoard(change: () => Promise<void>, reload = true): Promise<void> {
|
||||||
|
return this.run(async () => {
|
||||||
|
await change();
|
||||||
|
// The hidden mode reads only the catalog again. The saved board then keeps the current catalog text.
|
||||||
|
if (this.hidden) await this.reloadFor([catalogPath]);
|
||||||
|
else if (reload) await this.reload();
|
||||||
|
else this.boards = this.boards.map(board => board.id === this.board.reference?.id
|
||||||
|
? { ...board, value: this.board.value } : board);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
saveLabels(
|
||||||
|
labels: SavedLabel[],
|
||||||
|
expected: string | null | undefined,
|
||||||
|
): Promise<void> {
|
||||||
|
return this.run(async () => {
|
||||||
|
this.labels.checkSave(labels, expected);
|
||||||
|
const removed = new Set(parseLabels(expected ?? null).labels
|
||||||
|
.filter((label) => !labels.some((next) => next.id === label.id)).map((label) => label.id));
|
||||||
|
if (removed.size) {
|
||||||
|
await this.reloadFor([labelsPath]);
|
||||||
|
if (this.labels.source !== expected)
|
||||||
|
throw new Error(message("Saved labels changed. Refresh before deleting labels."));
|
||||||
|
if (this.issues.length)
|
||||||
|
throw new Error(format(message("Resolve workspace issues before deleting labels: {issues}"), { issues: this.issues.join(" ") }));
|
||||||
|
// Keep definitions until every guarded card write succeeds, so a retry is safe.
|
||||||
|
for (const task of this.tasks)
|
||||||
|
if (task.labels?.some((id) => removed.has(id))) {
|
||||||
|
const source = editTask(task, { labels: task.labels.filter((id) => !removed.has(id)) });
|
||||||
|
await saveDocument(this.workspace, task.path, source, task.source);
|
||||||
|
this.accept(task.path, source);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
await this.labels.save(labels, expected, true);
|
||||||
|
++this.revision;
|
||||||
|
if (this.hidden) await this.reloadFor([labelsPath]);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
createBoard(name: string) {
|
||||||
|
return this.run(async () => {
|
||||||
|
const reference = await createBoard(this.workspace, name);
|
||||||
|
await this.reloadFor([catalogPath]);
|
||||||
|
return reference;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
migrateStorage(cardIds: string[] = []) {
|
||||||
|
return this.run(async () => {
|
||||||
|
await this.reload();
|
||||||
|
if (this.issues.length)
|
||||||
|
throw new Error(format(message("Resolve the workspace issues before migration: {issues}"), { issues: this.issues.join(" ") }));
|
||||||
|
const selected = cardIds.map((id) => {
|
||||||
|
const task = this.tasks.find((task) => task.id === id);
|
||||||
|
if (!task)
|
||||||
|
throw new Error(message("A selected card is unavailable. Refresh before migration."));
|
||||||
|
return task;
|
||||||
|
});
|
||||||
|
const result = await migrateStorage(
|
||||||
|
this.workspace,
|
||||||
|
this.legacyBoards,
|
||||||
|
selected,
|
||||||
|
);
|
||||||
|
await this.reload();
|
||||||
|
return result;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
renameBoard(
|
||||||
|
name: string,
|
||||||
|
rename?: (document: BoardReference, name: string) => Promise<string>,
|
||||||
|
): Promise<void> {
|
||||||
|
return this.run(async () => {
|
||||||
|
await this.reloadFor([catalogPath]);
|
||||||
|
if (!this.board.editable)
|
||||||
|
throw new Error(message("Open an available board before renaming it."));
|
||||||
|
const reference = this.board.reference!;
|
||||||
|
if (isManagedBoard(reference.path)) {
|
||||||
|
await this.board.manage({ name });
|
||||||
|
await this.reloadFor([catalogPath]);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!rename) throw new Error(message("Migrate this board before renaming it."));
|
||||||
|
const path = await rename({ ...reference }, name.trim());
|
||||||
|
reference.path = path;
|
||||||
|
await this.reload();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* Add a note to Project Management and return its card. The legacy mode adds the properties to the note itself.
|
||||||
|
* The hidden mode leaves the note unchanged: it copies a plain note into a new private card, and it migrates a
|
||||||
|
* legacy task note with a backup. The card then gets a placement on the open board.
|
||||||
|
*/
|
||||||
|
adopt(path: string): Promise<Task> {
|
||||||
|
if (!this.legacy) return this.run(() => this.adoptHidden(path));
|
||||||
|
return this.run(async () => {
|
||||||
|
if (!/\.(md|markdown|mdown)$/i.test(path))
|
||||||
|
throw new Error(message("Choose a Markdown note from this workspace."));
|
||||||
|
await this.reload();
|
||||||
|
const id = this.board.reference?.id;
|
||||||
|
if (id && !this.board.available)
|
||||||
|
throw new Error(message("The board is unavailable. Reopen it before adding a note."));
|
||||||
|
if (this.board.archived)
|
||||||
|
throw new Error(message("Restore this board before adding cards."));
|
||||||
|
const source = await this.workspace.read(path);
|
||||||
|
let next = adoptNote(path, source);
|
||||||
|
const task = readTask(path, next)!;
|
||||||
|
if (
|
||||||
|
this.tasks.some(
|
||||||
|
(other) => other.id === task.id && other.path !== path,
|
||||||
|
) ||
|
||||||
|
this.issues.includes(duplicateTaskIssue(task.id))
|
||||||
|
)
|
||||||
|
throw new Error(message("Resolve this task's duplicate ID before adding it."));
|
||||||
|
if (id && !Object.hasOwn(task.placements ?? {}, id))
|
||||||
|
next = editTask(task, {
|
||||||
|
placements: {
|
||||||
|
...task.placements,
|
||||||
|
[id]: {
|
||||||
|
listId: this.board.value.defaults[task.status],
|
||||||
|
order: this.position(
|
||||||
|
task,
|
||||||
|
this.board.value.defaults[task.status],
|
||||||
|
),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
if (next !== source)
|
||||||
|
await saveDocument(this.workspace, path, next, source);
|
||||||
|
await this.reload();
|
||||||
|
const added = this.tasks.find(item => item.path === path);
|
||||||
|
if (!added) throw new Error(message("The linked card is unavailable. Refresh the board."));
|
||||||
|
return added;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
private async adoptHidden(path: string): Promise<Task> {
|
||||||
|
if (!/\.(md|markdown|mdown)$/i.test(path))
|
||||||
|
throw new Error(message("Choose a Markdown note from this workspace."));
|
||||||
|
const id = this.board.reference?.id;
|
||||||
|
if (id && !this.board.available)
|
||||||
|
throw new Error(message("The board is unavailable. Reopen it before adding a note."));
|
||||||
|
if (this.board.archived)
|
||||||
|
throw new Error(message("Restore this board before adding cards."));
|
||||||
|
let card: Task | undefined;
|
||||||
|
if (isHiddenCard(path)) {
|
||||||
|
await this.reloadFor([path]);
|
||||||
|
card = this.tasks.find(task => task.path === path);
|
||||||
|
if (!card) throw new Error(message("The linked card is unavailable. Refresh the board."));
|
||||||
|
} else {
|
||||||
|
const source = await this.workspace.read(path);
|
||||||
|
const note = readTask(path, source);
|
||||||
|
if (note) {
|
||||||
|
// A task note of the legacy format keeps its ID. The migration copies it with a backup.
|
||||||
|
await this.reloadFor([cardPath(note.id)]);
|
||||||
|
card = this.tasks.find(task => task.id === note.id);
|
||||||
|
if (!card) {
|
||||||
|
await migrateCards(this.workspace, [note]);
|
||||||
|
await this.reloadFor([cardPath(note.id)]);
|
||||||
|
card = this.tasks.find(task => task.id === note.id);
|
||||||
|
}
|
||||||
|
if (!card) throw new Error(message("The linked card is unavailable. Refresh the board."));
|
||||||
|
} else {
|
||||||
|
const { doc, body, match, newline } = split(source);
|
||||||
|
if (doc.has("runestone_pm"))
|
||||||
|
throw new Error(message("This document already contains Project Management data and cannot become a task."));
|
||||||
|
const cardId = crypto.randomUUID();
|
||||||
|
const last = this.tasks.filter(task => task.status === "todo" && !task.archived).sort((a, b) => compareCards(a, b)).at(-1);
|
||||||
|
doc.set("runestone_pm", {
|
||||||
|
schema: 1, id: cardId, kind: "task",
|
||||||
|
title: path.split("/").at(-1)!.replace(/\.(md|markdown|mdown)$/i, ""),
|
||||||
|
createdAt: new Date().toISOString(),
|
||||||
|
order: orderBetween(last ? cardOrder(last) : undefined),
|
||||||
|
status: "todo", tags: [], sessions: [], archived: false,
|
||||||
|
});
|
||||||
|
const copy = `${match?.[1] ?? ""}---${newline}${doc.toString({ lineWidth: 0 }).replaceAll("\n", newline)}---${newline}${body}`;
|
||||||
|
const target = cardPath(cardId);
|
||||||
|
parseCard(target, copy);
|
||||||
|
await prepareCards(this.workspace);
|
||||||
|
await saveDocument(this.workspace, target, copy, null);
|
||||||
|
this.accept(target, copy);
|
||||||
|
card = this.tasks.find(task => task.path === target)!;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (id && !Object.hasOwn(card.placements ?? {}, id)) {
|
||||||
|
const listId = this.board.value.defaults[card.status];
|
||||||
|
await this.saveTask(card, { placements: { ...card.placements, [id]: { listId, order: this.position(card, listId) } } }, false, undefined, true);
|
||||||
|
const placed = card.id;
|
||||||
|
card = this.tasks.find(task => task.id === placed)!;
|
||||||
|
}
|
||||||
|
return card;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,56 @@
|
|||||||
|
import type { BackgroundAppearance } from "./background.ts";
|
||||||
|
|
||||||
|
/** One background frame. It has the shape of `BackgroundFrame` in `src/lib/plugins/backgroundContracts.ts`. */
|
||||||
|
export interface BackgroundFrame extends BackgroundAppearance {
|
||||||
|
url: string;
|
||||||
|
blurredUrl?: string;
|
||||||
|
previous?: BackgroundAppearance & { url: string; blurredUrl?: string };
|
||||||
|
transitionMs?: number;
|
||||||
|
}
|
||||||
|
/** The part of the host background hub (`backgroundHub` in `src/lib/plugins/backgrounds.ts`) that the boards read. */
|
||||||
|
export interface PMBackgroundApi {
|
||||||
|
get(target: string): BackgroundFrame | null;
|
||||||
|
subscribe(listener: (target: string) => void): () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
function sameImage(a: BackgroundAppearance & { url: string; blurredUrl?: string }, b: BackgroundAppearance & { url: string; blurredUrl?: string }) {
|
||||||
|
return a.url === b.url && a.blurredUrl === b.blurredUrl && a.overlay === b.overlay && a.position === b.position && a.size === b.size;
|
||||||
|
}
|
||||||
|
|
||||||
|
function sameFrame(a: BackgroundFrame, b: BackgroundFrame | null | undefined) {
|
||||||
|
return !!b && sameImage(a, b) && (a.transitionMs ?? 0) === (b.transitionMs ?? 0)
|
||||||
|
&& (a.previous ? !!b.previous && sameImage(a.previous, b.previous) : !b.previous);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function watchBackground(
|
||||||
|
target: string,
|
||||||
|
api: PMBackgroundApi | undefined,
|
||||||
|
saved: () => Promise<BackgroundFrame | null>,
|
||||||
|
apply: (frame: BackgroundFrame | null) => void,
|
||||||
|
) {
|
||||||
|
let revision = 0;
|
||||||
|
let closed = false;
|
||||||
|
async function refresh() {
|
||||||
|
if (closed) return;
|
||||||
|
const current = ++revision;
|
||||||
|
try {
|
||||||
|
const frame = api?.get(target) ?? (target !== "pm-all" ? api?.get("pm-all") : null) ?? await saved();
|
||||||
|
// A shared slideshow uses the host image coordinates across every pane.
|
||||||
|
if (!closed && current === revision) apply(frame && sameFrame(frame, api?.get("app")) ? null : frame);
|
||||||
|
} catch {
|
||||||
|
if (!closed && current === revision) apply(null);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const unsubscribe = api?.subscribe(changed => {
|
||||||
|
if (changed === target || changed === "pm-all" || changed === "app") void refresh();
|
||||||
|
});
|
||||||
|
return {
|
||||||
|
refresh,
|
||||||
|
dispose() {
|
||||||
|
if (closed) return;
|
||||||
|
closed = true;
|
||||||
|
++revision;
|
||||||
|
unsubscribe?.();
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
import type { Workspace } from "./model.ts";
|
||||||
|
import { boardKey, readCatalog } from "../storage/catalog.ts";
|
||||||
|
import { boardDocument } from "../storage/board.ts";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The board that opens first in this workspace: the `pm-board:` key of a saved board, the path of a legacy Markdown board,
|
||||||
|
* or undefined for All tasks. Settings → Project Management writes `defaultBoardId` and `defaultBoardPath` of the catalog.
|
||||||
|
*/
|
||||||
|
export async function defaultBoardPath(workspace: Workspace): Promise<string | undefined> {
|
||||||
|
const snapshot = await readCatalog(workspace);
|
||||||
|
if (typeof snapshot.value.defaultBoardId !== "string") return;
|
||||||
|
const board = snapshot.value.boards.find(board => board.value.id === snapshot.value.defaultBoardId);
|
||||||
|
if (board) return board.archived ? undefined : boardKey(board.value.id);
|
||||||
|
if (snapshot.value.deletedBoardIds?.includes(snapshot.value.defaultBoardId)) return;
|
||||||
|
const path = snapshot.value.defaultBoardPath;
|
||||||
|
if (typeof path !== "string" || path.startsWith(".") || path.includes("\\") || path.split("/").some(part => !part || part === "..")) return;
|
||||||
|
try {
|
||||||
|
const legacy = boardDocument(await workspace.read(path), path);
|
||||||
|
return legacy?.id === snapshot.value.defaultBoardId && !legacy.archived ? path : undefined;
|
||||||
|
} catch { return; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,367 @@
|
|||||||
|
import { statuses, type Status, type Task, type Workspace } from "../model/model.ts";
|
||||||
|
import { Document } from "yaml";
|
||||||
|
import { split } from "./notes.ts";
|
||||||
|
import {
|
||||||
|
isManagedBoard,
|
||||||
|
readCatalog,
|
||||||
|
managedDocuments,
|
||||||
|
writeCatalog,
|
||||||
|
validateName,
|
||||||
|
} from "./catalog.ts";
|
||||||
|
import { message } from "./message.ts";
|
||||||
|
|
||||||
|
export interface BoardReference {
|
||||||
|
id: string;
|
||||||
|
path: string;
|
||||||
|
}
|
||||||
|
export interface BoardDocument extends BoardReference {
|
||||||
|
name: string;
|
||||||
|
value: Board;
|
||||||
|
source: string;
|
||||||
|
archived?: boolean;
|
||||||
|
}
|
||||||
|
export interface BoardList {
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
status: Status | null;
|
||||||
|
collapsed: boolean;
|
||||||
|
maxCards?: number;
|
||||||
|
}
|
||||||
|
export interface Board {
|
||||||
|
schema: 1;
|
||||||
|
kind: "board";
|
||||||
|
id: string;
|
||||||
|
lists: BoardList[];
|
||||||
|
backgroundImage?: string | null;
|
||||||
|
backgroundAppearance?: import("../model/background.ts").BackgroundAppearance;
|
||||||
|
defaults: Record<Status, string | null>;
|
||||||
|
}
|
||||||
|
export function defaultBoard(id: string = crypto.randomUUID()): Board {
|
||||||
|
return {
|
||||||
|
schema: 1,
|
||||||
|
kind: "board",
|
||||||
|
id,
|
||||||
|
lists: [
|
||||||
|
{ id: "todo", name: message("To do"), status: "todo", collapsed: false },
|
||||||
|
{ id: "doing", name: message("In progress"), status: "doing", collapsed: false },
|
||||||
|
{ id: "done", name: message("Done"), status: "done", collapsed: false },
|
||||||
|
],
|
||||||
|
defaults: { todo: "todo", doing: "doing", done: "done" },
|
||||||
|
};
|
||||||
|
}
|
||||||
|
export function parseBoard(source: string): Board {
|
||||||
|
const value = split(source).doc.toJS({ maxAliasCount: 50 }).runestone_pm;
|
||||||
|
if (
|
||||||
|
!value ||
|
||||||
|
value.schema !== 1 ||
|
||||||
|
value.kind !== "board" ||
|
||||||
|
typeof value.id !== "string" ||
|
||||||
|
!value.id.trim() ||
|
||||||
|
!Array.isArray(value.lists) ||
|
||||||
|
!value.defaults
|
||||||
|
)
|
||||||
|
throw new Error(message("The board file has an unsupported format. Restore or repair it before editing lists."));
|
||||||
|
if (value.backgroundImage != null && !/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/.test(value.backgroundImage)) throw new Error(message("The board background image is invalid."));
|
||||||
|
const ids = new Set<string>();
|
||||||
|
for (const list of value.lists) {
|
||||||
|
if (
|
||||||
|
!list ||
|
||||||
|
typeof list.id !== "string" ||
|
||||||
|
!list.id ||
|
||||||
|
ids.has(list.id) ||
|
||||||
|
typeof list.name !== "string" ||
|
||||||
|
!list.name.trim() ||
|
||||||
|
list.name.length > 80 ||
|
||||||
|
(list.status !== null && !statuses.includes(list.status)) ||
|
||||||
|
typeof list.collapsed !== "boolean" ||
|
||||||
|
(list.maxCards !== undefined && (!Number.isSafeInteger(list.maxCards) || list.maxCards < 1))
|
||||||
|
)
|
||||||
|
throw new Error(message("The board contains an invalid list. Repair the board file before editing."));
|
||||||
|
ids.add(list.id);
|
||||||
|
}
|
||||||
|
for (const status of statuses)
|
||||||
|
if (value.defaults[status] !== null && !ids.has(value.defaults[status]))
|
||||||
|
throw new Error(message("The board has an invalid default list."));
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
export function boardDocument(
|
||||||
|
source: string,
|
||||||
|
path: string,
|
||||||
|
): BoardDocument | null {
|
||||||
|
const value = split(source).doc.toJS({ maxAliasCount: 50 }).runestone_pm;
|
||||||
|
if (value?.kind !== "board") return null;
|
||||||
|
const board = parseBoard(source);
|
||||||
|
return {
|
||||||
|
id: board.id,
|
||||||
|
path,
|
||||||
|
name: path
|
||||||
|
.split("/")
|
||||||
|
.at(-1)!
|
||||||
|
.replace(/\.(md|markdown|mdown)$/i, ""),
|
||||||
|
value: board,
|
||||||
|
source,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
export function newBoardSource(): string {
|
||||||
|
return `---\n${new Document({ runestone_pm: defaultBoard() }).toString({ lineWidth: 0 })}---\n`;
|
||||||
|
}
|
||||||
|
export class BoardStore {
|
||||||
|
value = defaultBoard("all-tasks");
|
||||||
|
name: string = message("All tasks");
|
||||||
|
available = true;
|
||||||
|
archived = false;
|
||||||
|
private source: string | null = null;
|
||||||
|
private workspace: Workspace;
|
||||||
|
readonly reference?: BoardReference;
|
||||||
|
constructor(workspace: Workspace, reference?: BoardReference) {
|
||||||
|
this.workspace = workspace;
|
||||||
|
this.reference = reference ? { ...reference } : undefined;
|
||||||
|
}
|
||||||
|
get editable() {
|
||||||
|
return (
|
||||||
|
!!this.reference &&
|
||||||
|
this.available &&
|
||||||
|
!this.archived &&
|
||||||
|
this.source !== null
|
||||||
|
);
|
||||||
|
}
|
||||||
|
async reload() {
|
||||||
|
if (!this.reference) return;
|
||||||
|
if (!isManagedBoard(this.reference.path) && this.workspace.readOptional) {
|
||||||
|
const snapshot = await readCatalog(this.workspace);
|
||||||
|
if (snapshot.value.deletedBoardIds?.includes(this.reference.id)) {
|
||||||
|
this.load();
|
||||||
|
throw new Error(message("This board was deleted. Open All tasks to find its cards."));
|
||||||
|
}
|
||||||
|
const managed = snapshot.value.boards.find(
|
||||||
|
(board) => board.value.id === this.reference!.id,
|
||||||
|
);
|
||||||
|
if (managed) {
|
||||||
|
const current = await this.workspace.readOptional(this.reference.path);
|
||||||
|
if (
|
||||||
|
managed.original?.path !== this.reference.path ||
|
||||||
|
(current !== null && current !== managed.original.source)
|
||||||
|
)
|
||||||
|
throw new Error(message("The legacy board differs from hidden storage. Preserve both versions."));
|
||||||
|
this.load(
|
||||||
|
managedDocuments(snapshot.value, snapshot.source!).find(
|
||||||
|
(board) => board.id === this.reference!.id,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (isManagedBoard(this.reference.path)) {
|
||||||
|
const snapshot = await readCatalog(this.workspace);
|
||||||
|
this.load(
|
||||||
|
managedDocuments(snapshot.value, snapshot.source ?? "").find(
|
||||||
|
(board) => board.id === this.reference!.id,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
if (!this.available)
|
||||||
|
throw new Error(message("This board is unavailable. Refresh Project Management."));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const source = await this.workspace.read(this.reference.path);
|
||||||
|
const document = boardDocument(source, this.reference.path);
|
||||||
|
if (!document || document.id !== this.reference.id)
|
||||||
|
throw new Error(message("The board changed. Reopen it from navigation."));
|
||||||
|
this.load(document);
|
||||||
|
}
|
||||||
|
load(document?: BoardDocument) {
|
||||||
|
if (!this.reference) return;
|
||||||
|
this.available = !!document;
|
||||||
|
this.source = document?.source ?? null;
|
||||||
|
if (document) {
|
||||||
|
this.reference.path = document.path;
|
||||||
|
this.value = document.value;
|
||||||
|
this.name = document.name;
|
||||||
|
this.archived = document.archived ?? false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
listFor(
|
||||||
|
task: Pick<Task, "listId" | "status" | "placements">,
|
||||||
|
): BoardList | undefined {
|
||||||
|
const id = this.reference
|
||||||
|
? (task.placements?.[this.reference.id]?.listId ??
|
||||||
|
(task.listId !== undefined ? task.listId : null))
|
||||||
|
: this.value.defaults[task.status];
|
||||||
|
return this.value.lists.find((list) => list.id === id);
|
||||||
|
}
|
||||||
|
async update(change: (board: Board) => void) {
|
||||||
|
if (!this.editable)
|
||||||
|
throw new Error(message("Open an available board to edit its lists."));
|
||||||
|
const expected = this.source;
|
||||||
|
if (!isManagedBoard(this.reference!.path) && this.workspace.readOptional) {
|
||||||
|
const snapshot = await readCatalog(this.workspace);
|
||||||
|
if (snapshot.value.deletedBoardIds?.includes(this.reference!.id))
|
||||||
|
throw new Error(message("This board was deleted. Open All tasks to find its cards."));
|
||||||
|
if (
|
||||||
|
snapshot.value.boards.some(
|
||||||
|
(board) => board.value.id === this.reference!.id,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
throw new Error(message("This board moved to hidden storage. Refresh before editing."));
|
||||||
|
}
|
||||||
|
if (isManagedBoard(this.reference!.path)) {
|
||||||
|
const snapshot = await readCatalog(this.workspace);
|
||||||
|
if (snapshot.source !== expected)
|
||||||
|
throw new Error(message("The board changed. Refresh before editing its lists."));
|
||||||
|
const board = snapshot.value.boards.find(
|
||||||
|
(item) => item.value.id === this.reference!.id,
|
||||||
|
);
|
||||||
|
if (!board) throw new Error(message("The board is unavailable."));
|
||||||
|
change(board.value);
|
||||||
|
this.source = await writeCatalog(
|
||||||
|
this.workspace,
|
||||||
|
snapshot.value,
|
||||||
|
expected,
|
||||||
|
);
|
||||||
|
this.value = board.value;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const current = await this.workspace.read(this.reference!.path);
|
||||||
|
if (current !== expected)
|
||||||
|
throw new Error(message("The board changed. Refresh before editing its lists."));
|
||||||
|
const next = structuredClone(this.value);
|
||||||
|
change(next);
|
||||||
|
const { doc, body, newline, match } = split(expected!);
|
||||||
|
for (const key of ["lists", "defaults", "backgroundImage", "backgroundAppearance"] as const)
|
||||||
|
if (next[key] !== undefined) doc.setIn(["runestone_pm", key], next[key]);
|
||||||
|
const source = `${match?.[1] ?? ""}---${newline}${doc.toString({ lineWidth: 0 }).replaceAll("\n", newline)}---${newline}${body}`;
|
||||||
|
parseBoard(source);
|
||||||
|
await this.workspace.write(this.reference!.path, source, expected!);
|
||||||
|
this.source = source;
|
||||||
|
this.value = next;
|
||||||
|
}
|
||||||
|
async deleteBoard() {
|
||||||
|
if (!this.reference || !this.available || this.source === null)
|
||||||
|
throw new Error(message("Open an available board before deleting it."));
|
||||||
|
const { id, path } = this.reference;
|
||||||
|
const snapshot = await readCatalog(this.workspace);
|
||||||
|
if (snapshot.value.deletedBoardIds?.includes(id))
|
||||||
|
throw new Error(message("This board was already deleted. Refresh Project Management."));
|
||||||
|
if (isManagedBoard(path)) {
|
||||||
|
if (snapshot.source !== this.source)
|
||||||
|
throw new Error(message("The board changed. Cancel, refresh, and review it before deleting."));
|
||||||
|
if (!snapshot.value.boards.some((board) => board.value.id === id))
|
||||||
|
throw new Error(message("The board is unavailable. Refresh Project Management."));
|
||||||
|
} else {
|
||||||
|
if (snapshot.value.boards.some((board) => board.value.id === id))
|
||||||
|
throw new Error(message("This board moved to hidden storage. Refresh before deleting."));
|
||||||
|
if ((await this.workspace.read(path)) !== this.source)
|
||||||
|
throw new Error(message("The board changed. Cancel, refresh, and review it before deleting."));
|
||||||
|
}
|
||||||
|
snapshot.value.boards = snapshot.value.boards.filter((board) => board.value.id !== id);
|
||||||
|
// Keep originals and card memberships intact. The record prevents legacy rediscovery.
|
||||||
|
snapshot.value.deletedBoardIds = [...(snapshot.value.deletedBoardIds ?? []), id];
|
||||||
|
await writeCatalog(this.workspace, snapshot.value, snapshot.source);
|
||||||
|
this.load();
|
||||||
|
}
|
||||||
|
async manage(patch: { name?: string; archived?: boolean }) {
|
||||||
|
if (
|
||||||
|
!this.reference ||
|
||||||
|
!isManagedBoard(this.reference.path) ||
|
||||||
|
!this.available
|
||||||
|
)
|
||||||
|
throw new Error(message("Migrate this board before managing hidden storage."));
|
||||||
|
const snapshot = await readCatalog(this.workspace);
|
||||||
|
if (snapshot.source !== this.source)
|
||||||
|
throw new Error(message("The board changed. Refresh before saving."));
|
||||||
|
const board = snapshot.value.boards.find(
|
||||||
|
(item) => item.value.id === this.reference!.id,
|
||||||
|
)!;
|
||||||
|
if (patch.name !== undefined) {
|
||||||
|
validateName(patch.name);
|
||||||
|
if (
|
||||||
|
snapshot.value.boards.some(
|
||||||
|
(item) =>
|
||||||
|
item !== board &&
|
||||||
|
item.name.toLocaleLowerCase() ===
|
||||||
|
patch.name!.trim().toLocaleLowerCase(),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
throw new Error(message("A board with this name already exists."));
|
||||||
|
board.name = patch.name.trim();
|
||||||
|
}
|
||||||
|
if (patch.archived !== undefined) board.archived = patch.archived;
|
||||||
|
this.source = await writeCatalog(
|
||||||
|
this.workspace,
|
||||||
|
snapshot.value,
|
||||||
|
snapshot.source,
|
||||||
|
);
|
||||||
|
this.name = board.name;
|
||||||
|
this.archived = board.archived ?? false;
|
||||||
|
}
|
||||||
|
async add(name: string, status: Status | null) {
|
||||||
|
await this.update((board) => {
|
||||||
|
this.checkName(board, name);
|
||||||
|
board.lists.push({
|
||||||
|
id: crypto.randomUUID(),
|
||||||
|
name: name.trim(),
|
||||||
|
status,
|
||||||
|
collapsed: false,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
async edit(id: string, name: string, status: Status | null) {
|
||||||
|
await this.update((board) => {
|
||||||
|
this.checkName(board, name, id);
|
||||||
|
const list = this.requireList(board, id);
|
||||||
|
list.name = name.trim();
|
||||||
|
list.status = status;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
async collapse(id: string) {
|
||||||
|
await this.update((board) => {
|
||||||
|
const list = this.requireList(board, id);
|
||||||
|
list.collapsed = !list.collapsed;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
async setLimit(id: string, maximum?: number) {
|
||||||
|
if (maximum !== undefined && (!Number.isSafeInteger(maximum) || maximum < 1))
|
||||||
|
throw new Error(message("Enter a whole number of at least 1, or leave the maximum blank."));
|
||||||
|
await this.update((board) => {
|
||||||
|
const list = this.requireList(board, id);
|
||||||
|
if (maximum === undefined) delete list.maxCards;
|
||||||
|
else list.maxCards = maximum;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
async move(id: string, index: number) {
|
||||||
|
await this.update((board) => {
|
||||||
|
const list = this.requireList(board, id);
|
||||||
|
board.lists = board.lists.filter((item) => item.id !== id);
|
||||||
|
board.lists.splice(
|
||||||
|
Math.max(0, Math.min(index, board.lists.length)),
|
||||||
|
0,
|
||||||
|
list,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
async remove(id: string) {
|
||||||
|
await this.update((board) => {
|
||||||
|
this.requireList(board, id);
|
||||||
|
board.lists = board.lists.filter((list) => list.id !== id);
|
||||||
|
for (const status of statuses)
|
||||||
|
if (board.defaults[status] === id) board.defaults[status] = null;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
private requireList(board: Board, id: string) {
|
||||||
|
const list = board.lists.find((item) => item.id === id);
|
||||||
|
if (!list)
|
||||||
|
throw new Error(message("This list no longer exists. Refresh the board."));
|
||||||
|
return list;
|
||||||
|
}
|
||||||
|
private checkName(board: Board, name: string, except?: string) {
|
||||||
|
if (!name.trim() || name.trim().length > 80)
|
||||||
|
throw new Error(message("Enter a list name of 1 to 80 characters."));
|
||||||
|
if (
|
||||||
|
board.lists.some(
|
||||||
|
(list) =>
|
||||||
|
list.id !== except &&
|
||||||
|
list.name.toLocaleLowerCase() === name.trim().toLocaleLowerCase(),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
throw new Error(message("A list with this name already exists."));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,167 @@
|
|||||||
|
import { readTask, newTask, split } from "./notes.ts";
|
||||||
|
import type { Task, TaskFields, Workspace } from "../model/model.ts";
|
||||||
|
import { backupFile, type OriginalFile } from "./catalog.ts";
|
||||||
|
import { legacyPosition } from "./order.ts";
|
||||||
|
import { mapConcurrent, readSources } from "./scan.ts";
|
||||||
|
import {
|
||||||
|
cardsFolder,
|
||||||
|
cardsMarker,
|
||||||
|
isHiddenCard,
|
||||||
|
readOptional,
|
||||||
|
saveDocument,
|
||||||
|
} from "./persistence.ts";
|
||||||
|
import { format, message } from "./message.ts";
|
||||||
|
|
||||||
|
/** The issue of one file: its path and its problem. */
|
||||||
|
export function fileIssue(path: string, problem: string) {
|
||||||
|
return format(message("In {path}: {problem}"), { path, problem });
|
||||||
|
}
|
||||||
|
|
||||||
|
export function cardPath(id: string) {
|
||||||
|
const key = Array.from(new TextEncoder().encode(id), (byte) =>
|
||||||
|
byte.toString(16).padStart(2, "0"),
|
||||||
|
).join("");
|
||||||
|
return `${cardsFolder}/${key}.md`;
|
||||||
|
}
|
||||||
|
export function cardOrigin(source: string): OriginalFile | undefined {
|
||||||
|
const origin = split(source).doc.toJS({
|
||||||
|
maxAliasCount: 50,
|
||||||
|
}).runestone_pm_origin;
|
||||||
|
if (origin === undefined) return;
|
||||||
|
if (
|
||||||
|
!origin ||
|
||||||
|
typeof origin.path !== "string" ||
|
||||||
|
typeof origin.source !== "string" ||
|
||||||
|
typeof origin.backup !== "string" ||
|
||||||
|
origin.path.startsWith(".") ||
|
||||||
|
origin.path.includes("\\") ||
|
||||||
|
origin.path
|
||||||
|
.split("/")
|
||||||
|
.some((part: string) => !part || part === "." || part === "..") ||
|
||||||
|
origin.backup !== `.runestone/pm/backups/${origin.path}`
|
||||||
|
)
|
||||||
|
throw new Error(message("The card migration record is invalid. Keep the original note."));
|
||||||
|
return origin;
|
||||||
|
}
|
||||||
|
/** Read one hidden card file. It throws when the file is invalid or when its name does not match the card ID. */
|
||||||
|
export function parseCard(path: string, source: string): Task {
|
||||||
|
cardOrigin(source);
|
||||||
|
const task = readTask(path, source);
|
||||||
|
if (!task || cardPath(task.id) !== path)
|
||||||
|
throw new Error(message("The hidden card ID does not match its storage path."));
|
||||||
|
return task;
|
||||||
|
}
|
||||||
|
export async function prepareCards(workspace: Workspace) {
|
||||||
|
const marker = await readOptional(workspace, cardsMarker);
|
||||||
|
if (marker !== null) return;
|
||||||
|
try {
|
||||||
|
await saveDocument(workspace, cardsMarker, "*\n", null);
|
||||||
|
} catch (error) {
|
||||||
|
if ((await readOptional(workspace, cardsMarker)) !== "*\n") throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
export async function readCards(
|
||||||
|
workspace: Workspace,
|
||||||
|
previous: ReadonlyMap<string, Task> = new Map(),
|
||||||
|
): Promise<{ tasks: Task[]; issues: string[] }> {
|
||||||
|
const tasks: Task[] = [],
|
||||||
|
issues: string[] = [];
|
||||||
|
// Direct reads are necessary because the host hides .runestone from root listings.
|
||||||
|
if (
|
||||||
|
!workspace.readOptional ||
|
||||||
|
(await workspace.readOptional(cardsMarker)) === null
|
||||||
|
)
|
||||||
|
return { tasks, issues };
|
||||||
|
const entries = (await workspace.list(cardsFolder)).filter(
|
||||||
|
(entry) => entry.kind !== "folder" && isHiddenCard(entry.rel_path),
|
||||||
|
);
|
||||||
|
const sources = await readSources(workspace, entries.map(entry => entry.rel_path));
|
||||||
|
const documents = await mapConcurrent(entries, async (entry) => {
|
||||||
|
try {
|
||||||
|
const result = sources.get(entry.rel_path)!;
|
||||||
|
if (result.error || result.source === undefined) throw new Error(result.error ?? message("The card is unavailable."));
|
||||||
|
const source = result.source;
|
||||||
|
const cached = previous.get(entry.rel_path);
|
||||||
|
if (cached?.source === source) return { task: cached };
|
||||||
|
return { task: parseCard(entry.rel_path, source) };
|
||||||
|
} catch (error) {
|
||||||
|
return {
|
||||||
|
issue: fileIssue(entry.rel_path, error instanceof Error ? error.message : String(error)),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
});
|
||||||
|
for (const document of documents) {
|
||||||
|
if (document.task) tasks.push(document.task);
|
||||||
|
if (document.issue) issues.push(document.issue);
|
||||||
|
}
|
||||||
|
return { tasks, issues };
|
||||||
|
}
|
||||||
|
export async function createCard(
|
||||||
|
workspace: Workspace,
|
||||||
|
title: string,
|
||||||
|
fields: TaskFields,
|
||||||
|
body: string,
|
||||||
|
id: string = crypto.randomUUID(),
|
||||||
|
) {
|
||||||
|
// The storage name is independent of the title, so punctuation and duplicate titles are safe.
|
||||||
|
const note = newTask(id, { ...fields, title: title.trim() }, body, id);
|
||||||
|
const path = cardPath(id);
|
||||||
|
await prepareCards(workspace);
|
||||||
|
await saveDocument(workspace, path, note.source, null);
|
||||||
|
return { path, source: note.source };
|
||||||
|
}
|
||||||
|
export async function migrateCards(workspace: Workspace, tasks: Task[]) {
|
||||||
|
for (const task of tasks) {
|
||||||
|
if (isHiddenCard(task.path)) continue;
|
||||||
|
if ((await workspace.read(task.path)) !== task.source)
|
||||||
|
throw new Error(
|
||||||
|
format(message("The card changed: {path}. Refresh before migration."), { path: task.path }),
|
||||||
|
);
|
||||||
|
const destination = await readOptional(workspace, cardPath(task.id));
|
||||||
|
if (destination !== null) {
|
||||||
|
const origin = cardOrigin(destination);
|
||||||
|
if (origin?.path !== task.path || origin.source !== task.source)
|
||||||
|
throw new Error(
|
||||||
|
format(message("A different hidden card already uses the ID from {path}."), { path: task.path }),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (split(task.source).doc.has("runestone_pm_origin"))
|
||||||
|
throw new Error(
|
||||||
|
format(message("The note already contains a migration record: {path}. Review it before migration."), { path: task.path }),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
for (const task of tasks) {
|
||||||
|
if (isHiddenCard(task.path)) continue;
|
||||||
|
const original = await backupFile(workspace, task.path, task.source);
|
||||||
|
const path = cardPath(task.id);
|
||||||
|
if ((await readOptional(workspace, path)) !== null) continue;
|
||||||
|
const { doc, body, newline, match } = split(task.source);
|
||||||
|
doc.set("runestone_pm_origin", original);
|
||||||
|
if (task.order === undefined)
|
||||||
|
doc.setIn(["runestone_pm", "order"], legacyPosition(task.path));
|
||||||
|
for (const [id, placement] of Object.entries(task.placements ?? {}))
|
||||||
|
if (placement.order === undefined)
|
||||||
|
doc.setIn(
|
||||||
|
["runestone_pm", "placements", id, "order"],
|
||||||
|
legacyPosition(task.path),
|
||||||
|
);
|
||||||
|
const source = `${match?.[1] ?? ""}---${newline}${doc.toString({ lineWidth: 0 }).replaceAll("\n", newline)}---${newline}${body}`;
|
||||||
|
const copied = readTask(path, source)!;
|
||||||
|
if (
|
||||||
|
copied.id !== task.id ||
|
||||||
|
copied.title !== task.title ||
|
||||||
|
copied.body !== task.body
|
||||||
|
)
|
||||||
|
throw new Error(
|
||||||
|
format(message("The card copy differs from {path}. Keep the original."), { path: task.path }),
|
||||||
|
);
|
||||||
|
if ((await workspace.read(task.path)) !== task.source)
|
||||||
|
throw new Error(format(message("The card changed: {path}. Retry migration."), { path: task.path }));
|
||||||
|
await prepareCards(workspace);
|
||||||
|
await saveDocument(workspace, path, source, null);
|
||||||
|
if ((await workspace.read(path)) !== source)
|
||||||
|
throw new Error(
|
||||||
|
format(message("The saved card check failed: {path}. Keep the original."), { path: task.path }),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,139 @@
|
|||||||
|
import { Document } from "yaml";
|
||||||
|
import {
|
||||||
|
defaultBoard,
|
||||||
|
parseBoard,
|
||||||
|
type Board,
|
||||||
|
type BoardDocument,
|
||||||
|
} from "./board.ts";
|
||||||
|
import type { Workspace } from "../model/model.ts";
|
||||||
|
import { readOptional, saveDocument } from "./persistence.ts";
|
||||||
|
import { format, message } from "./message.ts";
|
||||||
|
|
||||||
|
export const catalogPath = ".runestone/pm/workspace.json";
|
||||||
|
export const boardKey = (id: string) => `pm-board:${id}`;
|
||||||
|
export const isManagedBoard = (path: string) => path.startsWith("pm-board:");
|
||||||
|
export interface OriginalFile {
|
||||||
|
path: string;
|
||||||
|
source: string;
|
||||||
|
backup: string;
|
||||||
|
}
|
||||||
|
export interface ManagedBoard {
|
||||||
|
name: string;
|
||||||
|
value: Board;
|
||||||
|
archived?: boolean;
|
||||||
|
original?: OriginalFile;
|
||||||
|
}
|
||||||
|
export interface Catalog {
|
||||||
|
schema: 1;
|
||||||
|
boards: ManagedBoard[];
|
||||||
|
deletedBoardIds?: string[];
|
||||||
|
[key: string]: unknown;
|
||||||
|
}
|
||||||
|
export function boardMarkdown(value: Board): string {
|
||||||
|
return `---\n${new Document({ runestone_pm: value }).toString({ lineWidth: 0 })}---\n`;
|
||||||
|
}
|
||||||
|
export function validateName(name: string) {
|
||||||
|
if (!name.trim() || name.trim().length > 100 || /[\x00-\x1f]/.test(name))
|
||||||
|
throw new Error(message("Enter a board name of 1 to 100 characters."));
|
||||||
|
}
|
||||||
|
export function parseCatalog(source: string | null): Catalog {
|
||||||
|
if (source === null) return { schema: 1, boards: [] };
|
||||||
|
const data = JSON.parse(source);
|
||||||
|
if (!data || data.schema !== 1 || !Array.isArray(data.boards))
|
||||||
|
throw new Error(message("The Project Management storage format is unsupported. Restore a backup or update Project Management."));
|
||||||
|
const ids = new Set<string>();
|
||||||
|
if (
|
||||||
|
data.deletedBoardIds !== undefined &&
|
||||||
|
(!Array.isArray(data.deletedBoardIds) ||
|
||||||
|
data.deletedBoardIds.some((id: unknown) => typeof id !== "string" || !id.trim()) ||
|
||||||
|
new Set(data.deletedBoardIds).size !== data.deletedBoardIds.length)
|
||||||
|
)
|
||||||
|
throw new Error(message("The deleted board record is invalid."));
|
||||||
|
for (const board of data.boards) {
|
||||||
|
if (!board || typeof board.name !== "string")
|
||||||
|
throw new Error(message("A saved board has no name."));
|
||||||
|
validateName(board.name);
|
||||||
|
parseBoard(boardMarkdown(board.value));
|
||||||
|
if (ids.has(board.value.id))
|
||||||
|
throw new Error(message("Project Management storage contains duplicate board IDs."));
|
||||||
|
ids.add(board.value.id);
|
||||||
|
if (data.deletedBoardIds?.includes(board.value.id))
|
||||||
|
throw new Error(message("A deleted board still has an active storage entry."));
|
||||||
|
if (board.archived !== undefined && typeof board.archived !== "boolean")
|
||||||
|
throw new Error(message("The board archive state is invalid."));
|
||||||
|
if (
|
||||||
|
board.original &&
|
||||||
|
(typeof board.original.path !== "string" ||
|
||||||
|
typeof board.original.source !== "string" ||
|
||||||
|
typeof board.original.backup !== "string")
|
||||||
|
)
|
||||||
|
throw new Error(message("The board migration record is invalid."));
|
||||||
|
}
|
||||||
|
return data;
|
||||||
|
}
|
||||||
|
export async function readCatalog(workspace: Workspace) {
|
||||||
|
const source = await readOptional(workspace, catalogPath);
|
||||||
|
return { source, value: parseCatalog(source) };
|
||||||
|
}
|
||||||
|
export async function writeCatalog(
|
||||||
|
workspace: Workspace,
|
||||||
|
value: Catalog,
|
||||||
|
expected: string | null,
|
||||||
|
) {
|
||||||
|
if (!workspace.readOptional)
|
||||||
|
throw new Error(message("Update RuneStone to use hidden Project Management storage."));
|
||||||
|
const source = JSON.stringify(value, null, 2) + "\n";
|
||||||
|
parseCatalog(source);
|
||||||
|
await saveDocument(workspace, catalogPath, source, expected);
|
||||||
|
return source;
|
||||||
|
}
|
||||||
|
export function managedDocuments(
|
||||||
|
value: Catalog,
|
||||||
|
source: string,
|
||||||
|
): BoardDocument[] {
|
||||||
|
return value.boards.map((board) => ({
|
||||||
|
id: board.value.id,
|
||||||
|
path: boardKey(board.value.id),
|
||||||
|
name: board.name,
|
||||||
|
value: board.value,
|
||||||
|
archived: board.archived,
|
||||||
|
source,
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
export async function createBoard(workspace: Workspace, name: string) {
|
||||||
|
validateName(name);
|
||||||
|
const snapshot = await readCatalog(workspace);
|
||||||
|
if (
|
||||||
|
snapshot.value.boards.some(
|
||||||
|
(board) =>
|
||||||
|
board.name.toLocaleLowerCase() === name.trim().toLocaleLowerCase(),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
throw new Error(message("A board with this name already exists."));
|
||||||
|
const value = defaultBoard();
|
||||||
|
snapshot.value.boards.push({ name: name.trim(), value });
|
||||||
|
await writeCatalog(workspace, snapshot.value, snapshot.source);
|
||||||
|
return { id: value.id, path: boardKey(value.id) };
|
||||||
|
}
|
||||||
|
export async function backupFile(
|
||||||
|
workspace: Workspace,
|
||||||
|
path: string,
|
||||||
|
source: string,
|
||||||
|
): Promise<OriginalFile> {
|
||||||
|
if (
|
||||||
|
path.startsWith(".") ||
|
||||||
|
path.includes("\\") ||
|
||||||
|
path.split("/").some((part) => !part || part === ".." || part === ".")
|
||||||
|
)
|
||||||
|
throw new Error(message("The migration source path is invalid."));
|
||||||
|
const backup = `.runestone/pm/backups/${path}`;
|
||||||
|
const saved = await readOptional(workspace, backup);
|
||||||
|
if (saved === null) await saveDocument(workspace, backup, source, null);
|
||||||
|
else if (saved !== source)
|
||||||
|
throw new Error(
|
||||||
|
format(message("The backup differs from {path}. Preserve both versions before migration."), { path }),
|
||||||
|
);
|
||||||
|
if ((await workspace.read(backup)) !== source)
|
||||||
|
throw new Error(format(message("The backup check failed for {path}."), { path }));
|
||||||
|
return { path, source, backup };
|
||||||
|
}
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
import type { Workspace } from "../model/model.ts";
|
||||||
|
import { readOptional, saveDocument } from "./persistence.ts";
|
||||||
|
import { message } from "./message.ts";
|
||||||
|
|
||||||
|
export const deletedCardsPath = ".runestone/pm/deleted-cards.json";
|
||||||
|
|
||||||
|
export async function readDeletedCards(workspace: Workspace) {
|
||||||
|
const source = await readOptional(workspace, deletedCardsPath);
|
||||||
|
if (source === null) return { source, ids: [] as string[] };
|
||||||
|
const value = JSON.parse(source);
|
||||||
|
if (value?.schema !== 1 || !Array.isArray(value.ids) ||
|
||||||
|
value.ids.some((id: unknown) => typeof id !== "string" || !id.trim()) ||
|
||||||
|
new Set(value.ids).size !== value.ids.length)
|
||||||
|
throw new Error(message("The deleted card record is invalid. Restore it before editing cards."));
|
||||||
|
return { source, ids: value.ids as string[] };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Keep a deletion record so saved legacy notes cannot restore deleted cards. */
|
||||||
|
export async function recordCardDeletion(workspace: Workspace, id: string) {
|
||||||
|
const snapshot = await readDeletedCards(workspace);
|
||||||
|
if (snapshot.ids.includes(id)) return;
|
||||||
|
await saveDocument(workspace, deletedCardsPath,
|
||||||
|
JSON.stringify({ schema: 1, ids: [...snapshot.ids, id] }, null, 2) + "\n", snapshot.source);
|
||||||
|
}
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
import type { Workspace } from "../model/model.ts";
|
||||||
|
import { readOptional, saveDocument } from "./persistence.ts";
|
||||||
|
import { message } from "./message.ts";
|
||||||
|
|
||||||
|
/** A draft is separate from the saved card and uses compare-and-write protection. */
|
||||||
|
export class DescriptionDraft {
|
||||||
|
private source: string | null = null;
|
||||||
|
private queue: Promise<unknown> = Promise.resolve();
|
||||||
|
readonly path: string;
|
||||||
|
private workspace: Workspace;
|
||||||
|
constructor(workspace: Workspace, id: string) {
|
||||||
|
this.workspace = workspace;
|
||||||
|
const key = Array.from(new TextEncoder().encode(id), byte => byte.toString(16).padStart(2, "0")).join("");
|
||||||
|
this.path = `.runestone/pm/drafts/${key}.json`;
|
||||||
|
}
|
||||||
|
async load(): Promise<string | null> {
|
||||||
|
this.source = await readOptional(this.workspace, this.path);
|
||||||
|
if (this.source === null) return null;
|
||||||
|
const value = JSON.parse(this.source);
|
||||||
|
if (value?.schema !== 1 || (value.body !== null && typeof value.body !== "string"))
|
||||||
|
throw new Error(message("The description draft is invalid. Preserve it before recovery."));
|
||||||
|
return value.body;
|
||||||
|
}
|
||||||
|
save(body: string | null): Promise<void> {
|
||||||
|
const write = this.queue.then(async () => {
|
||||||
|
const source = JSON.stringify({ schema: 1, body }) + "\n";
|
||||||
|
if (source === this.source || (body === null && this.source === null)) return;
|
||||||
|
await saveDocument(this.workspace, this.path, source, this.source);
|
||||||
|
this.source = source;
|
||||||
|
});
|
||||||
|
this.queue = write.catch(() => {});
|
||||||
|
return write;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,70 @@
|
|||||||
|
import type { Workspace, TaskFields } from "../model/model.ts";
|
||||||
|
import { saveDocument, storageRoot } from "./persistence.ts";
|
||||||
|
import { message } from "./message.ts";
|
||||||
|
|
||||||
|
export const maxImageBytes = 50 * 1024 * 1024;
|
||||||
|
export const imageTypes = [
|
||||||
|
"image/png",
|
||||||
|
"image/jpeg",
|
||||||
|
"image/gif",
|
||||||
|
"image/webp",
|
||||||
|
];
|
||||||
|
const idPattern =
|
||||||
|
"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}";
|
||||||
|
export const imageFolder = `${storageRoot}/images`;
|
||||||
|
export function imagePath(id: string) {
|
||||||
|
if (!new RegExp(`^${idPattern}$`).test(id))
|
||||||
|
throw new Error(message("The image ID is invalid."));
|
||||||
|
return `${imageFolder}/${id}.json`;
|
||||||
|
}
|
||||||
|
export function imageReferences(body: string) {
|
||||||
|
return [
|
||||||
|
...body.matchAll(
|
||||||
|
new RegExp(`!\\[([^\\]\\r\\n]*)\\]\\(pm-image:(${idPattern})\\)`, "g"),
|
||||||
|
),
|
||||||
|
].map((match) => ({
|
||||||
|
id: match[2],
|
||||||
|
name: match[1] || "Pasted image",
|
||||||
|
markdown: match[0],
|
||||||
|
index: match.index,
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
export function imageMarkdown(name: string, id: string) {
|
||||||
|
imagePath(id);
|
||||||
|
return `![${name.replace(/[\[\]\r\n\\]/g, " ").trim() || "Pasted image"}](pm-image:${id})`;
|
||||||
|
}
|
||||||
|
export function parseImage(source: string): string {
|
||||||
|
if (source.length > Math.ceil(maxImageBytes / 3) * 4 + 256)
|
||||||
|
throw new Error(message("The saved image exceeds the 50 MiB limit."));
|
||||||
|
const value = JSON.parse(source);
|
||||||
|
if (value?.schema !== 1 || typeof value.data !== "string")
|
||||||
|
throw new Error(message("The saved image is invalid."));
|
||||||
|
const match =
|
||||||
|
/^data:(image\/(?:png|jpeg|gif|webp));base64,([A-Za-z0-9+/]+={0,2})$/.exec(
|
||||||
|
value.data,
|
||||||
|
);
|
||||||
|
if (
|
||||||
|
!match ||
|
||||||
|
match[2].length % 4 !== 0 ||
|
||||||
|
atob(match[2]).length > maxImageBytes
|
||||||
|
)
|
||||||
|
throw new Error(message("The saved image is invalid or exceeds 50 MiB."));
|
||||||
|
return value.data;
|
||||||
|
}
|
||||||
|
export async function saveImages(
|
||||||
|
workspace: Workspace,
|
||||||
|
body: string,
|
||||||
|
pending: Map<string, string>,
|
||||||
|
attachments: TaskFields["attachments"] = [],
|
||||||
|
) {
|
||||||
|
for (const id of new Set([...imageReferences(body), ...attachments].map((image) => image.id))) {
|
||||||
|
const data = pending.get(id);
|
||||||
|
if (!data) continue;
|
||||||
|
const source = JSON.stringify({ schema: 1, data }) + "\n";
|
||||||
|
parseImage(source);
|
||||||
|
const path = imagePath(id);
|
||||||
|
// Retrying a failed card save reuses its complete image files.
|
||||||
|
const previous = await workspace.readOptional?.(path);
|
||||||
|
if (previous !== source) await saveDocument(workspace, path, source, null);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,136 @@
|
|||||||
|
import { cardColors, type Workspace } from "../model/model.ts";
|
||||||
|
import { readOptional, saveDocument } from "./persistence.ts";
|
||||||
|
import { message } from "./message.ts";
|
||||||
|
|
||||||
|
export const labelsPath = ".runestone/pm/labels.json";
|
||||||
|
export const legacyLabelsPath = "runestone-pm-labels.json";
|
||||||
|
export interface SavedLabel {
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
color: keyof typeof cardColors;
|
||||||
|
archived?: boolean;
|
||||||
|
}
|
||||||
|
export interface LabelSnapshot {
|
||||||
|
source: string | null;
|
||||||
|
labels: SavedLabel[];
|
||||||
|
legacy?: boolean;
|
||||||
|
}
|
||||||
|
export function defaultLabels(): SavedLabel[] {
|
||||||
|
return [
|
||||||
|
{ id: "bug", name: "Bug", color: "red" },
|
||||||
|
{ id: "feature", name: "Feature", color: "blue" },
|
||||||
|
{ id: "improvement", name: "Improvement", color: "green" },
|
||||||
|
];
|
||||||
|
}
|
||||||
|
export function validateLabels(
|
||||||
|
labels: unknown,
|
||||||
|
): asserts labels is SavedLabel[] {
|
||||||
|
if (!Array.isArray(labels)) throw new Error(message("Saved labels must be a list."));
|
||||||
|
const ids = new Set<string>(),
|
||||||
|
names = new Set<string>();
|
||||||
|
for (const label of labels) {
|
||||||
|
if (
|
||||||
|
!label ||
|
||||||
|
typeof label !== "object" ||
|
||||||
|
Array.isArray(label) ||
|
||||||
|
typeof label.id !== "string" ||
|
||||||
|
!/^[a-zA-Z0-9_-]{1,100}$/.test(label.id) ||
|
||||||
|
ids.has(label.id)
|
||||||
|
)
|
||||||
|
throw new Error(message("Each saved label needs a unique ID."));
|
||||||
|
if (
|
||||||
|
typeof label.name !== "string" ||
|
||||||
|
!label.name.trim() ||
|
||||||
|
label.name.trim().length > 80 ||
|
||||||
|
/[\x00-\x1f\x7f]/.test(label.name)
|
||||||
|
)
|
||||||
|
throw new Error(message("Enter a label name of 1 to 80 characters."));
|
||||||
|
const name = label.name.trim().toLocaleLowerCase();
|
||||||
|
if (names.has(name))
|
||||||
|
throw new Error(message("Use a different name for each label, including archived labels."));
|
||||||
|
if (
|
||||||
|
typeof label.color !== "string" ||
|
||||||
|
!Object.hasOwn(cardColors, label.color)
|
||||||
|
)
|
||||||
|
throw new Error(message("Choose a supported label color."));
|
||||||
|
if (label.archived !== undefined && typeof label.archived !== "boolean")
|
||||||
|
throw new Error(message("The label archive state must be true or false."));
|
||||||
|
ids.add(label.id);
|
||||||
|
names.add(name);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
export function parseLabels(source: string | null): LabelSnapshot {
|
||||||
|
if (source === null) return { source, labels: defaultLabels() };
|
||||||
|
let data;
|
||||||
|
try {
|
||||||
|
data = JSON.parse(source);
|
||||||
|
} catch {
|
||||||
|
throw new Error(message("Fix the saved labels file before editing labels."));
|
||||||
|
}
|
||||||
|
if (
|
||||||
|
!data ||
|
||||||
|
typeof data !== "object" ||
|
||||||
|
Array.isArray(data) ||
|
||||||
|
data.schema !== 1
|
||||||
|
)
|
||||||
|
throw new Error(message("The saved labels file has an unsupported schema."));
|
||||||
|
validateLabels(data.labels);
|
||||||
|
return { source, labels: data.labels };
|
||||||
|
}
|
||||||
|
|
||||||
|
export class LabelStore {
|
||||||
|
value: SavedLabel[] = [];
|
||||||
|
source: string | null | undefined;
|
||||||
|
error = "";
|
||||||
|
legacy = false;
|
||||||
|
readonly workspace: Workspace;
|
||||||
|
constructor(workspace: Workspace) {
|
||||||
|
this.workspace = workspace;
|
||||||
|
}
|
||||||
|
async read(): Promise<LabelSnapshot> {
|
||||||
|
const source = await readOptional(this.workspace, labelsPath);
|
||||||
|
if (source !== null) return parseLabels(source);
|
||||||
|
const legacy = await readOptional(this.workspace, legacyLabelsPath);
|
||||||
|
return { ...parseLabels(legacy), legacy: legacy !== null };
|
||||||
|
}
|
||||||
|
load(snapshot?: LabelSnapshot, error = "") {
|
||||||
|
this.value = snapshot?.labels ?? [];
|
||||||
|
this.source = snapshot?.source;
|
||||||
|
this.error = error;
|
||||||
|
this.legacy = snapshot?.legacy ?? false;
|
||||||
|
}
|
||||||
|
checkSave(labels: SavedLabel[], expected: string | null | undefined): asserts expected is string | null {
|
||||||
|
if (this.legacy)
|
||||||
|
throw new Error(message("Use the workspace migration tool before editing legacy labels. See the Project Management development guide."));
|
||||||
|
if (!this.workspace.readOptional)
|
||||||
|
throw new Error(message("Update RuneStone to use hidden Project Management storage."));
|
||||||
|
if (expected === undefined || this.error)
|
||||||
|
throw new Error(message("Saved labels are unavailable. Refresh before editing labels."));
|
||||||
|
validateLabels(labels);
|
||||||
|
}
|
||||||
|
async save(labels: SavedLabel[], expected: string | null | undefined, allowDelete = false) {
|
||||||
|
this.checkSave(labels, expected);
|
||||||
|
const previous = parseLabels(expected!);
|
||||||
|
if (
|
||||||
|
!allowDelete && previous.labels.some(
|
||||||
|
(label) => !labels.some((next) => next.id === label.id),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
throw new Error(message("Archive unused labels to preserve existing cards."));
|
||||||
|
const data = expected === null ? { schema: 1 } : JSON.parse(expected);
|
||||||
|
const source =
|
||||||
|
JSON.stringify(
|
||||||
|
{
|
||||||
|
...data,
|
||||||
|
labels: labels.map((label) => ({
|
||||||
|
...label,
|
||||||
|
name: label.name.trim(),
|
||||||
|
})),
|
||||||
|
},
|
||||||
|
null,
|
||||||
|
2,
|
||||||
|
) + "\n";
|
||||||
|
await saveDocument(this.workspace, labelsPath, source, expected);
|
||||||
|
this.load(parseLabels(source));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,78 @@
|
|||||||
|
// The legacy format: boards and task notes in visible Markdown files, and the root label file.
|
||||||
|
// The native feature reads only `.runestone/pm/`. When it opens a workspace that still has data in the legacy format,
|
||||||
|
// it offers the migration (`migrateStorage` in `migration.ts`), and it migrates only after the user chooses it.
|
||||||
|
import type { Workspace } from "../model/model.ts";
|
||||||
|
import { readCatalog } from "./catalog.ts";
|
||||||
|
import { cardPath } from "./cards.ts";
|
||||||
|
import { readDeletedCards } from "./deleted-cards.ts";
|
||||||
|
import { labelsPath, legacyLabelsPath } from "./labels.ts";
|
||||||
|
import { split } from "./notes.ts";
|
||||||
|
import { cardsFolder, readOptional } from "./persistence.ts";
|
||||||
|
import { markdownPaths, readSources } from "./scan.ts";
|
||||||
|
|
||||||
|
/** The legacy data that the migration has not copied to `.runestone/pm/` yet. */
|
||||||
|
export interface LegacyContent {
|
||||||
|
/** The paths of board notes. */
|
||||||
|
boards: string[];
|
||||||
|
/** The paths of task notes. */
|
||||||
|
cards: string[];
|
||||||
|
/** The paths of notes with invalid Project Management properties. The migration reports them. */
|
||||||
|
invalid: string[];
|
||||||
|
/** True when `runestone-pm-labels.json` exists and `.runestone/pm/labels.json` does not. */
|
||||||
|
labels: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The YAML properties at the start of a note, up to a line that starts with `runestone_pm:`. The closing line stops it. */
|
||||||
|
const properties = /^---[ \t]*\r?\n(?:(?!(?:---|\.\.\.)[ \t]*\r?\n)[^\n]*\n)*?runestone_pm[ \t]*:/;
|
||||||
|
|
||||||
|
/** True when the YAML properties of a note can contain Project Management data. It needs no YAML parse. */
|
||||||
|
export function mentionsProjectData(source: string): boolean {
|
||||||
|
return properties.test(source.charCodeAt(0) === 0xfeff ? source.slice(1) : source);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Find the legacy data of a workspace. Only notes that name `runestone_pm` in their properties get a YAML parse.
|
||||||
|
* A board or a card that the migration copied, or that the user deleted, does not count.
|
||||||
|
*/
|
||||||
|
export async function findLegacy(workspace: Workspace, check: () => void = () => {}): Promise<LegacyContent> {
|
||||||
|
const result: LegacyContent = { boards: [], cards: [], invalid: [], labels: false };
|
||||||
|
const paths = await markdownPaths(workspace, check);
|
||||||
|
const found: { path: string; kind: "board" | "task"; id: string }[] = [];
|
||||||
|
// One batch at a time, so the texts of all notes are never in memory together.
|
||||||
|
for (let offset = 0; offset < paths.length; offset += 64) {
|
||||||
|
const sources = await readSources(workspace, paths.slice(offset, offset + 64));
|
||||||
|
check();
|
||||||
|
for (const [path, file] of sources) {
|
||||||
|
if (file.source === undefined || !mentionsProjectData(file.source)) continue;
|
||||||
|
try {
|
||||||
|
const value = split(file.source).doc.toJS({ maxAliasCount: 50 }).runestone_pm;
|
||||||
|
if (value === undefined) continue;
|
||||||
|
if (!value || typeof value.id !== "string" || !value.id.trim() || (value.kind !== "board" && value.kind !== "task")) throw new Error("Invalid data.");
|
||||||
|
found.push({ path, kind: value.kind, id: value.id });
|
||||||
|
} catch { result.invalid.push(path); }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let saved = new Set<string>(), deletedBoards = new Set<string>(), deletedCards = new Set<string>();
|
||||||
|
try {
|
||||||
|
const catalog = await readCatalog(workspace);
|
||||||
|
saved = new Set(catalog.value.boards.map(board => board.value.id));
|
||||||
|
deletedBoards = new Set(catalog.value.deletedBoardIds ?? []);
|
||||||
|
} catch { /* The migration reports a damaged catalog. */ }
|
||||||
|
try { deletedCards = new Set((await readDeletedCards(workspace)).ids); } catch { /* The migration reports it. */ }
|
||||||
|
let cards = new Set<string>();
|
||||||
|
if (found.some(item => item.kind === "task")) {
|
||||||
|
try { cards = new Set((await workspace.list(cardsFolder)).map(entry => entry.rel_path)); } catch { /* No card folder yet. */ }
|
||||||
|
}
|
||||||
|
for (const item of found) {
|
||||||
|
if (item.kind === "board" && !saved.has(item.id) && !deletedBoards.has(item.id)) result.boards.push(item.path);
|
||||||
|
if (item.kind === "task" && !cards.has(cardPath(item.id)) && !deletedCards.has(item.id)) result.cards.push(item.path);
|
||||||
|
}
|
||||||
|
result.labels = (await readOptional(workspace, legacyLabelsPath)) !== null && (await readOptional(workspace, labelsPath)) === null;
|
||||||
|
for (const list of [result.boards, result.cards, result.invalid]) list.sort();
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** True when the workspace has legacy data to migrate. */
|
||||||
|
export function hasLegacy(content: LegacyContent): boolean {
|
||||||
|
return content.boards.length > 0 || content.cards.length > 0 || content.invalid.length > 0 || content.labels;
|
||||||
|
}
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
// The user-visible text of the storage code and the domain code. These folders use no host module, so the skill helper
|
||||||
|
// can bundle them for Node. `message()` marks a key of the host catalog (`src/lib/i18n/messages.ts`), and the catalog
|
||||||
|
// audit counts it. The text stays English here. The interface translates it with `localize()` (`../ui/text.ts`).
|
||||||
|
|
||||||
|
/** Mark a catalog key. It returns the text unchanged. */
|
||||||
|
export function message<T extends string>(text: T): T {
|
||||||
|
return text;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Put the values into the `{name}` placeholders of a catalog key. */
|
||||||
|
export function format(template: string, values: Record<string, string | number>): string {
|
||||||
|
return template.replace(/\{(\w+)\}/g, (match, key: string) => Object.hasOwn(values, key) ? String(values[key]) : match);
|
||||||
|
}
|
||||||
@@ -0,0 +1,151 @@
|
|||||||
|
import type { Workspace, Task } from "../model/model.ts";
|
||||||
|
import { migrateCards, readCards, cardOrigin } from "./cards.ts";
|
||||||
|
import type { BoardDocument } from "./board.ts";
|
||||||
|
import {
|
||||||
|
backupFile,
|
||||||
|
readCatalog,
|
||||||
|
writeCatalog,
|
||||||
|
isManagedBoard,
|
||||||
|
type OriginalFile,
|
||||||
|
} from "./catalog.ts";
|
||||||
|
import { labelsPath, legacyLabelsPath, parseLabels } from "./labels.ts";
|
||||||
|
import {
|
||||||
|
readOptional,
|
||||||
|
saveDocument,
|
||||||
|
ensurePrivateStorage,
|
||||||
|
} from "./persistence.ts";
|
||||||
|
import { format, message } from "./message.ts";
|
||||||
|
|
||||||
|
/** Retain originals until the user checks the boards and removes the listed files. */
|
||||||
|
export async function migrateStorage(
|
||||||
|
workspace: Workspace,
|
||||||
|
boards: BoardDocument[],
|
||||||
|
cards: Task[] = [],
|
||||||
|
) {
|
||||||
|
if (!workspace.readOptional || !workspace.create)
|
||||||
|
throw new Error(message("Update RuneStone before migrating Project Management storage."));
|
||||||
|
const snapshot = await readCatalog(workspace);
|
||||||
|
const legacy = boards.filter((board) => !isManagedBoard(board.path));
|
||||||
|
const legacyLabels = await readOptional(workspace, legacyLabelsPath);
|
||||||
|
const savedLabels = await readOptional(workspace, labelsPath);
|
||||||
|
if (legacyLabels !== null) parseLabels(legacyLabels);
|
||||||
|
if (savedLabels !== null) parseLabels(savedLabels);
|
||||||
|
// Validate every source before creating backups or publishing any changes.
|
||||||
|
for (const board of legacy) {
|
||||||
|
if (snapshot.value.deletedBoardIds?.includes(board.id))
|
||||||
|
throw new Error(message("This board was deleted. Refresh Project Management before migration."));
|
||||||
|
if ((await workspace.read(board.path)) !== board.source)
|
||||||
|
throw new Error(
|
||||||
|
format(message("The board changed: {path}. Refresh before migration."), { path: board.path }),
|
||||||
|
);
|
||||||
|
const existing = snapshot.value.boards.find(
|
||||||
|
(item) => item.value.id === board.id,
|
||||||
|
);
|
||||||
|
if (
|
||||||
|
existing &&
|
||||||
|
(existing.original?.path !== board.path ||
|
||||||
|
existing.original.source !== board.source)
|
||||||
|
)
|
||||||
|
throw new Error(
|
||||||
|
format(message("A different board already uses the ID from {path}."), { path: board.path }),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (legacyLabels !== null && savedLabels !== null) {
|
||||||
|
const original = JSON.parse(savedLabels).original;
|
||||||
|
if (
|
||||||
|
original?.path !== legacyLabelsPath ||
|
||||||
|
original?.source !== legacyLabels
|
||||||
|
)
|
||||||
|
throw new Error(message("Hidden labels and legacy labels both exist. Resolve their differences before migration."));
|
||||||
|
}
|
||||||
|
await ensurePrivateStorage(workspace);
|
||||||
|
let changed = false;
|
||||||
|
for (const board of legacy) {
|
||||||
|
if (snapshot.value.boards.some((item) => item.value.id === board.id))
|
||||||
|
continue;
|
||||||
|
const original = await backupFile(workspace, board.path, board.source);
|
||||||
|
snapshot.value.boards.push({
|
||||||
|
name: board.name,
|
||||||
|
value: board.value,
|
||||||
|
original,
|
||||||
|
});
|
||||||
|
changed = true;
|
||||||
|
}
|
||||||
|
const labelBackup =
|
||||||
|
legacyLabels !== null && savedLabels === null
|
||||||
|
? await backupFile(workspace, legacyLabelsPath, legacyLabels)
|
||||||
|
: undefined;
|
||||||
|
for (const board of legacy)
|
||||||
|
if ((await workspace.read(board.path)) !== board.source)
|
||||||
|
throw new Error(
|
||||||
|
format(message("The board changed: {path}. Refresh before migration."), { path: board.path }),
|
||||||
|
);
|
||||||
|
if (legacyLabels !== (await readOptional(workspace, legacyLabelsPath)))
|
||||||
|
throw new Error(message("Legacy labels changed. Refresh before migration."));
|
||||||
|
if (changed) await writeCatalog(workspace, snapshot.value, snapshot.source);
|
||||||
|
if (labelBackup) {
|
||||||
|
const source =
|
||||||
|
JSON.stringify(
|
||||||
|
{ ...JSON.parse(legacyLabels!), original: labelBackup },
|
||||||
|
null,
|
||||||
|
2,
|
||||||
|
) + "\n";
|
||||||
|
await saveDocument(workspace, labelsPath, source, null);
|
||||||
|
if ((await workspace.read(labelsPath)) !== source)
|
||||||
|
throw new Error(message("The saved label check failed. Retry migration."));
|
||||||
|
}
|
||||||
|
const saved = await readCatalog(workspace);
|
||||||
|
for (const board of legacy) {
|
||||||
|
const entry = saved.value.boards.find((item) => item.value.id === board.id);
|
||||||
|
const expected = snapshot.value.boards.find(
|
||||||
|
(item) => item.value.id === board.id,
|
||||||
|
);
|
||||||
|
if (
|
||||||
|
entry?.original?.source !== board.source ||
|
||||||
|
JSON.stringify(entry) !== JSON.stringify(expected)
|
||||||
|
)
|
||||||
|
throw new Error(message("The saved board check failed. Retry migration."));
|
||||||
|
}
|
||||||
|
await migrateCards(workspace, cards);
|
||||||
|
const files = await migrationFiles(workspace);
|
||||||
|
for (const file of files) {
|
||||||
|
if ((await workspace.read(file.backup)) !== file.source)
|
||||||
|
throw new Error(
|
||||||
|
format(message("The backup check failed for {path}. Keep the original."), { path: file.path }),
|
||||||
|
);
|
||||||
|
const current = await readOptional(workspace, file.path);
|
||||||
|
if (current !== null && current !== file.source)
|
||||||
|
throw new Error(
|
||||||
|
format(message("The original changed: {path}. Keep both versions."), { path: file.path }),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return files;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function migrationFiles(
|
||||||
|
workspace: Workspace,
|
||||||
|
): Promise<OriginalFile[]> {
|
||||||
|
const snapshot = await readCatalog(workspace);
|
||||||
|
const files = snapshot.value.boards.flatMap((board) =>
|
||||||
|
board.original ? [board.original] : [],
|
||||||
|
);
|
||||||
|
const labels = await readOptional(workspace, labelsPath);
|
||||||
|
if (labels !== null) {
|
||||||
|
parseLabels(labels);
|
||||||
|
const original = JSON.parse(labels).original;
|
||||||
|
if (
|
||||||
|
original &&
|
||||||
|
typeof original.path === "string" &&
|
||||||
|
typeof original.source === "string" &&
|
||||||
|
typeof original.backup === "string"
|
||||||
|
)
|
||||||
|
files.push(original);
|
||||||
|
}
|
||||||
|
const cards = await readCards(workspace);
|
||||||
|
if (cards.issues.length) throw new Error(cards.issues.join(" "));
|
||||||
|
for (const task of cards.tasks) {
|
||||||
|
const original = cardOrigin(task.source);
|
||||||
|
if (original) files.push(original);
|
||||||
|
}
|
||||||
|
return files;
|
||||||
|
}
|
||||||
@@ -0,0 +1,206 @@
|
|||||||
|
import { Document, isMap, parseDocument } from "yaml";
|
||||||
|
import { isHiddenCard } from "./persistence.ts";
|
||||||
|
import {
|
||||||
|
validateFields,
|
||||||
|
type Task,
|
||||||
|
type TaskFields,
|
||||||
|
type Status,
|
||||||
|
type Session,
|
||||||
|
} from "../model/model.ts";
|
||||||
|
import { message } from "./message.ts";
|
||||||
|
|
||||||
|
const frontmatter =
|
||||||
|
/^(\uFEFF?)(---[ \t]*\r?\n)([\s\S]*?)(\r?\n(?:---|\.\.\.)[ \t]*(?:\r?\n|$))/;
|
||||||
|
export function split(source: string) {
|
||||||
|
const match = frontmatter.exec(source);
|
||||||
|
if (!match && /^\uFEFF?---[ \t]*\r?\n/.test(source))
|
||||||
|
throw new Error(message("Close the YAML properties block before editing this note."));
|
||||||
|
const doc = match
|
||||||
|
? parseDocument(match[3], { uniqueKeys: true, keepSourceTokens: true })
|
||||||
|
: new Document({});
|
||||||
|
if (doc.errors.length || doc.warnings.length)
|
||||||
|
throw new Error(message("Fix invalid or unsupported YAML properties before editing this note."));
|
||||||
|
if (!isMap(doc.contents))
|
||||||
|
throw new Error(message("Note properties must be a YAML mapping."));
|
||||||
|
return {
|
||||||
|
match,
|
||||||
|
doc,
|
||||||
|
body: match ? source.slice(match[0].length) : source,
|
||||||
|
newline: source.includes("\r\n") ? "\r\n" : "\n",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
function record(value: unknown): value is Record<string, unknown> {
|
||||||
|
return value !== null && typeof value === "object" && !Array.isArray(value);
|
||||||
|
}
|
||||||
|
export function readTask(path: string, source: string): Task | null {
|
||||||
|
const { doc, body } = split(source);
|
||||||
|
const metadata = doc.toJS({ maxAliasCount: 50 });
|
||||||
|
const pm: unknown = metadata.runestone_pm;
|
||||||
|
if (pm === undefined) return null;
|
||||||
|
if (record(pm) && pm.kind === "board") return null;
|
||||||
|
if (
|
||||||
|
!record(pm) ||
|
||||||
|
pm.schema !== 1 ||
|
||||||
|
pm.kind !== "task" ||
|
||||||
|
typeof pm.id !== "string" ||
|
||||||
|
!pm.id.trim()
|
||||||
|
) {
|
||||||
|
throw new Error(message("This note has an unsupported Project Management schema, kind, or ID."));
|
||||||
|
}
|
||||||
|
if (pm.archived !== undefined && typeof pm.archived !== "boolean")
|
||||||
|
throw new Error(message("The archive state must be true or false."));
|
||||||
|
if (
|
||||||
|
pm.due !== undefined &&
|
||||||
|
(!record(pm.due) || typeof pm.due.date !== "string")
|
||||||
|
)
|
||||||
|
throw new Error(message("This preview supports date-only deadlines."));
|
||||||
|
if (
|
||||||
|
pm.plan !== undefined &&
|
||||||
|
(!record(pm.plan) ||
|
||||||
|
typeof pm.plan.start !== "string" ||
|
||||||
|
typeof pm.plan.end !== "string")
|
||||||
|
)
|
||||||
|
throw new Error(message("The plan needs a start and an exclusive end date."));
|
||||||
|
if (
|
||||||
|
pm.sessions !== undefined &&
|
||||||
|
(!Array.isArray(pm.sessions) ||
|
||||||
|
pm.sessions.some(
|
||||||
|
(value) =>
|
||||||
|
!record(value) ||
|
||||||
|
typeof value.id !== "string" ||
|
||||||
|
typeof value.start !== "string" ||
|
||||||
|
typeof value.end !== "string" ||
|
||||||
|
typeof value.timeZone !== "string",
|
||||||
|
))
|
||||||
|
) {
|
||||||
|
throw new Error(message("Sessions need an ID, start, end, and time zone."));
|
||||||
|
}
|
||||||
|
const task: Task = {
|
||||||
|
id: pm.id,
|
||||||
|
createdAt: pm.createdAt as string | undefined,
|
||||||
|
path,
|
||||||
|
title:
|
||||||
|
pm.title === undefined
|
||||||
|
? (isHiddenCard(path) &&
|
||||||
|
record(metadata.runestone_pm_origin) &&
|
||||||
|
typeof metadata.runestone_pm_origin.path === "string"
|
||||||
|
? metadata.runestone_pm_origin.path
|
||||||
|
: path
|
||||||
|
)
|
||||||
|
.split("/")
|
||||||
|
.at(-1)!
|
||||||
|
.replace(/\.(md|markdown|mdown)$/i, "")
|
||||||
|
: (pm.title as string),
|
||||||
|
order: pm.order as string | undefined,
|
||||||
|
body,
|
||||||
|
source,
|
||||||
|
status: pm.status as Status,
|
||||||
|
listId: pm.listId as string | null | undefined,
|
||||||
|
placements: pm.placements as Task["placements"],
|
||||||
|
tags: (pm.tags ?? []) as string[],
|
||||||
|
labels: pm.labels as Task["labels"],
|
||||||
|
priority: pm.priority as Task["priority"],
|
||||||
|
coverImage: pm.coverImage as Task["coverImage"],
|
||||||
|
attachments: pm.attachments as Task["attachments"],
|
||||||
|
subtasks: pm.subtasks as Task["subtasks"],
|
||||||
|
links: pm.links as Task["links"],
|
||||||
|
color: pm.color as Task["color"],
|
||||||
|
assignees: pm.assignees as Task["assignees"],
|
||||||
|
customFields: pm.customFields as Task["customFields"],
|
||||||
|
due: pm.due as Task["due"],
|
||||||
|
plan: pm.plan as Task["plan"],
|
||||||
|
sessions: (pm.sessions ?? []) as Session[],
|
||||||
|
archived: pm.archived === true,
|
||||||
|
};
|
||||||
|
validateFields({ ...task, title: pm.title as string | undefined });
|
||||||
|
return task;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Update individual YAML nodes so unknown keys and comments remain in the document.
|
||||||
|
export function editTask(
|
||||||
|
task: Task,
|
||||||
|
patch: Partial<TaskFields> & { body?: string },
|
||||||
|
): string {
|
||||||
|
const fields = { ...task, title: undefined, ...patch };
|
||||||
|
if (Object.hasOwn(patch, "createdAt") && patch.createdAt !== task.createdAt)
|
||||||
|
throw new Error(message("The card creation timestamp cannot change."));
|
||||||
|
validateFields(fields);
|
||||||
|
const { doc, match, newline } = split(task.source);
|
||||||
|
for (const key of [
|
||||||
|
"title",
|
||||||
|
"order",
|
||||||
|
"listId",
|
||||||
|
"placements",
|
||||||
|
"status",
|
||||||
|
"tags",
|
||||||
|
"labels",
|
||||||
|
"priority",
|
||||||
|
"coverImage",
|
||||||
|
"attachments",
|
||||||
|
"subtasks",
|
||||||
|
"links",
|
||||||
|
"color",
|
||||||
|
"assignees",
|
||||||
|
"customFields",
|
||||||
|
"due",
|
||||||
|
"plan",
|
||||||
|
"sessions",
|
||||||
|
"archived",
|
||||||
|
] as const) {
|
||||||
|
if (!Object.hasOwn(patch, key)) continue;
|
||||||
|
const value = patch[key];
|
||||||
|
if (value === undefined) {
|
||||||
|
doc.deleteIn(["runestone_pm", key]);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (key === "due" || key === "plan") {
|
||||||
|
for (const [name, child] of Object.entries(value as object))
|
||||||
|
doc.setIn(["runestone_pm", key, name], child);
|
||||||
|
} else doc.setIn(["runestone_pm", key], value);
|
||||||
|
}
|
||||||
|
const bom = match?.[1] ?? "";
|
||||||
|
const yaml = doc.toString({ lineWidth: 0 }).replaceAll("\n", newline);
|
||||||
|
const closing = match?.[4].replace(/^\r?\n/, "") ?? `---${newline}`;
|
||||||
|
return `${bom}---${newline}${yaml}${closing}${patch.body ?? task.body}`;
|
||||||
|
}
|
||||||
|
export function newTask(
|
||||||
|
title: string,
|
||||||
|
fields: TaskFields,
|
||||||
|
body = "",
|
||||||
|
id: string = crypto.randomUUID(),
|
||||||
|
): { path: string; source: string } {
|
||||||
|
title = title.trim();
|
||||||
|
if (
|
||||||
|
!title ||
|
||||||
|
title.length > 100 ||
|
||||||
|
/[<>:"/\\|?*\x00-\x1f]/.test(title) ||
|
||||||
|
/[. ]$/.test(title) ||
|
||||||
|
/^(con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(title)
|
||||||
|
)
|
||||||
|
throw new Error(message("Use a valid note name of 1 to 100 characters."));
|
||||||
|
validateFields(fields);
|
||||||
|
const doc = new Document({
|
||||||
|
runestone_pm: { schema: 1, id, kind: "task", ...fields, createdAt: fields.createdAt ?? new Date().toISOString() },
|
||||||
|
});
|
||||||
|
return {
|
||||||
|
path: `Projects/Inbox/${title}.md`,
|
||||||
|
source: `---\n${doc.toString({ lineWidth: 0 })}---\n${body}`,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
export function adoptNote(path: string, source: string): string {
|
||||||
|
if (readTask(path, source)) return source;
|
||||||
|
const { doc, body, match, newline } = split(source);
|
||||||
|
if (doc.has("runestone_pm"))
|
||||||
|
throw new Error(message("This document already contains Project Management data and cannot become a task."));
|
||||||
|
doc.set("runestone_pm", {
|
||||||
|
schema: 1,
|
||||||
|
id: crypto.randomUUID(),
|
||||||
|
kind: "task",
|
||||||
|
createdAt: new Date().toISOString(),
|
||||||
|
status: "todo",
|
||||||
|
tags: [],
|
||||||
|
sessions: [],
|
||||||
|
archived: false,
|
||||||
|
});
|
||||||
|
return `${match?.[1] ?? ""}---${newline}${doc.toString({ lineWidth: 0 }).replaceAll("\n", newline)}---${newline}${body}`;
|
||||||
|
}
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
import type { Task } from "../model/model.ts";
|
||||||
|
import { message } from "./message.ts";
|
||||||
|
|
||||||
|
const digits = "0123456789abcdefghijklmnopqrstuvwxyz";
|
||||||
|
const encode = (text: string) =>
|
||||||
|
text
|
||||||
|
.split("")
|
||||||
|
.map((char) => char.charCodeAt(0).toString(16).padStart(4, "0"))
|
||||||
|
.join("");
|
||||||
|
|
||||||
|
export function cardOrder(task: Task, boardId?: string): string {
|
||||||
|
const saved = boardId ? task.placements?.[boardId]?.order : task.order;
|
||||||
|
// Old notes keep filename order. Title edits do not change their positions.
|
||||||
|
const position = saved ?? legacyPosition(task.path);
|
||||||
|
// The ID breaks ties when separate windows choose the same position.
|
||||||
|
return position + "i" + encode(task.id) + "8";
|
||||||
|
}
|
||||||
|
|
||||||
|
export function legacyPosition(path: string): string {
|
||||||
|
return encode(path.split("/").at(-1)!.toLowerCase()) + "0000" + encode(path);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function compareCards(a: Task, b: Task, boardId?: string): number {
|
||||||
|
const left = cardOrder(a, boardId),
|
||||||
|
right = cardOrder(b, boardId);
|
||||||
|
return left < right ? -1 : left > right ? 1 : 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function orderBetween(lower?: string, upper?: string): string {
|
||||||
|
if (lower !== undefined && upper !== undefined && lower >= upper)
|
||||||
|
throw new Error(message("The card order changed. Refresh the board."));
|
||||||
|
let result = "";
|
||||||
|
for (let index = 0; ; index++) {
|
||||||
|
const low =
|
||||||
|
index < (lower?.length ?? 0) ? digits.indexOf(lower![index]) : 0;
|
||||||
|
const high =
|
||||||
|
upper === undefined ? digits.length : digits.indexOf(upper[index]);
|
||||||
|
if (high - low > 1) return result + digits[Math.floor((low + high) / 2)];
|
||||||
|
result += digits[low];
|
||||||
|
if (low < high) upper = undefined;
|
||||||
|
}
|
||||||
|
}
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user