Translate Project Management and add its tests and guide

- Every interface string of Project Management goes through the catalog: 539 new rows with fr, ja, and zh-CN.
- Storage and model messages use a local message() marker and stay free of host imports. The interface translates them.
- A board renders again when the language changes. Dates use the interface language.
- Fix: the ribbon button waits for the feature switches at startup, and the settings code loads no feature module.
- Add six smoke tests: board state, cards, menus, drag and drop, views, and language.
- Add docs/guides/project-management.md and UI-060. Update the user, plugin, SDK, host, development, and interface docs and CLAUDE.md.
- Name the fake board view of tree/renameUndo "Board fixture", because the native Project Management button is now in the ribbon.
This commit is contained in:
Knotty Wyvern
2026-10-29 21:53:09 -07:00
parent e66f089176
commit 956ead818b
53 changed files with 2510 additions and 867 deletions
+1 -1
View File
@@ -2,7 +2,7 @@
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, Background, Terminal, and PDF Viewer are native features with an off switch in Settings → Features (`src/lib/features/`). They do 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_CSV_Viewer`. 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.
+15
View File
@@ -1091,3 +1091,18 @@ Update 2026-10-29: The native Terminal feature keeps the 65% cap on `--rs-select
- 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/`. - 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. - 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. - 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.
+15 -8
View 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, the launch rules, the Background settings (`backgroundSettings.ts`), and one folder for each feature (`git/`, `background/`, `terminal/`). The main-bundle files of Terminal are `terminalKeys.ts`, `terminalSettings.ts`, `terminalHost.ts`, `TerminalHost.svelte`, and `TerminalSettings.svelte`. 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,12 +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, feature switches, Background, Terminal | `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). | | 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
@@ -136,15 +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, "background": true, "terminal": 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" }, "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 } "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`, `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). 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. |
@@ -209,7 +210,7 @@ Errors of the plugin API stay in English, because they are for plugin developers
## Native features ## Native features
Git, Background, Terminal, and PDF Viewer are native features: host code with an off switch in **Settings → Features**. They do 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 |
| --- | --- | | --- | --- |
@@ -229,6 +230,12 @@ Git, Background, Terminal, and PDF Viewer are native features: host code with an
- `@xterm/xterm` and `@xterm/addon-fit` are host dependencies. `pnpm check:features` keeps them out of the start chunks. - `@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. - 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. - `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. - [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. - 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. - Before Terminal goes off, Settings asks `pty_running` for the shells of all windows. Off closes the sessions of each window.
+168
View File
@@ -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.
+1 -1
View File
@@ -74,7 +74,7 @@ RuneStone keeps these settings in `.runestone-backgrounds.json` in the image fol
### Choose where the background shows ### Choose where the background shows
Under **Show the background in**, select **The workspace and new tabs**, **All Project Management boards**, or one board. Under **Show the background in**, select **The workspace and new tabs**, **All Project Management boards**, or one board.
The board list comes from the Project Management plugin of the current workspace. A saved board that is not available shows as **Unavailable board**, so that you can clear it. 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. A blank tab of a browser window also shows the background.
### Next and Pause ### Next and Pause
+11 -53
View File
@@ -13,7 +13,6 @@ This reference gives the package contract, the build procedure, and the API for
- [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)
- [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
@@ -223,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.
@@ -230,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,7 +265,6 @@ Older hosts ignore unknown fields in objects that you pass to the host, such as
| `completion` | yes | Autocomplete fields and providers. See the [completion API](completion.md). | | `completion` | yes | Autocomplete fields and providers. See the [completion API](completion.md). |
| `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
@@ -306,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
@@ -422,7 +421,7 @@ Do not call `invoke`, `listen`, or other `@tauri-apps/api` functions from a plug
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. 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. Make sure that an optional member exists before you use it.
The Project Management, Local Autocomplete, and CSV Viewer plugins make no native calls. The Local Autocomplete 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.
## Folder grants ## Folder grants
@@ -450,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.
@@ -464,51 +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, and read the frames of other owners.
Frames stay in the current window and do not change the saved appearance settings.
To read images from a folder outside the workspace, use [folder grants](#folder-grants).
| Method | Contract |
| --- | --- |
| `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. |
The folder methods of earlier hosts (`chooseFolder`, `defaultFolder`, `list`, `read`, `readImageSettings`, and `writeImageSettings`) are gone. The native Background feature replaced the Background Slideshow plugin that used them.
### 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: the native Background feature (`src/lib/features/background/index.ts`) sets frames from a local image folder through the host frames.
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 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.
+2 -2
View File
@@ -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, Background, Terminal, and PDF Viewer, 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. 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). 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
@@ -219,7 +219,7 @@ 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.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) |
+3 -3
View File
@@ -2,9 +2,9 @@
[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 Project Management 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, Git, Background, Terminal, and PDF Viewer are part of RuneStone and are not plugins. To turn Git, Background, Terminal, or PDF Viewer 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.
@@ -75,7 +75,6 @@ RuneStone uses the token for this request only and does not save it.
| Plugin | Guide | | Plugin | Guide |
| --- | --- | | --- | --- |
| Project Management | [Project Management guide](https://git.knottywyvern.com/kwyvern/RuneStone_PM/src/branch/main/project-management.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) |
| 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) |
@@ -95,6 +94,7 @@ RuneStone uses the token for this request only and does not save it.
| 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 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 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 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.
+1 -1
View File
@@ -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. |
+8 -6
View File
@@ -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.
@@ -175,12 +175,13 @@ Decisions: [UI-004](design-decisions.md#ui-004--detached-tab-work-area), [UI-039
- **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 settings section of an off feature shows one line that names Settings → Features. - 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. - **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), [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). 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
@@ -233,7 +234,7 @@ Decisions: [UI-010](design-decisions.md#ui-010--background-surface-visibility),
### 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.
@@ -292,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
+6 -3
View File
@@ -16,6 +16,7 @@ This guide explains how to work with files, documents, tabs, settings, and the b
| 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 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) |
@@ -221,22 +222,24 @@ Settings apply at once to all workspaces on this computer and update all open wi
| --- | --- | | --- | --- |
| General | Display language, **File name title**, **Keep line breaks**, **Table formulas**, **Show .runestone folder**, and auto-save | | General | Display language, **File name title**, **Keep line breaks**, **Table formulas**, **Show .runestone folder**, and auto-save |
| Appearance | Color theme, transparency, background (a folder slideshow or one 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, Background, Terminal, and PDF Viewer 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). | | 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, Background, Terminal, and PDF Viewer are built-in features 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, the terminal panel, or a PDF file. Background loads at the start only when you selected a folder or an image. - 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. - 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, 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. 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.
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. 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). 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. Settings → Plug-ins shows an old package as **Included with RuneStone**. You can uninstall it.
+1 -1
View File
@@ -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.files`, `api.backgrounds`, 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
@@ -6,27 +6,30 @@
--> -->
<script lang="ts"> <script lang="ts">
import { onDestroy, onMount } from "svelte"; import { onDestroy, onMount } from "svelte";
import { t } from "$lib/i18n"; import { message, t } from "$lib/i18n";
import Icon from "$lib/ui/Icon.svelte"; import Icon from "$lib/ui/Icon.svelte";
import { showActionMenu } from "$lib/ui/managedActionMenu"; import { showActionMenu } from "$lib/ui/managedActionMenu";
import { PRIORITY_LEVELS, onProjectManagementChange, readProjectManagement, writeProjectManagement, type PriorityLevels, type ProjectManagementSettings } from "./pmSettings"; import { PRIORITY_LEVELS, onProjectManagementChange, readProjectManagement, writeProjectManagement, type PriorityLevels, type ProjectManagementSettings } from "./pmSettings";
import { readBoardCatalog, writeDefaultBoard, type BoardSummary } from "./pmBoards"; import { readBoardCatalog, writeDefaultBoard, type BoardSummary } from "./pmBoards";
let { compact = false }: { compact?: boolean } = $props(); 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: "2 — High and Low", 3: "3 — High, Medium, and Low", 5: "5 — Highest through Lowest" }; 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 settings = $state<ProjectManagementSettings>(readProjectManagement());
let boards = $state<BoardSummary[]>([]); let boards = $state<BoardSummary[]>([]);
let defaultBoard = $state(""); let defaultBoard = $state("");
let boardsReady = $state(false); let boardsReady = $state(false);
let boardNote = $state(""); let boardNote = $state("");
let saving = $state(false); let saving = $state(false);
let message = $state(""); let notice = $state("");
let error = $state(""); let error = $state("");
let closeMenu = () => {}; let closeMenu = () => {};
let disposed = false; let disposed = false;
const active = $derived(boards.filter(board => !board.archived)); const active = $derived(boards.filter(board => !board.archived));
const boardName = $derived(defaultBoard ? active.find(board => board.id === defaultBoard)?.name ?? "Unavailable board (opens All tasks)" : "All tasks"); 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 }[]) { function picker(event: MouseEvent, label: string, choices: { label: string; checked: boolean; run: () => void }[]) {
closeMenu(); closeMenu();
@@ -39,15 +42,15 @@
function saveLevels(priorityLevels: PriorityLevels) { function saveLevels(priorityLevels: PriorityLevels) {
error = ""; error = "";
settings = { ...settings, priorityLevels }; settings = { ...settings, priorityLevels };
writeProjectManagement(settings).then(() => { message = $t("Changes saved."); }) writeProjectManagement(settings).then(() => { notice = $t("Changes saved."); })
.catch(() => { error = $t("Could not save these settings. Your previous settings still apply. Try again."); message = ""; settings = readProjectManagement(); }); .catch(() => { error = $t("Could not save these settings. Your previous settings still apply. Try again."); notice = ""; settings = readProjectManagement(); });
} }
async function saveDefault(id: string) { async function saveDefault(id: string) {
const previous = defaultBoard; const previous = defaultBoard;
error = ""; saving = true; defaultBoard = id; error = ""; saving = true; defaultBoard = id;
try { await writeDefaultBoard(id || null); if (!disposed) message = $t("Changes saved."); } try { await writeDefaultBoard(id || null); if (!disposed) notice = $t("Changes saved."); }
catch (reason) { if (!disposed) { defaultBoard = previous; message = ""; error = reason instanceof Error ? reason.message : String(reason); } } catch (reason) { if (!disposed) { defaultBoard = previous; notice = ""; error = errorText(reason); } }
finally { saving = false; } finally { saving = false; }
} }
@@ -60,7 +63,7 @@
boardsReady = true; boardsReady = true;
boardNote = ""; boardNote = "";
} catch (reason) { } catch (reason) {
if (!disposed) boardNote = /no workspace/i.test(String(reason)) ? "Open a workspace to choose its default board." : reason instanceof Error ? reason.message : String(reason); if (!disposed) boardNote = /no workspace/i.test(String(reason)) ? $t("Open a workspace to choose its default board.") : errorText(reason);
} }
} }
@@ -74,21 +77,21 @@
<div class="pm-settings"> <div class="pm-settings">
{#if !compact} {#if !compact}
<h2>{$t("Project Management")}</h2> <h2>{$t("Project Management")}</h2>
<p class="intro">The boards of each workspace stay in .runestone/pm in the workspace.</p> <p class="intro">{$t("The boards of each workspace stay in {folder} in the workspace.", { folder: ".runestone/pm" })}</p>
{/if} {/if}
<div class="card"> <div class="card">
<div class="setting-row"> <div class="setting-row">
<div><span class="name" id="pm-priority-label">Priority levels</span><p id="pm-priority-description">Existing card priorities stay unchanged when you change this setting.</p></div> <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="Priority levels" aria-describedby="pm-priority-description" aria-haspopup="menu" <button class="picker" type="button" aria-label={$t("Priority levels")} aria-describedby="pm-priority-description" aria-haspopup="menu"
onclick={event => picker(event, "Priority levels", PRIORITY_LEVELS.map(levels => ({ label: levelNames[levels], checked: settings.priorityLevels === levels, run: () => saveLevels(levels) })))}> onclick={event => picker(event, $t("Priority levels"), PRIORITY_LEVELS.map(levels => ({ label: $t(levelNames[levels]), checked: settings.priorityLevels === levels, run: () => saveLevels(levels) })))}>
{levelNames[settings.priorityLevels]}<Icon icon="chevron-down" /> {$t(levelNames[settings.priorityLevels])}<Icon icon="chevron-down" />
</button> </button>
</div> </div>
<div class="setting-row"> <div class="setting-row">
<div><span class="name" id="pm-default-label">Default board</span><p id="pm-default-description">{boardNote || "Choose the board that opens in this workspace. Restored tabs keep their board."}</p></div> <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="Default board" aria-describedby="pm-default-description" aria-haspopup="menu" disabled={!boardsReady || saving} <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, "Default board", [ onclick={event => picker(event, $t("Default board"), [
{ label: "All tasks", checked: !defaultBoard, run: () => void saveDefault("") }, { label: $t("All tasks"), checked: !defaultBoard, run: () => void saveDefault("") },
...active.map(board => ({ label: board.name, checked: defaultBoard === board.id, run: () => void saveDefault(board.id) })), ...active.map(board => ({ label: board.name, checked: defaultBoard === board.id, run: () => void saveDefault(board.id) })),
])}> ])}>
{boardName}<Icon icon="chevron-down" /> {boardName}<Icon icon="chevron-down" />
@@ -96,7 +99,7 @@
</div> </div>
</div> </div>
{#if error}<p class="error" role="alert">{error}</p>{/if} {#if error}<p class="error" role="alert">{error}</p>{/if}
<p class="saved" role="status">{message}</p> <p class="saved" role="status">{notice}</p>
</div> </div>
<style> <style>
+5 -4
View File
@@ -8,6 +8,7 @@ import type { FeatureContext, FeatureInstance } from "../types.ts";
import { boardKey, isManagedBoard, readCatalog } from "./storage/catalog.ts"; import { boardKey, isManagedBoard, readCatalog } from "./storage/catalog.ts";
import { findLegacy, hasLegacy, type LegacyContent } from "./storage/legacy.ts"; import { findLegacy, hasLegacy, type LegacyContent } from "./storage/legacy.ts";
import { isHiddenCard } from "./storage/persistence.ts"; import { isHiddenCard } from "./storage/persistence.ts";
import { message } from "./storage/message.ts";
import type { BoardReference } from "./storage/board.ts"; import type { BoardReference } from "./storage/board.ts";
import { TaskStore } from "./model/store.ts"; import { TaskStore } from "./model/store.ts";
import { hostMenus } from "./ui/host.ts"; import { hostMenus } from "./ui/host.ts";
@@ -45,7 +46,7 @@ export function start(context: FeatureContext): FeatureInstance {
if (fresh) legacy.delete(key); if (fresh) legacy.delete(key);
let pending = legacy.get(key); let pending = legacy.get(key);
if (!pending) { if (!pending) {
pending = findLegacy(workspace, () => { if (disposed) throw new Error("Project Management is off."); }); pending = findLegacy(workspace, () => { if (disposed) throw new Error(message("Project Management is off.")); });
pending.catch(() => legacy.delete(key)); pending.catch(() => legacy.delete(key));
legacy.set(key, pending); legacy.set(key, pending);
} }
@@ -67,7 +68,7 @@ export function start(context: FeatureContext): FeatureInstance {
const openBoard = async (path: string, from?: string) => { const openBoard = async (path: string, from?: string) => {
const snapshot = await readCatalog(workspace); const snapshot = await readCatalog(workspace);
const board = isManagedBoard(path) ? snapshot.value.boards.find(item => boardKey(item.value.id) === path) : undefined; const board = isManagedBoard(path) ? snapshot.value.boards.find(item => boardKey(item.value.id) === path) : undefined;
if (!board) throw new Error("This board is unavailable. Refresh Project Management."); if (!board) throw new Error(message("This board is unavailable. Refresh Project Management."));
const id = boardViewId(board.value.id); const id = boardViewId(board.value.id);
context.setViewTitle(id, board.name); context.setViewTitle(id, board.name);
if (from) context.replaceView(from, id); else context.openView(id); if (from) context.replaceView(from, id); else context.openView(id);
@@ -75,7 +76,7 @@ export function start(context: FeatureContext): FeatureInstance {
function mountView(view: string, element: HTMLElement) { function mountView(view: string, element: HTMLElement) {
const boardId = view === PLANNING ? null : boardOfView(view); const boardId = view === PLANNING ? null : boardOfView(view);
if (view !== PLANNING && !boardId) throw new Error("This view is unavailable."); if (view !== PLANNING && !boardId) throw new Error(message("This view is unavailable."));
const reference: BoardReference | undefined = boardId ? { id: boardId, path: boardKey(boardId) } : undefined; const reference: BoardReference | undefined = boardId ? { id: boardId, path: boardKey(boardId) } : undefined;
if (!states.has(view)) states.set(view, {}); if (!states.has(view)) states.set(view, {});
const store = new TaskStore(workspace, reference, { legacy: false }); const store = new TaskStore(workspace, reference, { legacy: false });
@@ -117,7 +118,7 @@ export function start(context: FeatureContext): FeatureInstance {
}, },
saveTabState: view => structuredClone(states.get(view) ?? {}), saveTabState: view => structuredClone(states.get(view) ?? {}),
restoreTabState(view, value) { restoreTabState(view, value) {
if (view !== PLANNING && !boardOfView(view)) throw new Error("This view is unavailable."); if (view !== PLANNING && !boardOfView(view)) throw new Error(message("This view is unavailable."));
states.set(view, parseViewState(value)); states.set(view, parseViewState(value));
persist(view); persist(view);
}, },
+2 -1
View File
@@ -1,5 +1,6 @@
import { defaultBoard, type BoardDocument, type BoardList } from "../storage/board.ts"; import { defaultBoard, type BoardDocument, type BoardList } from "../storage/board.ts";
import type { Task } from "./model.ts"; import type { Task } from "./model.ts";
import { message } from "../storage/message.ts";
export interface TaskColumn { export interface TaskColumn {
list?: BoardList; list?: BoardList;
@@ -64,7 +65,7 @@ export function allTaskGroups(boards: BoardDocument[], column: TaskColumn): Task
const key = JSON.stringify(boardIds); const key = JSON.stringify(boardIds);
let group = groups.get(key); let group = groups.get(key);
if (!group) { if (!group) {
group = { boardIds, name: owners.length ? owners.map(board => board.name).join(" · ") : "No active board", tasks: [] }; group = { boardIds, name: owners.length ? owners.map(board => board.name).join(" · ") : message("No active board"), tasks: [] };
groups.set(key, group); groups.set(key, group);
} }
group.tasks.push(task); group.tasks.push(task);
+35 -29
View File
@@ -1,3 +1,5 @@
import { message } from "../storage/message.ts";
export const statuses = ["todo", "doing", "done"] as const; export const statuses = ["todo", "doing", "done"] as const;
export type Status = (typeof statuses)[number]; export type Status = (typeof statuses)[number];
export const priorities = ["highest", "high", "medium", "low", "lowest"] as const; export const priorities = ["highest", "high", "medium", "low", "lowest"] as const;
@@ -6,11 +8,17 @@ export function availablePriorities(levels: PriorityLevels): readonly Priority[]
return levels === 2 ? ["high", "low"] : levels === 3 ? ["high", "medium", "low"] : priorities; return levels === 2 ? ["high", "low"] : levels === 3 ? ["high", "medium", "low"] : priorities;
} }
export type Priority = (typeof priorities)[number]; export type Priority = (typeof priorities)[number];
export const priorityNames: Record<Priority, string> = { highest: "Highest", high: "High", medium: "Medium", low: "Low", lowest: "Lowest" }; 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> = { export const statusNames: Record<Status, string> = {
todo: "To do", todo: message("To do"),
doing: "In progress", doing: message("In progress"),
done: "Done", done: message("Done"),
}; };
export const cardColors = { export const cardColors = {
red: "#df7373", red: "#df7373",
@@ -91,7 +99,7 @@ export function validDate(value: unknown): value is string {
return !isNaN(date.getTime()) && date.toISOString().slice(0, 10) === value; return !isNaN(date.getTime()) && date.toISOString().slice(0, 10) === value;
} }
export function addDays(value: string, days: number): string { export function addDays(value: string, days: number): string {
if (!validDate(value)) throw new Error("Enter a valid calendar date."); if (!validDate(value)) throw new Error(message("Enter a valid calendar date."));
const date = new Date(`${value}T12:00:00Z`); const date = new Date(`${value}T12:00:00Z`);
date.setUTCDate(date.getUTCDate() + days); date.setUTCDate(date.getUTCDate() + days);
return date.toISOString().slice(0, 10); return date.toISOString().slice(0, 10);
@@ -112,24 +120,24 @@ export function localTime(instant: string): string {
export function localInstant(value: string): string { export function localInstant(value: string): string {
const date = new Date(value); const date = new Date(value);
if (isNaN(date.getTime()) || localTime(date.toISOString()) !== value) if (isNaN(date.getTime()) || localTime(date.toISOString()) !== value)
throw new Error("Enter an existing local date and time."); throw new Error(message("Enter an existing local date and time."));
return date.toISOString(); return date.toISOString();
} }
export function validateFields(fields: TaskFields): void { export function validateFields(fields: TaskFields): void {
if (fields.createdAt !== undefined && (typeof fields.createdAt !== "string" || 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) || !/^\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)))) !validDate(fields.createdAt.slice(0, 10)) || !Number.isFinite(Date.parse(fields.createdAt))))
throw new Error("The card creation timestamp is invalid."); 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)) 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("Each image attachment needs a unique image ID and a name of 1 to 255 characters."); 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)) if (fields.priority !== undefined && fields.priority !== null && !priorities.includes(fields.priority))
throw new Error("Choose a supported priority or No 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)) if (fields.coverImage != null && !/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/.test(fields.coverImage))
throw new Error("Choose an image from this card."); 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)) 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("Each subtask needs a unique ID, a title, and a completion state."); 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)) 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("Choose each linked card once and select its relationship."); throw new Error(message("Choose each linked card once and select its relationship."));
if ( if (
fields.title !== undefined && fields.title !== undefined &&
(typeof fields.title !== "string" || (typeof fields.title !== "string" ||
@@ -137,19 +145,19 @@ export function validateFields(fields: TaskFields): void {
fields.title.length > 100 || fields.title.length > 100 ||
/[\x00-\x1f]/.test(fields.title)) /[\x00-\x1f]/.test(fields.title))
) )
throw new Error("Enter a card title of 1 to 100 characters."); throw new Error(message("Enter a card title of 1 to 100 characters."));
const validOrder = (value: unknown) => const validOrder = (value: unknown) =>
value === undefined || value === undefined ||
(typeof value === "string" && /^[0-9a-z]*[1-9a-z]$/.test(value)); (typeof value === "string" && /^[0-9a-z]*[1-9a-z]$/.test(value));
if (!validOrder(fields.order)) if (!validOrder(fields.order))
throw new Error("The card order is invalid. Refresh the board."); throw new Error(message("The card order is invalid. Refresh the board."));
if (fields.placements !== undefined) { if (fields.placements !== undefined) {
if ( if (
!fields.placements || !fields.placements ||
typeof fields.placements !== "object" || typeof fields.placements !== "object" ||
Array.isArray(fields.placements) Array.isArray(fields.placements)
) )
throw new Error("Board placements must be a mapping."); throw new Error(message("Board placements must be a mapping."));
for (const [id, placement] of Object.entries(fields.placements)) { for (const [id, placement] of Object.entries(fields.placements)) {
if ( if (
!id.trim() || !id.trim() ||
@@ -160,9 +168,7 @@ export function validateFields(fields: TaskFields): void {
(typeof placement.listId !== "string" || !placement.listId)) || (typeof placement.listId !== "string" || !placement.listId)) ||
!validOrder(placement.order) !validOrder(placement.order)
) )
throw new Error( throw new Error(message("Each board placement needs a board ID and a valid list ID."));
"Each board placement needs a board ID and a valid list ID.",
);
} }
} }
if ( if (
@@ -170,13 +176,13 @@ export function validateFields(fields: TaskFields): void {
(typeof fields.color !== "string" || (typeof fields.color !== "string" ||
!Object.hasOwn(cardColors, fields.color)) !Object.hasOwn(cardColors, fields.color))
) )
throw new Error("Choose a supported card color."); throw new Error(message("Choose a supported card color."));
if ( if (
fields.assignees !== undefined && fields.assignees !== undefined &&
(!Array.isArray(fields.assignees) || (!Array.isArray(fields.assignees) ||
fields.assignees.some((name) => typeof name !== "string" || !name.trim())) fields.assignees.some((name) => typeof name !== "string" || !name.trim()))
) )
throw new Error("Assignments must contain names."); throw new Error(message("Assignments must contain names."));
if (fields.customFields !== undefined) { if (fields.customFields !== undefined) {
if ( if (
!Array.isArray(fields.customFields) || !Array.isArray(fields.customFields) ||
@@ -188,26 +194,26 @@ export function validateFields(fields: TaskFields): void {
typeof field.value !== "string", typeof field.value !== "string",
) )
) )
throw new Error("Each custom field needs a name and a text value."); throw new Error(message("Each custom field needs a name and a text value."));
const names = fields.customFields.map((field) => const names = fields.customFields.map((field) =>
field.name.trim().toLocaleLowerCase(), field.name.trim().toLocaleLowerCase(),
); );
if (new Set(names).size !== names.length) if (new Set(names).size !== names.length)
throw new Error("Use a different name for each custom field."); throw new Error(message("Use a different name for each custom field."));
} }
if ( if (
fields.listId !== undefined && fields.listId !== undefined &&
fields.listId !== null && fields.listId !== null &&
(typeof fields.listId !== "string" || !fields.listId) (typeof fields.listId !== "string" || !fields.listId)
) )
throw new Error("The task has an invalid list ID."); throw new Error(message("The task has an invalid list ID."));
if (!statuses.includes(fields.status)) if (!statuses.includes(fields.status))
throw new Error("Choose a supported task status."); throw new Error(message("Choose a supported task status."));
if ( if (
!Array.isArray(fields.tags) || !Array.isArray(fields.tags) ||
fields.tags.some((tag) => typeof tag !== "string") fields.tags.some((tag) => typeof tag !== "string")
) )
throw new Error("Tags must be text."); throw new Error(message("Tags must be text."));
if ( if (
fields.labels !== undefined && fields.labels !== undefined &&
(!Array.isArray(fields.labels) || (!Array.isArray(fields.labels) ||
@@ -216,16 +222,16 @@ export function validateFields(fields: TaskFields): void {
) || ) ||
new Set(fields.labels).size !== fields.labels.length) new Set(fields.labels).size !== fields.labels.length)
) )
throw new Error("Labels must contain unique saved label IDs."); throw new Error(message("Labels must contain unique saved label IDs."));
if (fields.due && !validDate(fields.due.date)) if (fields.due && !validDate(fields.due.date))
throw new Error("Enter a valid deadline date."); throw new Error(message("Enter a valid deadline date."));
if ( if (
fields.plan && fields.plan &&
(!validDate(fields.plan.start) || (!validDate(fields.plan.start) ||
!validDate(fields.plan.end) || !validDate(fields.plan.end) ||
fields.plan.end <= fields.plan.start) fields.plan.end <= fields.plan.start)
) { ) {
throw new Error("The planned end must follow the start."); throw new Error(message("The planned end must follow the start."));
} }
const ids = new Set<string>(); const ids = new Set<string>();
for (const session of fields.sessions) { for (const session of fields.sessions) {
@@ -242,7 +248,7 @@ export function validateFields(fields: TaskFields): void {
!Number.isFinite(Date.parse(session.end)) || !Number.isFinite(Date.parse(session.end)) ||
Date.parse(session.end) <= Date.parse(session.start) Date.parse(session.end) <= Date.parse(session.start)
) )
throw new Error("Each session needs a unique ID and a valid time range."); throw new Error(message("Each session needs a unique ID and a valid time range."));
new Intl.DateTimeFormat("en", { timeZone: session.timeZone }).format(); new Intl.DateTimeFormat("en", { timeZone: session.timeZone }).format();
ids.add(session.id); ids.add(session.id);
} }
+82 -104
View File
@@ -1,5 +1,5 @@
import { readTask, editTask, adoptNote, split } from "../storage/notes.ts"; import { readTask, editTask, adoptNote, split } from "../storage/notes.ts";
import { createCard, readCards, cardOrigin, cardPath, migrateCards, parseCard, prepareCards } from "../storage/cards.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 { cardsFolder, cardsMarker, isHiddenCard, readOptional, saveDocument, storageRoot } from "../storage/persistence.ts";
import { deletedCardsPath, readDeletedCards, recordCardDeletion } from "../storage/deleted-cards.ts"; import { deletedCardsPath, readDeletedCards, recordCardDeletion } from "../storage/deleted-cards.ts";
import { mapConcurrent, markdownPaths, readSources } from "../storage/scan.ts"; import { mapConcurrent, markdownPaths, readSources } from "../storage/scan.ts";
@@ -14,6 +14,7 @@ import {
createBoard, createBoard,
} from "../storage/catalog.ts"; } from "../storage/catalog.ts";
import { migrateStorage } from "../storage/migration.ts"; import { migrateStorage } from "../storage/migration.ts";
import { format, message } from "../storage/message.ts";
import { import {
BoardStore, BoardStore,
boardDocument, boardDocument,
@@ -32,7 +33,10 @@ export interface TaskStoreOptions {
legacy?: boolean; legacy?: boolean;
} }
const message = (error: unknown) => error instanceof Error ? error.message : String(error); 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. */ /** The files of `.runestone/pm/` that the hidden mode reads, with the problem of each file. */
interface HiddenState { interface HiddenState {
@@ -78,7 +82,7 @@ export class TaskStore {
} }
private check() { private check() {
if (this.disposed) if (this.disposed)
throw new Error("The Project Management view is closed. Reopen it before saving."); throw new Error(message("The Project Management view is closed. Reopen it before saving."));
} }
/** Read all Project Management data again. */ /** Read all Project Management data again. */
async reload(): Promise<void> { async reload(): Promise<void> {
@@ -99,7 +103,7 @@ export class TaskStore {
for (const path of paths) this.acceptCard(state, path, sources.get(path)!, previous.get(path)); for (const path of paths) this.acceptCard(state, path, sources.get(path)!, previous.get(path));
} }
} catch (error) { } catch (error) {
state.cardsError = message(error); state.cardsError = errorMessage(error);
} }
await Promise.all([this.readHiddenCatalog(state), this.readHiddenLabels(state), this.readHiddenDeleted(state)]); await Promise.all([this.readHiddenCatalog(state), this.readHiddenLabels(state), this.readHiddenDeleted(state)]);
this.check(); this.check();
@@ -148,12 +152,12 @@ export class TaskStore {
} }
private acceptCard(state: HiddenState, path: string, result: { source?: string; error?: string }, cached?: Task) { private acceptCard(state: HiddenState, path: string, result: { source?: string; error?: string }, cached?: Task) {
try { try {
if (result.error || result.source === undefined) throw new Error(result.error ?? "The card is unavailable."); 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.cards.set(path, cached?.source === result.source ? cached : parseCard(path, result.source));
state.cardIssues.delete(path); state.cardIssues.delete(path);
} catch (error) { } catch (error) {
state.cards.delete(path); state.cards.delete(path);
state.cardIssues.set(path, message(error)); state.cardIssues.set(path, errorMessage(error));
} }
} }
private async readHiddenCatalog(state: HiddenState) { private async readHiddenCatalog(state: HiddenState) {
@@ -162,25 +166,25 @@ export class TaskStore {
state.catalog = { source: catalog.source, boards: managedDocuments(catalog.value, catalog.source ?? ""), error: "" }; state.catalog = { source: catalog.source, boards: managedDocuments(catalog.value, catalog.source ?? ""), error: "" };
} catch (error) { } catch (error) {
// Do not expose boards as writable when hidden storage cannot be read. // Do not expose boards as writable when hidden storage cannot be read.
state.catalog = { source: null, boards: [], error: message(error) }; state.catalog = { source: null, boards: [], error: errorMessage(error) };
} }
} }
private async readHiddenLabels(state: HiddenState) { private async readHiddenLabels(state: HiddenState) {
try { state.labels = { snapshot: await this.labels.read(), error: "" }; } try { state.labels = { snapshot: await this.labels.read(), error: "" }; }
catch (error) { state.labels = { error: message(error) }; } catch (error) { state.labels = { error: errorMessage(error) }; }
} }
private async readHiddenDeleted(state: HiddenState) { private async readHiddenDeleted(state: HiddenState) {
try { state.deleted = { ids: new Set((await readDeletedCards(this.workspace)).ids), error: "" }; } try { state.deleted = { ids: new Set((await readDeletedCards(this.workspace)).ids), error: "" }; }
catch (error) { state.deleted = { ids: new Set(), error: message(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. */ /** Make the public fields from the hidden files. One invalid card file hides all cards, as in the legacy mode. */
private publishHidden() { private publishHidden() {
const state = this.hidden!; const state = this.hidden!;
const issues: string[] = [...[...state.cardIssues].map(([path, issue]) => `${path}: ${issue}`)]; const issues: string[] = [...[...state.cardIssues].map(([path, issue]) => fileIssue(path, issue))];
if (state.cardsError) issues.push("Hidden cards: " + state.cardsError); if (state.cardsError) issues.push(format(message("Hidden cards: {error}"), { error: state.cardsError }));
if (state.catalog.error) issues.push("Hidden Project Management storage: " + state.catalog.error); if (state.catalog.error) issues.push(format(message("Hidden Project Management storage: {error}"), { error: state.catalog.error }));
if (state.labels.error) issues.push("Saved labels: " + state.labels.error); if (state.labels.error) issues.push(format(message("Saved labels: {error}"), { error: state.labels.error }));
if (state.deleted.error) issues.push("Deleted cards: " + state.deleted.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); this.labels.load(state.labels.snapshot, state.labels.error);
const blocked = !!(state.cardsError || state.cardIssues.size || state.deleted.error); const blocked = !!(state.cardsError || state.cardIssues.size || state.deleted.error);
this.tasks = blocked ? [] : [...state.cards.values()] this.tasks = blocked ? [] : [...state.cards.values()]
@@ -191,7 +195,7 @@ export class TaskStore {
if (this.board.reference) { if (this.board.reference) {
this.board.load(this.boards.find((board) => board.id === this.board.reference!.id)); this.board.load(this.boards.find((board) => board.id === this.board.reference!.id));
if (!this.board.available) if (!this.board.available)
issues.push("This board is missing, invalid, or duplicated. Task notes remain available in All tasks."); issues.push(message("This board is missing, invalid, or duplicated. Task notes remain available in All tasks."));
} }
this.issues = issues; this.issues = issues;
workspaceTasks.set(this.workspace, this.tasks); workspaceTasks.set(this.workspace, this.tasks);
@@ -210,16 +214,14 @@ export class TaskStore {
this.check(); this.check();
try { try {
const result = sources.get(path)!; const result = sources.get(path)!;
if (result.error || result.source === undefined) throw new Error(result.error ?? "The file is unavailable."); if (result.error || result.source === undefined) throw new Error(result.error ?? message("The file is unavailable."));
const source = result.source; const source = result.source;
const cached = previous.get(path); const cached = previous.get(path);
if (cached?.source === source) return { task: cached }; if (cached?.source === source) return { task: cached };
const board = boardDocument(source, path); const board = boardDocument(source, path);
return board ? { board } : { task: readTask(path, source) }; return board ? { board } : { task: readTask(path, source) };
} catch (error) { } catch (error) {
return { return { issue: fileIssue(path, errorMessage(error)) };
issue: `${path}: ${error instanceof Error ? error.message : String(error)}`,
};
} }
}); });
for (const document of documents) { for (const document of documents) {
@@ -241,17 +243,15 @@ export class TaskStore {
) )
tasks.splice(tasks.indexOf(original), 1); tasks.splice(tasks.indexOf(original), 1);
else else
issues.push( issues.push(format(
`The original card differs from hidden storage: ${original.path}. Preserve both versions.`, message("The original card differs from hidden storage: {path}. Preserve both versions."),
); { path: original.path },
));
} }
} }
tasks.push(...hidden.tasks); tasks.push(...hidden.tasks);
} catch (error) { } catch (error) {
issues.push( issues.push(format(message("Hidden cards: {error}"), { error: errorMessage(error) }));
"Hidden cards: " +
(error instanceof Error ? error.message : String(error)),
);
// Block legacy edits when the hidden store cannot be checked for migrated IDs. // Block legacy edits when the hidden store cannot be checked for migrated IDs.
tasks.length = 0; tasks.length = 0;
} }
@@ -271,17 +271,15 @@ export class TaskStore {
) )
boards.splice(boards.indexOf(board), 1); boards.splice(boards.indexOf(board), 1);
else else
issues.push( issues.push(format(
`Legacy board differs from hidden storage: ${board.path}. Preserve both versions before cleanup.`, message("The legacy board differs from hidden storage: {path}. Preserve both versions before cleanup."),
); { path: board.path },
));
} }
} }
boards.push(...managedDocuments(catalog.value, catalog.source ?? "")); boards.push(...managedDocuments(catalog.value, catalog.source ?? ""));
} catch (error) { } catch (error) {
issues.push( issues.push(format(message("Hidden Project Management storage: {error}"), { error: errorMessage(error) }));
"Hidden Project Management storage: " +
(error instanceof Error ? error.message : String(error)),
);
// Do not expose legacy boards as writable when hidden storage cannot be read. // Do not expose legacy boards as writable when hidden storage cannot be read.
boards.length = 0; boards.length = 0;
} }
@@ -290,8 +288,8 @@ export class TaskStore {
try { try {
labels = await this.labels.read(); labels = await this.labels.read();
} catch (error) { } catch (error) {
labelError = error instanceof Error ? error.message : String(error); labelError = errorMessage(error);
issues.push("Saved labels: " + labelError); issues.push(format(message("Saved labels: {error}"), { error: labelError }));
} }
this.check(); this.check();
if (revision !== this.revision) return; if (revision !== this.revision) return;
@@ -301,14 +299,11 @@ export class TaskStore {
for (const task of tasks) for (const task of tasks)
counts.set(task.id, (counts.get(task.id) ?? 0) + 1); counts.set(task.id, (counts.get(task.id) ?? 0) + 1);
for (const [id, count] of counts) for (const [id, count] of counts)
if (count > 1) if (count > 1) issues.push(duplicateTaskIssue(id));
issues.push(
`Duplicate task ID ${id}: resolve the copied notes before editing them.`,
);
let deletedIds = new Set<string>(); let deletedIds = new Set<string>();
try { deletedIds = new Set((await readDeletedCards(this.workspace)).ids); } try { deletedIds = new Set((await readDeletedCards(this.workspace)).ids); }
catch (error) { catch (error) {
issues.push("Deleted cards: " + (error instanceof Error ? error.message : String(error))); issues.push(format(message("Deleted cards: {error}"), { error: errorMessage(error) }));
tasks.length = 0; tasks.length = 0;
} }
this.check(); this.check();
@@ -321,9 +316,7 @@ export class TaskStore {
boardCounts.set(board.id, (boardCounts.get(board.id) ?? 0) + 1); boardCounts.set(board.id, (boardCounts.get(board.id) ?? 0) + 1);
for (const [id, count] of boardCounts) for (const [id, count] of boardCounts)
if (count > 1) if (count > 1)
issues.push( issues.push(format(message("Duplicate board ID {id}: resolve the copied boards before editing them."), { id }));
`Duplicate board ID ${id}: resolve the copied boards before editing them.`,
);
this.boards = boards this.boards = boards
.filter((board) => boardCounts.get(board.id) === 1) .filter((board) => boardCounts.get(board.id) === 1)
.sort((a, b) => a.name.localeCompare(b.name)); .sort((a, b) => a.name.localeCompare(b.name));
@@ -332,9 +325,7 @@ export class TaskStore {
this.boards.find((board) => board.id === this.board.reference!.id), this.boards.find((board) => board.id === this.board.reference!.id),
); );
if (!this.board.available) if (!this.board.available)
issues.push( issues.push(message("This board is missing, invalid, or duplicated. Task notes remain available in All tasks."));
"This board is missing, invalid, or duplicated. Task notes remain available in All tasks.",
);
} }
this.issues = issues; this.issues = issues;
workspaceTasks.set(this.workspace, this.tasks); workspaceTasks.set(this.workspace, this.tasks);
@@ -360,7 +351,7 @@ export class TaskStore {
await this.reloadFor([task.path]); await this.reloadFor([task.path]);
const current = this.tasks.find(item => item.id === task.id && item.path === task.path); const current = this.tasks.find(item => item.id === task.id && item.path === task.path);
if (!current || current.source !== task.source) if (!current || current.source !== task.source)
throw new Error("The card changed or is unavailable. Refresh before deleting it."); throw new Error(message("The card changed or is unavailable. Refresh before deleting it."));
await recordCardDeletion(this.workspace, task.id); await recordCardDeletion(this.workspace, task.id);
await this.reloadFor([deletedCardsPath]); await this.reloadFor([deletedCardsPath]);
}); });
@@ -373,7 +364,7 @@ export class TaskStore {
const found = this.tasks.find(task => task.id === source.id && task.path === source.path); 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.links?.some(link => link.taskId === targetId)) return undefined;
if (!found || found.source !== source.source) if (!found || found.source !== source.source)
throw new Error("A linked card changed. Refresh before removing its link."); throw new Error(message("A linked card changed. Refresh before removing its link."));
return found; return found;
}); });
for (const source of current) { for (const source of current) {
@@ -395,17 +386,15 @@ export class TaskStore {
(item) => item.id === task.id && item.path === task.path, (item) => item.id === task.id && item.path === task.path,
); );
if (!current || current.source !== task.source) if (!current || current.source !== task.source)
throw new Error( throw new Error(message("The task changed or has a duplicate ID. Cancel, refresh, and review the note before saving."));
"The task changed or has a duplicate ID. Cancel, refresh, and review the note before saving.",
);
const next = { ...patch }; const next = { ...patch };
if (Object.hasOwn(next, "listId")) { if (Object.hasOwn(next, "listId")) {
if (this.board.archived) if (this.board.archived)
throw new Error("Restore this board before moving cards."); throw new Error(message("Restore this board before moving cards."));
const listId = next.listId ?? null; const listId = next.listId ?? null;
const list = this.board.value.lists.find((list) => list.id === listId); const list = this.board.value.lists.find((list) => list.id === listId);
if (listId !== null && !list) if (listId !== null && !list)
throw new Error("This list no longer exists. Refresh the board."); throw new Error(message("This list no longer exists. Refresh the board."));
const previousList = this.board.listFor(task); const previousList = this.board.listFor(task);
if (applyListStatus && listId !== (previousList?.id ?? null)) { if (applyListStatus && listId !== (previousList?.id ?? null)) {
if (list?.status) next.status = list.status; if (list?.status) next.status = list.status;
@@ -414,7 +403,7 @@ export class TaskStore {
const id = this.board.reference?.id; const id = this.board.reference?.id;
if (id) { if (id) {
if (!this.board.available) if (!this.board.available)
throw new Error("The board is unavailable. Reopen it before saving."); throw new Error(message("The board is unavailable. Reopen it before saving."));
const placement = { ...task.placements?.[id], listId }; const placement = { ...task.placements?.[id], listId };
if ( if (
listId !== (this.board.listFor(task)?.id ?? null) || listId !== (this.board.listFor(task)?.id ?? null) ||
@@ -491,9 +480,9 @@ export class TaskStore {
return this.run(async () => { return this.run(async () => {
await this.reloadFor(this.cardsInList(listId).map(task => task.path)); await this.reloadFor(this.cardsInList(listId).map(task => task.path));
if (!this.board.editable || !this.board.value.lists.some((list) => list.id === listId)) if (!this.board.editable || !this.board.value.lists.some((list) => list.id === listId))
throw new Error("The list is unavailable. Refresh the board."); throw new Error(message("The list is unavailable. Refresh the board."));
if (this.issues.length) if (this.issues.length)
throw new Error("Resolve workspace issues before archiving cards: " + this.issues.join(" ")); throw new Error(format(message("Resolve workspace issues before archiving cards: {issues}"), { issues: this.issues.join(" ") }));
for (const task of this.cardsInList(listId)) { for (const task of this.cardsInList(listId)) {
const source = editTask(task, { archived: true }); const source = editTask(task, { archived: true });
await saveDocument(this.workspace, task.path, source, task.source); await saveDocument(this.workspace, task.path, source, task.source);
@@ -513,7 +502,7 @@ export class TaskStore {
beforeId == null beforeId == null
? cards.length ? cards.length
: cards.findIndex((card) => card.id === beforeId); : cards.findIndex((card) => card.id === beforeId);
if (index < 0) throw new Error("The target card moved. Refresh the board."); if (index < 0) throw new Error(message("The target card moved. Refresh the board."));
const id = this.board.reference?.id; const id = this.board.reference?.id;
return orderBetween( return orderBetween(
index > 0 ? cardOrder(cards[index - 1], id) : undefined, index > 0 ? cardOrder(cards[index - 1], id) : undefined,
@@ -524,30 +513,28 @@ export class TaskStore {
const path = title.trim().replaceAll("\\", "/").replace(/^\.\//, ""); const path = title.trim().replaceAll("\\", "/").replace(/^\.\//, "");
if (!/\.(md|markdown|mdown)$/i.test(path)) return this.create(title, fields, ""); 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 === "..")) if (/^(?:[a-z]+:|\/)/i.test(path) || path.split("/").some(part => !part || part === "." || part === ".."))
throw new Error("Use a relative Markdown path inside this workspace."); throw new Error(message("Use a relative Markdown path inside this workspace."));
const added = await this.adopt(path); const added = await this.adopt(path);
const task = this.tasks.find(item => item.id === added.id && item.path === added.path); const task = this.tasks.find(item => item.id === added.id && item.path === added.path);
if (!task) throw new Error("The linked card is unavailable. Refresh the board."); 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); if (this.board.reference) await this.moveTask(task, fields.listId ?? null);
} }
create(title: string, fields: TaskFields, body: string, destinationId?: string): Promise<void> { create(title: string, fields: TaskFields, body: string, destinationId?: string): Promise<void> {
return this.run(async () => { return this.run(async () => {
if (!this.workspace.create) if (!this.workspace.create)
throw new Error( throw new Error(message("This RuneStone version cannot create plugin notes. Add an existing note or install the host bridge."));
"This RuneStone version cannot create plugin notes. Add an existing note or install the host bridge.",
);
if (!this.loaded) await this.reload(); if (!this.loaded) await this.reload();
++this.revision; ++this.revision;
if (destinationId !== undefined) await this.reloadFor([catalogPath]); if (destinationId !== undefined) await this.reloadFor([catalogPath]);
const destination = destinationId === undefined ? undefined : this.boards.find(board => board.id === destinationId && !board.archived); const destination = destinationId === undefined ? undefined : this.boards.find(board => board.id === destinationId && !board.archived);
if (destinationId !== undefined && !destination) throw new Error("Choose an available, active board for this card."); if (destinationId !== undefined && !destination) throw new Error(message("Choose an available, active board for this card."));
const id = destination?.id ?? this.board.reference?.id; const id = destination?.id ?? this.board.reference?.id;
if (id && !destination && !this.board.available) if (id && !destination && !this.board.available)
throw new Error("The board is unavailable. Reopen it before saving."); throw new Error(message("The board is unavailable. Reopen it before saving."));
// Named-board creation reads the current board without a workspace scan. // Named-board creation reads the current board without a workspace scan.
await this.board.reload(); await this.board.reload();
if (this.board.archived) if (this.board.archived)
throw new Error("Restore this board before adding cards."); throw new Error(message("Restore this board before adding cards."));
const targetBoard = destination?.value ?? this.board.value; const targetBoard = destination?.value ?? this.board.value;
const listId = const listId =
fields.listId === undefined fields.listId === undefined
@@ -558,7 +545,7 @@ export class TaskStore {
listId !== null && listId !== null &&
!targetBoard.lists.some((list) => list.id === listId) !targetBoard.lists.some((list) => list.id === listId)
) )
throw new Error("This list no longer exists. Refresh the board."); throw new Error(message("This list no longer exists. Refresh the board."));
const lastGlobalCard = this.tasks const lastGlobalCard = this.tasks
.filter( .filter(
(task) => (task) =>
@@ -602,10 +589,10 @@ export class TaskStore {
await this.reloadFor([cardPath(parentId)]); await this.reloadFor([cardPath(parentId)]);
const parent = this.tasks.find(task => task.id === parentId); const parent = this.tasks.find(task => task.id === parentId);
const item = parent?.subtasks?.find(item => item.id === subtaskId); const item = parent?.subtasks?.find(item => item.id === subtaskId);
if (!parent || !item) throw new Error("The subtask is unavailable. Refresh the board."); if (!parent || !item) throw new Error(message("The subtask is unavailable. Refresh the board."));
if (item.taskId) { if (item.taskId) {
const target = this.tasks.find(task => task.id === item.taskId); const target = this.tasks.find(task => task.id === item.taskId);
if (!target) throw new Error("The subtask card is unavailable. Refresh the board."); if (!target) throw new Error(message("The subtask card is unavailable. Refresh the board."));
return target; return target;
} }
// A stable ID lets a retry recover after the child saves but the parent fails. // A stable ID lets a retry recover after the child saves but the parent fails.
@@ -637,7 +624,7 @@ export class TaskStore {
removeFromBoard(task: Task): Promise<void> { removeFromBoard(task: Task): Promise<void> {
const id = this.board.reference?.id; const id = this.board.reference?.id;
if (!id) if (!id)
return Promise.reject(new Error("Open a board before removing a card.")); return Promise.reject(new Error(message("Open a board before removing a card.")));
const placements = { ...task.placements }; const placements = { ...task.placements };
delete placements[id]; delete placements[id];
return this.save(task, { placements }); return this.save(task, { placements });
@@ -647,8 +634,8 @@ export class TaskStore {
await this.reloadFor([task.path]); await this.reloadFor([task.path]);
const destination = this.boards.find(board => board.id === destinationId); const destination = this.boards.find(board => board.id === destinationId);
if (!destination || destination.archived || (listId !== null && !destination.value.lists.some(list => list.id === listId))) if (!destination || destination.archived || (listId !== null && !destination.value.lists.some(list => list.id === listId)))
throw new Error("The destination board or list is unavailable. Refresh the board."); 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("Open an available, active board before moving a card."); 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 }; const placements = { ...task.placements };
if (this.board.reference) delete placements[this.board.reference.id]; 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); const last = this.tasks.filter(item => item.id !== task.id && item.placements?.[destinationId]?.listId === listId).sort((a, b) => compareCards(a, b, destinationId)).at(-1);
@@ -669,21 +656,21 @@ export class TaskStore {
await this.reloadFor([task.path]); await this.reloadFor([task.path]);
const sourceId = this.board.reference?.id; const sourceId = this.board.reference?.id;
if (!sourceId || !this.board.available || this.board.archived) if (!sourceId || !this.board.available || this.board.archived)
throw new Error("Open an available, active board before moving a card."); throw new Error(message("Open an available, active board before moving a card."));
const current = this.tasks.find( const current = this.tasks.find(
(item) => item.id === task.id && item.path === task.path, (item) => item.id === task.id && item.path === task.path,
); );
if (!current || current.source !== task.source) if (!current || current.source !== task.source)
throw new Error("The card changed. Cancel, refresh, and review it before moving."); throw new Error(message("The card changed. Cancel, refresh, and review it before moving."));
if (!Object.hasOwn(current.placements ?? {}, sourceId)) if (!Object.hasOwn(current.placements ?? {}, sourceId))
throw new Error("This card no longer belongs to the source board."); throw new Error(message("This card no longer belongs to the source board."));
if (sourceId === destinationId) if (sourceId === destinationId)
throw new Error("Choose a different destination board."); throw new Error(message("Choose a different destination board."));
const destination = this.boards.find((board) => board.id === destinationId); const destination = this.boards.find((board) => board.id === destinationId);
if (!destination || destination.archived) if (!destination || destination.archived)
throw new Error("The destination board is unavailable or archived. Choose another board."); 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)) if (listId !== null && !destination.value.lists.some((list) => list.id === listId))
throw new Error("The destination list no longer exists. Choose another list."); throw new Error(message("The destination list no longer exists. Choose another list."));
const last = this.tasks const last = this.tasks
.filter((card) => card.id !== task.id && card.archived === task.archived && .filter((card) => card.id !== task.id && card.archived === task.archived &&
Object.hasOwn(card.placements ?? {}, destinationId) && Object.hasOwn(card.placements ?? {}, destinationId) &&
@@ -724,9 +711,9 @@ export class TaskStore {
if (removed.size) { if (removed.size) {
await this.reloadFor([labelsPath]); await this.reloadFor([labelsPath]);
if (this.labels.source !== expected) if (this.labels.source !== expected)
throw new Error("Saved labels changed. Refresh before deleting labels."); throw new Error(message("Saved labels changed. Refresh before deleting labels."));
if (this.issues.length) if (this.issues.length)
throw new Error("Resolve workspace issues before deleting labels: " + this.issues.join(" ")); 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. // Keep definitions until every guarded card write succeeds, so a retry is safe.
for (const task of this.tasks) for (const task of this.tasks)
if (task.labels?.some((id) => removed.has(id))) { if (task.labels?.some((id) => removed.has(id))) {
@@ -751,16 +738,11 @@ export class TaskStore {
return this.run(async () => { return this.run(async () => {
await this.reload(); await this.reload();
if (this.issues.length) if (this.issues.length)
throw new Error( throw new Error(format(message("Resolve the workspace issues before migration: {issues}"), { issues: this.issues.join(" ") }));
"Resolve the workspace issues before migration: " +
this.issues.join(" "),
);
const selected = cardIds.map((id) => { const selected = cardIds.map((id) => {
const task = this.tasks.find((task) => task.id === id); const task = this.tasks.find((task) => task.id === id);
if (!task) if (!task)
throw new Error( throw new Error(message("A selected card is unavailable. Refresh before migration."));
"A selected card is unavailable. Refresh before migration.",
);
return task; return task;
}); });
const result = await migrateStorage( const result = await migrateStorage(
@@ -779,14 +761,14 @@ export class TaskStore {
return this.run(async () => { return this.run(async () => {
await this.reloadFor([catalogPath]); await this.reloadFor([catalogPath]);
if (!this.board.editable) if (!this.board.editable)
throw new Error("Open an available board before renaming it."); throw new Error(message("Open an available board before renaming it."));
const reference = this.board.reference!; const reference = this.board.reference!;
if (isManagedBoard(reference.path)) { if (isManagedBoard(reference.path)) {
await this.board.manage({ name }); await this.board.manage({ name });
await this.reloadFor([catalogPath]); await this.reloadFor([catalogPath]);
return; return;
} }
if (!rename) throw new Error("Migrate this board before renaming it."); if (!rename) throw new Error(message("Migrate this board before renaming it."));
const path = await rename({ ...reference }, name.trim()); const path = await rename({ ...reference }, name.trim());
reference.path = path; reference.path = path;
await this.reload(); await this.reload();
@@ -801,15 +783,13 @@ export class TaskStore {
if (!this.legacy) return this.run(() => this.adoptHidden(path)); if (!this.legacy) return this.run(() => this.adoptHidden(path));
return this.run(async () => { return this.run(async () => {
if (!/\.(md|markdown|mdown)$/i.test(path)) if (!/\.(md|markdown|mdown)$/i.test(path))
throw new Error("Choose a Markdown note from this workspace."); throw new Error(message("Choose a Markdown note from this workspace."));
await this.reload(); await this.reload();
const id = this.board.reference?.id; const id = this.board.reference?.id;
if (id && !this.board.available) if (id && !this.board.available)
throw new Error( throw new Error(message("The board is unavailable. Reopen it before adding a note."));
"The board is unavailable. Reopen it before adding a note.",
);
if (this.board.archived) if (this.board.archived)
throw new Error("Restore this board before adding cards."); throw new Error(message("Restore this board before adding cards."));
const source = await this.workspace.read(path); const source = await this.workspace.read(path);
let next = adoptNote(path, source); let next = adoptNote(path, source);
const task = readTask(path, next)!; const task = readTask(path, next)!;
@@ -817,11 +797,9 @@ export class TaskStore {
this.tasks.some( this.tasks.some(
(other) => other.id === task.id && other.path !== path, (other) => other.id === task.id && other.path !== path,
) || ) ||
this.issues.some((issue) => this.issues.includes(duplicateTaskIssue(task.id))
issue.startsWith(`Duplicate task ID ${task.id}:`),
)
) )
throw new Error("Resolve this task's duplicate ID before adding it."); throw new Error(message("Resolve this task's duplicate ID before adding it."));
if (id && !Object.hasOwn(task.placements ?? {}, id)) if (id && !Object.hasOwn(task.placements ?? {}, id))
next = editTask(task, { next = editTask(task, {
placements: { placements: {
@@ -839,23 +817,23 @@ export class TaskStore {
await saveDocument(this.workspace, path, next, source); await saveDocument(this.workspace, path, next, source);
await this.reload(); await this.reload();
const added = this.tasks.find(item => item.path === path); const added = this.tasks.find(item => item.path === path);
if (!added) throw new Error("The linked card is unavailable. Refresh the board."); if (!added) throw new Error(message("The linked card is unavailable. Refresh the board."));
return added; return added;
}); });
} }
private async adoptHidden(path: string): Promise<Task> { private async adoptHidden(path: string): Promise<Task> {
if (!/\.(md|markdown|mdown)$/i.test(path)) if (!/\.(md|markdown|mdown)$/i.test(path))
throw new Error("Choose a Markdown note from this workspace."); throw new Error(message("Choose a Markdown note from this workspace."));
const id = this.board.reference?.id; const id = this.board.reference?.id;
if (id && !this.board.available) if (id && !this.board.available)
throw new Error("The board is unavailable. Reopen it before adding a note."); throw new Error(message("The board is unavailable. Reopen it before adding a note."));
if (this.board.archived) if (this.board.archived)
throw new Error("Restore this board before adding cards."); throw new Error(message("Restore this board before adding cards."));
let card: Task | undefined; let card: Task | undefined;
if (isHiddenCard(path)) { if (isHiddenCard(path)) {
await this.reloadFor([path]); await this.reloadFor([path]);
card = this.tasks.find(task => task.path === path); card = this.tasks.find(task => task.path === path);
if (!card) throw new Error("The linked card is unavailable. Refresh the board."); if (!card) throw new Error(message("The linked card is unavailable. Refresh the board."));
} else { } else {
const source = await this.workspace.read(path); const source = await this.workspace.read(path);
const note = readTask(path, source); const note = readTask(path, source);
@@ -868,11 +846,11 @@ export class TaskStore {
await this.reloadFor([cardPath(note.id)]); await this.reloadFor([cardPath(note.id)]);
card = this.tasks.find(task => task.id === note.id); card = this.tasks.find(task => task.id === note.id);
} }
if (!card) throw new Error("The linked card is unavailable. Refresh the board."); if (!card) throw new Error(message("The linked card is unavailable. Refresh the board."));
} else { } else {
const { doc, body, match, newline } = split(source); const { doc, body, match, newline } = split(source);
if (doc.has("runestone_pm")) if (doc.has("runestone_pm"))
throw new Error("This document already contains Project Management data and cannot become a task."); throw new Error(message("This document already contains Project Management data and cannot become a task."));
const cardId = crypto.randomUUID(); const cardId = crypto.randomUUID();
const last = this.tasks.filter(task => task.status === "todo" && !task.archived).sort((a, b) => compareCards(a, b)).at(-1); const last = this.tasks.filter(task => task.status === "todo" && !task.archived).sort((a, b) => compareCards(a, b)).at(-1);
doc.set("runestone_pm", { doc.set("runestone_pm", {
+32 -39
View File
@@ -8,6 +8,7 @@ import {
writeCatalog, writeCatalog,
validateName, validateName,
} from "./catalog.ts"; } from "./catalog.ts";
import { message } from "./message.ts";
export interface BoardReference { export interface BoardReference {
id: string; id: string;
@@ -41,9 +42,9 @@ export function defaultBoard(id: string = crypto.randomUUID()): Board {
kind: "board", kind: "board",
id, id,
lists: [ lists: [
{ id: "todo", name: "To do", status: "todo", collapsed: false }, { id: "todo", name: message("To do"), status: "todo", collapsed: false },
{ id: "doing", name: "In progress", status: "doing", collapsed: false }, { id: "doing", name: message("In progress"), status: "doing", collapsed: false },
{ id: "done", name: "Done", status: "done", collapsed: false }, { id: "done", name: message("Done"), status: "done", collapsed: false },
], ],
defaults: { todo: "todo", doing: "doing", done: "done" }, defaults: { todo: "todo", doing: "doing", done: "done" },
}; };
@@ -59,10 +60,8 @@ export function parseBoard(source: string): Board {
!Array.isArray(value.lists) || !Array.isArray(value.lists) ||
!value.defaults !value.defaults
) )
throw new Error( throw new Error(message("The board file has an unsupported format. Restore or repair it before editing lists."));
"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."));
);
if (value.backgroundImage != null && !/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/.test(value.backgroundImage)) throw new Error("The board background image is invalid.");
const ids = new Set<string>(); const ids = new Set<string>();
for (const list of value.lists) { for (const list of value.lists) {
if ( if (
@@ -77,14 +76,12 @@ export function parseBoard(source: string): Board {
typeof list.collapsed !== "boolean" || typeof list.collapsed !== "boolean" ||
(list.maxCards !== undefined && (!Number.isSafeInteger(list.maxCards) || list.maxCards < 1)) (list.maxCards !== undefined && (!Number.isSafeInteger(list.maxCards) || list.maxCards < 1))
) )
throw new Error( throw new Error(message("The board contains an invalid list. Repair the board file before editing."));
"The board contains an invalid list. Repair the board file before editing.",
);
ids.add(list.id); ids.add(list.id);
} }
for (const status of statuses) for (const status of statuses)
if (value.defaults[status] !== null && !ids.has(value.defaults[status])) if (value.defaults[status] !== null && !ids.has(value.defaults[status]))
throw new Error("The board has an invalid default list."); throw new Error(message("The board has an invalid default list."));
return value; return value;
} }
export function boardDocument( export function boardDocument(
@@ -110,7 +107,7 @@ export function newBoardSource(): string {
} }
export class BoardStore { export class BoardStore {
value = defaultBoard("all-tasks"); value = defaultBoard("all-tasks");
name = "All tasks"; name: string = message("All tasks");
available = true; available = true;
archived = false; archived = false;
private source: string | null = null; private source: string | null = null;
@@ -134,7 +131,7 @@ export class BoardStore {
const snapshot = await readCatalog(this.workspace); const snapshot = await readCatalog(this.workspace);
if (snapshot.value.deletedBoardIds?.includes(this.reference.id)) { if (snapshot.value.deletedBoardIds?.includes(this.reference.id)) {
this.load(); this.load();
throw new Error("This board was deleted. Open All tasks to find its cards."); throw new Error(message("This board was deleted. Open All tasks to find its cards."));
} }
const managed = snapshot.value.boards.find( const managed = snapshot.value.boards.find(
(board) => board.value.id === this.reference!.id, (board) => board.value.id === this.reference!.id,
@@ -145,9 +142,7 @@ export class BoardStore {
managed.original?.path !== this.reference.path || managed.original?.path !== this.reference.path ||
(current !== null && current !== managed.original.source) (current !== null && current !== managed.original.source)
) )
throw new Error( throw new Error(message("The legacy board differs from hidden storage. Preserve both versions."));
"The legacy board differs from hidden storage. Preserve both versions.",
);
this.load( this.load(
managedDocuments(snapshot.value, snapshot.source!).find( managedDocuments(snapshot.value, snapshot.source!).find(
(board) => board.id === this.reference!.id, (board) => board.id === this.reference!.id,
@@ -164,13 +159,13 @@ export class BoardStore {
), ),
); );
if (!this.available) if (!this.available)
throw new Error("This board is unavailable. Refresh Project Management."); throw new Error(message("This board is unavailable. Refresh Project Management."));
return; return;
} }
const source = await this.workspace.read(this.reference.path); const source = await this.workspace.read(this.reference.path);
const document = boardDocument(source, this.reference.path); const document = boardDocument(source, this.reference.path);
if (!document || document.id !== this.reference.id) if (!document || document.id !== this.reference.id)
throw new Error("The board changed. Reopen it from navigation."); throw new Error(message("The board changed. Reopen it from navigation."));
this.load(document); this.load(document);
} }
load(document?: BoardDocument) { load(document?: BoardDocument) {
@@ -195,29 +190,27 @@ export class BoardStore {
} }
async update(change: (board: Board) => void) { async update(change: (board: Board) => void) {
if (!this.editable) if (!this.editable)
throw new Error("Open an available board to edit its lists."); throw new Error(message("Open an available board to edit its lists."));
const expected = this.source; const expected = this.source;
if (!isManagedBoard(this.reference!.path) && this.workspace.readOptional) { if (!isManagedBoard(this.reference!.path) && this.workspace.readOptional) {
const snapshot = await readCatalog(this.workspace); const snapshot = await readCatalog(this.workspace);
if (snapshot.value.deletedBoardIds?.includes(this.reference!.id)) if (snapshot.value.deletedBoardIds?.includes(this.reference!.id))
throw new Error("This board was deleted. Open All tasks to find its cards."); throw new Error(message("This board was deleted. Open All tasks to find its cards."));
if ( if (
snapshot.value.boards.some( snapshot.value.boards.some(
(board) => board.value.id === this.reference!.id, (board) => board.value.id === this.reference!.id,
) )
) )
throw new Error( throw new Error(message("This board moved to hidden storage. Refresh before editing."));
"This board moved to hidden storage. Refresh before editing.",
);
} }
if (isManagedBoard(this.reference!.path)) { if (isManagedBoard(this.reference!.path)) {
const snapshot = await readCatalog(this.workspace); const snapshot = await readCatalog(this.workspace);
if (snapshot.source !== expected) if (snapshot.source !== expected)
throw new Error("The board changed. Refresh before editing its lists."); throw new Error(message("The board changed. Refresh before editing its lists."));
const board = snapshot.value.boards.find( const board = snapshot.value.boards.find(
(item) => item.value.id === this.reference!.id, (item) => item.value.id === this.reference!.id,
); );
if (!board) throw new Error("The board is unavailable."); if (!board) throw new Error(message("The board is unavailable."));
change(board.value); change(board.value);
this.source = await writeCatalog( this.source = await writeCatalog(
this.workspace, this.workspace,
@@ -229,7 +222,7 @@ export class BoardStore {
} }
const current = await this.workspace.read(this.reference!.path); const current = await this.workspace.read(this.reference!.path);
if (current !== expected) if (current !== expected)
throw new Error("The board changed. Refresh before editing its lists."); throw new Error(message("The board changed. Refresh before editing its lists."));
const next = structuredClone(this.value); const next = structuredClone(this.value);
change(next); change(next);
const { doc, body, newline, match } = split(expected!); const { doc, body, newline, match } = split(expected!);
@@ -243,21 +236,21 @@ export class BoardStore {
} }
async deleteBoard() { async deleteBoard() {
if (!this.reference || !this.available || this.source === null) if (!this.reference || !this.available || this.source === null)
throw new Error("Open an available board before deleting it."); throw new Error(message("Open an available board before deleting it."));
const { id, path } = this.reference; const { id, path } = this.reference;
const snapshot = await readCatalog(this.workspace); const snapshot = await readCatalog(this.workspace);
if (snapshot.value.deletedBoardIds?.includes(id)) if (snapshot.value.deletedBoardIds?.includes(id))
throw new Error("This board was already deleted. Refresh Project Management."); throw new Error(message("This board was already deleted. Refresh Project Management."));
if (isManagedBoard(path)) { if (isManagedBoard(path)) {
if (snapshot.source !== this.source) if (snapshot.source !== this.source)
throw new Error("The board changed. Cancel, refresh, and review it before deleting."); throw new Error(message("The board changed. Cancel, refresh, and review it before deleting."));
if (!snapshot.value.boards.some((board) => board.value.id === id)) if (!snapshot.value.boards.some((board) => board.value.id === id))
throw new Error("The board is unavailable. Refresh Project Management."); throw new Error(message("The board is unavailable. Refresh Project Management."));
} else { } else {
if (snapshot.value.boards.some((board) => board.value.id === id)) if (snapshot.value.boards.some((board) => board.value.id === id))
throw new Error("This board moved to hidden storage. Refresh before deleting."); throw new Error(message("This board moved to hidden storage. Refresh before deleting."));
if ((await this.workspace.read(path)) !== this.source) if ((await this.workspace.read(path)) !== this.source)
throw new Error("The board changed. Cancel, refresh, and review it before deleting."); 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); snapshot.value.boards = snapshot.value.boards.filter((board) => board.value.id !== id);
// Keep originals and card memberships intact. The record prevents legacy rediscovery. // Keep originals and card memberships intact. The record prevents legacy rediscovery.
@@ -271,10 +264,10 @@ export class BoardStore {
!isManagedBoard(this.reference.path) || !isManagedBoard(this.reference.path) ||
!this.available !this.available
) )
throw new Error("Migrate this board before managing hidden storage."); throw new Error(message("Migrate this board before managing hidden storage."));
const snapshot = await readCatalog(this.workspace); const snapshot = await readCatalog(this.workspace);
if (snapshot.source !== this.source) if (snapshot.source !== this.source)
throw new Error("The board changed. Refresh before saving."); throw new Error(message("The board changed. Refresh before saving."));
const board = snapshot.value.boards.find( const board = snapshot.value.boards.find(
(item) => item.value.id === this.reference!.id, (item) => item.value.id === this.reference!.id,
)!; )!;
@@ -288,7 +281,7 @@ export class BoardStore {
patch.name!.trim().toLocaleLowerCase(), patch.name!.trim().toLocaleLowerCase(),
) )
) )
throw new Error("A board with this name already exists."); throw new Error(message("A board with this name already exists."));
board.name = patch.name.trim(); board.name = patch.name.trim();
} }
if (patch.archived !== undefined) board.archived = patch.archived; if (patch.archived !== undefined) board.archived = patch.archived;
@@ -327,7 +320,7 @@ export class BoardStore {
} }
async setLimit(id: string, maximum?: number) { async setLimit(id: string, maximum?: number) {
if (maximum !== undefined && (!Number.isSafeInteger(maximum) || maximum < 1)) if (maximum !== undefined && (!Number.isSafeInteger(maximum) || maximum < 1))
throw new Error("Enter a whole number of at least 1, or leave the maximum blank."); throw new Error(message("Enter a whole number of at least 1, or leave the maximum blank."));
await this.update((board) => { await this.update((board) => {
const list = this.requireList(board, id); const list = this.requireList(board, id);
if (maximum === undefined) delete list.maxCards; if (maximum === undefined) delete list.maxCards;
@@ -356,12 +349,12 @@ export class BoardStore {
private requireList(board: Board, id: string) { private requireList(board: Board, id: string) {
const list = board.lists.find((item) => item.id === id); const list = board.lists.find((item) => item.id === id);
if (!list) if (!list)
throw new Error("This list no longer exists. Refresh the board."); throw new Error(message("This list no longer exists. Refresh the board."));
return list; return list;
} }
private checkName(board: Board, name: string, except?: string) { private checkName(board: Board, name: string, except?: string) {
if (!name.trim() || name.trim().length > 80) if (!name.trim() || name.trim().length > 80)
throw new Error("Enter a list name of 1 to 80 characters."); throw new Error(message("Enter a list name of 1 to 80 characters."));
if ( if (
board.lists.some( board.lists.some(
(list) => (list) =>
@@ -369,6 +362,6 @@ export class BoardStore {
list.name.toLocaleLowerCase() === name.trim().toLocaleLowerCase(), list.name.toLocaleLowerCase() === name.trim().toLocaleLowerCase(),
) )
) )
throw new Error("A list with this name already exists."); throw new Error(message("A list with this name already exists."));
} }
} }
+16 -12
View File
@@ -10,6 +10,12 @@ import {
readOptional, readOptional,
saveDocument, saveDocument,
} from "./persistence.ts"; } 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) { export function cardPath(id: string) {
const key = Array.from(new TextEncoder().encode(id), (byte) => const key = Array.from(new TextEncoder().encode(id), (byte) =>
@@ -34,9 +40,7 @@ export function cardOrigin(source: string): OriginalFile | undefined {
.some((part: string) => !part || part === "." || part === "..") || .some((part: string) => !part || part === "." || part === "..") ||
origin.backup !== `.runestone/pm/backups/${origin.path}` origin.backup !== `.runestone/pm/backups/${origin.path}`
) )
throw new Error( throw new Error(message("The card migration record is invalid. Keep the original note."));
"The card migration record is invalid. Keep the original note.",
);
return origin; return origin;
} }
/** Read one hidden card file. It throws when the file is invalid or when its name does not match the card ID. */ /** Read one hidden card file. It throws when the file is invalid or when its name does not match the card ID. */
@@ -44,7 +48,7 @@ export function parseCard(path: string, source: string): Task {
cardOrigin(source); cardOrigin(source);
const task = readTask(path, source); const task = readTask(path, source);
if (!task || cardPath(task.id) !== path) if (!task || cardPath(task.id) !== path)
throw new Error("The hidden card ID does not match its storage path."); throw new Error(message("The hidden card ID does not match its storage path."));
return task; return task;
} }
export async function prepareCards(workspace: Workspace) { export async function prepareCards(workspace: Workspace) {
@@ -75,14 +79,14 @@ export async function readCards(
const documents = await mapConcurrent(entries, async (entry) => { const documents = await mapConcurrent(entries, async (entry) => {
try { try {
const result = sources.get(entry.rel_path)!; const result = sources.get(entry.rel_path)!;
if (result.error || result.source === undefined) throw new Error(result.error ?? "The card is unavailable."); if (result.error || result.source === undefined) throw new Error(result.error ?? message("The card is unavailable."));
const source = result.source; const source = result.source;
const cached = previous.get(entry.rel_path); const cached = previous.get(entry.rel_path);
if (cached?.source === source) return { task: cached }; if (cached?.source === source) return { task: cached };
return { task: parseCard(entry.rel_path, source) }; return { task: parseCard(entry.rel_path, source) };
} catch (error) { } catch (error) {
return { return {
issue: `${entry.rel_path}: ${error instanceof Error ? error.message : String(error)}`, issue: fileIssue(entry.rel_path, error instanceof Error ? error.message : String(error)),
}; };
} }
}); });
@@ -111,19 +115,19 @@ export async function migrateCards(workspace: Workspace, tasks: Task[]) {
if (isHiddenCard(task.path)) continue; if (isHiddenCard(task.path)) continue;
if ((await workspace.read(task.path)) !== task.source) if ((await workspace.read(task.path)) !== task.source)
throw new Error( throw new Error(
`The card changed: ${task.path}. Refresh before migration.`, format(message("The card changed: {path}. Refresh before migration."), { path: task.path }),
); );
const destination = await readOptional(workspace, cardPath(task.id)); const destination = await readOptional(workspace, cardPath(task.id));
if (destination !== null) { if (destination !== null) {
const origin = cardOrigin(destination); const origin = cardOrigin(destination);
if (origin?.path !== task.path || origin.source !== task.source) if (origin?.path !== task.path || origin.source !== task.source)
throw new Error( throw new Error(
`A different hidden card already uses the ID from ${task.path}.`, format(message("A different hidden card already uses the ID from {path}."), { path: task.path }),
); );
} }
if (split(task.source).doc.has("runestone_pm_origin")) if (split(task.source).doc.has("runestone_pm_origin"))
throw new Error( throw new Error(
`The note already contains a migration record: ${task.path}. Review it before migration.`, format(message("The note already contains a migration record: {path}. Review it before migration."), { path: task.path }),
); );
} }
for (const task of tasks) { for (const task of tasks) {
@@ -149,15 +153,15 @@ export async function migrateCards(workspace: Workspace, tasks: Task[]) {
copied.body !== task.body copied.body !== task.body
) )
throw new Error( throw new Error(
`The card copy differs from ${task.path}. Keep the original.`, format(message("The card copy differs from {path}. Keep the original."), { path: task.path }),
); );
if ((await workspace.read(task.path)) !== task.source) if ((await workspace.read(task.path)) !== task.source)
throw new Error(`The card changed: ${task.path}. Retry migration.`); throw new Error(format(message("The card changed: {path}. Retry migration."), { path: task.path }));
await prepareCards(workspace); await prepareCards(workspace);
await saveDocument(workspace, path, source, null); await saveDocument(workspace, path, source, null);
if ((await workspace.read(path)) !== source) if ((await workspace.read(path)) !== source)
throw new Error( throw new Error(
`The saved card check failed: ${task.path}. Keep the original.`, format(message("The saved card check failed: {path}. Keep the original."), { path: task.path }),
); );
} }
} }
+14 -15
View File
@@ -7,6 +7,7 @@ import {
} from "./board.ts"; } from "./board.ts";
import type { Workspace } from "../model/model.ts"; import type { Workspace } from "../model/model.ts";
import { readOptional, saveDocument } from "./persistence.ts"; import { readOptional, saveDocument } from "./persistence.ts";
import { format, message } from "./message.ts";
export const catalogPath = ".runestone/pm/workspace.json"; export const catalogPath = ".runestone/pm/workspace.json";
export const boardKey = (id: string) => `pm-board:${id}`; export const boardKey = (id: string) => `pm-board:${id}`;
@@ -33,15 +34,13 @@ export function boardMarkdown(value: Board): string {
} }
export function validateName(name: string) { export function validateName(name: string) {
if (!name.trim() || name.trim().length > 100 || /[\x00-\x1f]/.test(name)) if (!name.trim() || name.trim().length > 100 || /[\x00-\x1f]/.test(name))
throw new Error("Enter a board name of 1 to 100 characters."); throw new Error(message("Enter a board name of 1 to 100 characters."));
} }
export function parseCatalog(source: string | null): Catalog { export function parseCatalog(source: string | null): Catalog {
if (source === null) return { schema: 1, boards: [] }; if (source === null) return { schema: 1, boards: [] };
const data = JSON.parse(source); const data = JSON.parse(source);
if (!data || data.schema !== 1 || !Array.isArray(data.boards)) if (!data || data.schema !== 1 || !Array.isArray(data.boards))
throw new Error( throw new Error(message("The Project Management storage format is unsupported. Restore a backup or update Project Management."));
"The Project Management storage format is unsupported. Restore a backup or update Project Management.",
);
const ids = new Set<string>(); const ids = new Set<string>();
if ( if (
data.deletedBoardIds !== undefined && data.deletedBoardIds !== undefined &&
@@ -49,26 +48,26 @@ export function parseCatalog(source: string | null): Catalog {
data.deletedBoardIds.some((id: unknown) => typeof id !== "string" || !id.trim()) || data.deletedBoardIds.some((id: unknown) => typeof id !== "string" || !id.trim()) ||
new Set(data.deletedBoardIds).size !== data.deletedBoardIds.length) new Set(data.deletedBoardIds).size !== data.deletedBoardIds.length)
) )
throw new Error("The deleted board record is invalid."); throw new Error(message("The deleted board record is invalid."));
for (const board of data.boards) { for (const board of data.boards) {
if (!board || typeof board.name !== "string") if (!board || typeof board.name !== "string")
throw new Error("A saved board has no name."); throw new Error(message("A saved board has no name."));
validateName(board.name); validateName(board.name);
parseBoard(boardMarkdown(board.value)); parseBoard(boardMarkdown(board.value));
if (ids.has(board.value.id)) if (ids.has(board.value.id))
throw new Error("Project Management storage contains duplicate board IDs."); throw new Error(message("Project Management storage contains duplicate board IDs."));
ids.add(board.value.id); ids.add(board.value.id);
if (data.deletedBoardIds?.includes(board.value.id)) if (data.deletedBoardIds?.includes(board.value.id))
throw new Error("A deleted board still has an active storage entry."); throw new Error(message("A deleted board still has an active storage entry."));
if (board.archived !== undefined && typeof board.archived !== "boolean") if (board.archived !== undefined && typeof board.archived !== "boolean")
throw new Error("The board archive state is invalid."); throw new Error(message("The board archive state is invalid."));
if ( if (
board.original && board.original &&
(typeof board.original.path !== "string" || (typeof board.original.path !== "string" ||
typeof board.original.source !== "string" || typeof board.original.source !== "string" ||
typeof board.original.backup !== "string") typeof board.original.backup !== "string")
) )
throw new Error("The board migration record is invalid."); throw new Error(message("The board migration record is invalid."));
} }
return data; return data;
} }
@@ -82,7 +81,7 @@ export async function writeCatalog(
expected: string | null, expected: string | null,
) { ) {
if (!workspace.readOptional) if (!workspace.readOptional)
throw new Error("Update RuneStone to use hidden Project Management storage."); throw new Error(message("Update RuneStone to use hidden Project Management storage."));
const source = JSON.stringify(value, null, 2) + "\n"; const source = JSON.stringify(value, null, 2) + "\n";
parseCatalog(source); parseCatalog(source);
await saveDocument(workspace, catalogPath, source, expected); await saveDocument(workspace, catalogPath, source, expected);
@@ -110,7 +109,7 @@ export async function createBoard(workspace: Workspace, name: string) {
board.name.toLocaleLowerCase() === name.trim().toLocaleLowerCase(), board.name.toLocaleLowerCase() === name.trim().toLocaleLowerCase(),
) )
) )
throw new Error("A board with this name already exists."); throw new Error(message("A board with this name already exists."));
const value = defaultBoard(); const value = defaultBoard();
snapshot.value.boards.push({ name: name.trim(), value }); snapshot.value.boards.push({ name: name.trim(), value });
await writeCatalog(workspace, snapshot.value, snapshot.source); await writeCatalog(workspace, snapshot.value, snapshot.source);
@@ -126,15 +125,15 @@ export async function backupFile(
path.includes("\\") || path.includes("\\") ||
path.split("/").some((part) => !part || part === ".." || part === ".") path.split("/").some((part) => !part || part === ".." || part === ".")
) )
throw new Error("The migration source path is invalid."); throw new Error(message("The migration source path is invalid."));
const backup = `.runestone/pm/backups/${path}`; const backup = `.runestone/pm/backups/${path}`;
const saved = await readOptional(workspace, backup); const saved = await readOptional(workspace, backup);
if (saved === null) await saveDocument(workspace, backup, source, null); if (saved === null) await saveDocument(workspace, backup, source, null);
else if (saved !== source) else if (saved !== source)
throw new Error( throw new Error(
`The backup differs from ${path}. Preserve both versions before migration.`, format(message("The backup differs from {path}. Preserve both versions before migration."), { path }),
); );
if ((await workspace.read(backup)) !== source) if ((await workspace.read(backup)) !== source)
throw new Error(`Backup check failed for ${path}.`); throw new Error(format(message("The backup check failed for {path}."), { path }));
return { path, source, backup }; return { path, source, backup };
} }
+2 -1
View File
@@ -1,5 +1,6 @@
import type { Workspace } from "../model/model.ts"; import type { Workspace } from "../model/model.ts";
import { readOptional, saveDocument } from "./persistence.ts"; import { readOptional, saveDocument } from "./persistence.ts";
import { message } from "./message.ts";
export const deletedCardsPath = ".runestone/pm/deleted-cards.json"; export const deletedCardsPath = ".runestone/pm/deleted-cards.json";
@@ -10,7 +11,7 @@ export async function readDeletedCards(workspace: Workspace) {
if (value?.schema !== 1 || !Array.isArray(value.ids) || if (value?.schema !== 1 || !Array.isArray(value.ids) ||
value.ids.some((id: unknown) => typeof id !== "string" || !id.trim()) || value.ids.some((id: unknown) => typeof id !== "string" || !id.trim()) ||
new Set(value.ids).size !== value.ids.length) new Set(value.ids).size !== value.ids.length)
throw new Error("The deleted card record is invalid. Restore it before editing cards."); throw new Error(message("The deleted card record is invalid. Restore it before editing cards."));
return { source, ids: value.ids as string[] }; return { source, ids: value.ids as string[] };
} }
@@ -1,5 +1,6 @@
import type { Workspace } from "../model/model.ts"; import type { Workspace } from "../model/model.ts";
import { readOptional, saveDocument } from "./persistence.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. */ /** A draft is separate from the saved card and uses compare-and-write protection. */
export class DescriptionDraft { export class DescriptionDraft {
@@ -17,7 +18,7 @@ export class DescriptionDraft {
if (this.source === null) return null; if (this.source === null) return null;
const value = JSON.parse(this.source); const value = JSON.parse(this.source);
if (value?.schema !== 1 || (value.body !== null && typeof value.body !== "string")) if (value?.schema !== 1 || (value.body !== null && typeof value.body !== "string"))
throw new Error("The description draft is invalid. Preserve it before recovery."); throw new Error(message("The description draft is invalid. Preserve it before recovery."));
return value.body; return value.body;
} }
save(body: string | null): Promise<void> { save(body: string | null): Promise<void> {
+5 -4
View File
@@ -1,5 +1,6 @@
import type { Workspace, TaskFields } from "../model/model.ts"; import type { Workspace, TaskFields } from "../model/model.ts";
import { saveDocument, storageRoot } from "./persistence.ts"; import { saveDocument, storageRoot } from "./persistence.ts";
import { message } from "./message.ts";
export const maxImageBytes = 50 * 1024 * 1024; export const maxImageBytes = 50 * 1024 * 1024;
export const imageTypes = [ export const imageTypes = [
@@ -13,7 +14,7 @@ const idPattern =
export const imageFolder = `${storageRoot}/images`; export const imageFolder = `${storageRoot}/images`;
export function imagePath(id: string) { export function imagePath(id: string) {
if (!new RegExp(`^${idPattern}$`).test(id)) if (!new RegExp(`^${idPattern}$`).test(id))
throw new Error("The image ID is invalid."); throw new Error(message("The image ID is invalid."));
return `${imageFolder}/${id}.json`; return `${imageFolder}/${id}.json`;
} }
export function imageReferences(body: string) { export function imageReferences(body: string) {
@@ -34,10 +35,10 @@ export function imageMarkdown(name: string, id: string) {
} }
export function parseImage(source: string): string { export function parseImage(source: string): string {
if (source.length > Math.ceil(maxImageBytes / 3) * 4 + 256) if (source.length > Math.ceil(maxImageBytes / 3) * 4 + 256)
throw new Error("The saved image exceeds the 50 MiB limit."); throw new Error(message("The saved image exceeds the 50 MiB limit."));
const value = JSON.parse(source); const value = JSON.parse(source);
if (value?.schema !== 1 || typeof value.data !== "string") if (value?.schema !== 1 || typeof value.data !== "string")
throw new Error("The saved image is invalid."); throw new Error(message("The saved image is invalid."));
const match = const match =
/^data:(image\/(?:png|jpeg|gif|webp));base64,([A-Za-z0-9+/]+={0,2})$/.exec( /^data:(image\/(?:png|jpeg|gif|webp));base64,([A-Za-z0-9+/]+={0,2})$/.exec(
value.data, value.data,
@@ -47,7 +48,7 @@ export function parseImage(source: string): string {
match[2].length % 4 !== 0 || match[2].length % 4 !== 0 ||
atob(match[2]).length > maxImageBytes atob(match[2]).length > maxImageBytes
) )
throw new Error("The saved image is invalid or exceeds 50 MiB."); throw new Error(message("The saved image is invalid or exceeds 50 MiB."));
return value.data; return value.data;
} }
export async function saveImages( export async function saveImages(
+13 -18
View File
@@ -1,5 +1,6 @@
import { cardColors, type Workspace } from "../model/model.ts"; import { cardColors, type Workspace } from "../model/model.ts";
import { readOptional, saveDocument } from "./persistence.ts"; import { readOptional, saveDocument } from "./persistence.ts";
import { message } from "./message.ts";
export const labelsPath = ".runestone/pm/labels.json"; export const labelsPath = ".runestone/pm/labels.json";
export const legacyLabelsPath = "runestone-pm-labels.json"; export const legacyLabelsPath = "runestone-pm-labels.json";
@@ -24,7 +25,7 @@ export function defaultLabels(): SavedLabel[] {
export function validateLabels( export function validateLabels(
labels: unknown, labels: unknown,
): asserts labels is SavedLabel[] { ): asserts labels is SavedLabel[] {
if (!Array.isArray(labels)) throw new Error("Saved labels must be a list."); if (!Array.isArray(labels)) throw new Error(message("Saved labels must be a list."));
const ids = new Set<string>(), const ids = new Set<string>(),
names = new Set<string>(); names = new Set<string>();
for (const label of labels) { for (const label of labels) {
@@ -36,26 +37,24 @@ export function validateLabels(
!/^[a-zA-Z0-9_-]{1,100}$/.test(label.id) || !/^[a-zA-Z0-9_-]{1,100}$/.test(label.id) ||
ids.has(label.id) ids.has(label.id)
) )
throw new Error("Each saved label needs a unique ID."); throw new Error(message("Each saved label needs a unique ID."));
if ( if (
typeof label.name !== "string" || typeof label.name !== "string" ||
!label.name.trim() || !label.name.trim() ||
label.name.trim().length > 80 || label.name.trim().length > 80 ||
/[\x00-\x1f\x7f]/.test(label.name) /[\x00-\x1f\x7f]/.test(label.name)
) )
throw new Error("Enter a label name of 1 to 80 characters."); throw new Error(message("Enter a label name of 1 to 80 characters."));
const name = label.name.trim().toLocaleLowerCase(); const name = label.name.trim().toLocaleLowerCase();
if (names.has(name)) if (names.has(name))
throw new Error( throw new Error(message("Use a different name for each label, including archived labels."));
"Use a different name for each label, including archived labels.",
);
if ( if (
typeof label.color !== "string" || typeof label.color !== "string" ||
!Object.hasOwn(cardColors, label.color) !Object.hasOwn(cardColors, label.color)
) )
throw new Error("Choose a supported label color."); throw new Error(message("Choose a supported label color."));
if (label.archived !== undefined && typeof label.archived !== "boolean") if (label.archived !== undefined && typeof label.archived !== "boolean")
throw new Error("Label archive state must be true or false."); throw new Error(message("The label archive state must be true or false."));
ids.add(label.id); ids.add(label.id);
names.add(name); names.add(name);
} }
@@ -66,7 +65,7 @@ export function parseLabels(source: string | null): LabelSnapshot {
try { try {
data = JSON.parse(source); data = JSON.parse(source);
} catch { } catch {
throw new Error("Fix the saved labels file before editing labels."); throw new Error(message("Fix the saved labels file before editing labels."));
} }
if ( if (
!data || !data ||
@@ -74,7 +73,7 @@ export function parseLabels(source: string | null): LabelSnapshot {
Array.isArray(data) || Array.isArray(data) ||
data.schema !== 1 data.schema !== 1
) )
throw new Error("The saved labels file has an unsupported schema."); throw new Error(message("The saved labels file has an unsupported schema."));
validateLabels(data.labels); validateLabels(data.labels);
return { source, labels: data.labels }; return { source, labels: data.labels };
} }
@@ -102,15 +101,11 @@ export class LabelStore {
} }
checkSave(labels: SavedLabel[], expected: string | null | undefined): asserts expected is string | null { checkSave(labels: SavedLabel[], expected: string | null | undefined): asserts expected is string | null {
if (this.legacy) if (this.legacy)
throw new Error( throw new Error(message("Use the workspace migration tool before editing legacy labels. See the Project Management development guide."));
"Use the workspace migration tool before editing legacy labels. See the Project Management development guide.",
);
if (!this.workspace.readOptional) if (!this.workspace.readOptional)
throw new Error("Update RuneStone to use hidden Project Management storage."); throw new Error(message("Update RuneStone to use hidden Project Management storage."));
if (expected === undefined || this.error) if (expected === undefined || this.error)
throw new Error( throw new Error(message("Saved labels are unavailable. Refresh before editing labels."));
"Saved labels are unavailable. Refresh before editing labels.",
);
validateLabels(labels); validateLabels(labels);
} }
async save(labels: SavedLabel[], expected: string | null | undefined, allowDelete = false) { async save(labels: SavedLabel[], expected: string | null | undefined, allowDelete = false) {
@@ -121,7 +116,7 @@ export class LabelStore {
(label) => !labels.some((next) => next.id === label.id), (label) => !labels.some((next) => next.id === label.id),
) )
) )
throw new Error("Archive unused labels to preserve existing cards."); throw new Error(message("Archive unused labels to preserve existing cards."));
const data = expected === null ? { schema: 1 } : JSON.parse(expected); const data = expected === null ? { schema: 1 } : JSON.parse(expected);
const source = const source =
JSON.stringify( JSON.stringify(
+13
View File
@@ -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);
}
+12 -13
View File
@@ -14,6 +14,7 @@ import {
saveDocument, saveDocument,
ensurePrivateStorage, ensurePrivateStorage,
} from "./persistence.ts"; } from "./persistence.ts";
import { format, message } from "./message.ts";
/** Retain originals until the user checks the boards and removes the listed files. */ /** Retain originals until the user checks the boards and removes the listed files. */
export async function migrateStorage( export async function migrateStorage(
@@ -22,7 +23,7 @@ export async function migrateStorage(
cards: Task[] = [], cards: Task[] = [],
) { ) {
if (!workspace.readOptional || !workspace.create) if (!workspace.readOptional || !workspace.create)
throw new Error("Update RuneStone before migrating Project Management storage."); throw new Error(message("Update RuneStone before migrating Project Management storage."));
const snapshot = await readCatalog(workspace); const snapshot = await readCatalog(workspace);
const legacy = boards.filter((board) => !isManagedBoard(board.path)); const legacy = boards.filter((board) => !isManagedBoard(board.path));
const legacyLabels = await readOptional(workspace, legacyLabelsPath); const legacyLabels = await readOptional(workspace, legacyLabelsPath);
@@ -32,10 +33,10 @@ export async function migrateStorage(
// Validate every source before creating backups or publishing any changes. // Validate every source before creating backups or publishing any changes.
for (const board of legacy) { for (const board of legacy) {
if (snapshot.value.deletedBoardIds?.includes(board.id)) if (snapshot.value.deletedBoardIds?.includes(board.id))
throw new Error("This board was deleted. Refresh Project Management before migration."); throw new Error(message("This board was deleted. Refresh Project Management before migration."));
if ((await workspace.read(board.path)) !== board.source) if ((await workspace.read(board.path)) !== board.source)
throw new Error( throw new Error(
`The board changed: ${board.path}. Refresh before migration.`, format(message("The board changed: {path}. Refresh before migration."), { path: board.path }),
); );
const existing = snapshot.value.boards.find( const existing = snapshot.value.boards.find(
(item) => item.value.id === board.id, (item) => item.value.id === board.id,
@@ -46,7 +47,7 @@ export async function migrateStorage(
existing.original.source !== board.source) existing.original.source !== board.source)
) )
throw new Error( throw new Error(
`A different board already uses the ID from ${board.path}.`, format(message("A different board already uses the ID from {path}."), { path: board.path }),
); );
} }
if (legacyLabels !== null && savedLabels !== null) { if (legacyLabels !== null && savedLabels !== null) {
@@ -55,9 +56,7 @@ export async function migrateStorage(
original?.path !== legacyLabelsPath || original?.path !== legacyLabelsPath ||
original?.source !== legacyLabels original?.source !== legacyLabels
) )
throw new Error( throw new Error(message("Hidden labels and legacy labels both exist. Resolve their differences before migration."));
"Hidden labels and legacy labels both exist. Resolve their differences before migration.",
);
} }
await ensurePrivateStorage(workspace); await ensurePrivateStorage(workspace);
let changed = false; let changed = false;
@@ -79,10 +78,10 @@ export async function migrateStorage(
for (const board of legacy) for (const board of legacy)
if ((await workspace.read(board.path)) !== board.source) if ((await workspace.read(board.path)) !== board.source)
throw new Error( throw new Error(
`The board changed: ${board.path}. Refresh before migration.`, format(message("The board changed: {path}. Refresh before migration."), { path: board.path }),
); );
if (legacyLabels !== (await readOptional(workspace, legacyLabelsPath))) if (legacyLabels !== (await readOptional(workspace, legacyLabelsPath)))
throw new Error("Legacy labels changed. Refresh before migration."); throw new Error(message("Legacy labels changed. Refresh before migration."));
if (changed) await writeCatalog(workspace, snapshot.value, snapshot.source); if (changed) await writeCatalog(workspace, snapshot.value, snapshot.source);
if (labelBackup) { if (labelBackup) {
const source = const source =
@@ -93,7 +92,7 @@ export async function migrateStorage(
) + "\n"; ) + "\n";
await saveDocument(workspace, labelsPath, source, null); await saveDocument(workspace, labelsPath, source, null);
if ((await workspace.read(labelsPath)) !== source) if ((await workspace.read(labelsPath)) !== source)
throw new Error("The saved label check failed. Retry migration."); throw new Error(message("The saved label check failed. Retry migration."));
} }
const saved = await readCatalog(workspace); const saved = await readCatalog(workspace);
for (const board of legacy) { for (const board of legacy) {
@@ -105,19 +104,19 @@ export async function migrateStorage(
entry?.original?.source !== board.source || entry?.original?.source !== board.source ||
JSON.stringify(entry) !== JSON.stringify(expected) JSON.stringify(entry) !== JSON.stringify(expected)
) )
throw new Error("The saved board check failed. Retry migration."); throw new Error(message("The saved board check failed. Retry migration."));
} }
await migrateCards(workspace, cards); await migrateCards(workspace, cards);
const files = await migrationFiles(workspace); const files = await migrationFiles(workspace);
for (const file of files) { for (const file of files) {
if ((await workspace.read(file.backup)) !== file.source) if ((await workspace.read(file.backup)) !== file.source)
throw new Error( throw new Error(
`Backup check failed for ${file.path}. Keep the original.`, format(message("The backup check failed for {path}. Keep the original."), { path: file.path }),
); );
const current = await readOptional(workspace, file.path); const current = await readOptional(workspace, file.path);
if (current !== null && current !== file.source) if (current !== null && current !== file.source)
throw new Error( throw new Error(
`The original changed: ${file.path}. Keep both versions.`, format(message("The original changed: {path}. Keep both versions."), { path: file.path }),
); );
} }
return files; return files;
+12 -17
View File
@@ -7,24 +7,21 @@ import {
type Status, type Status,
type Session, type Session,
} from "../model/model.ts"; } from "../model/model.ts";
import { message } from "./message.ts";
const frontmatter = const frontmatter =
/^(\uFEFF?)(---[ \t]*\r?\n)([\s\S]*?)(\r?\n(?:---|\.\.\.)[ \t]*(?:\r?\n|$))/; /^(\uFEFF?)(---[ \t]*\r?\n)([\s\S]*?)(\r?\n(?:---|\.\.\.)[ \t]*(?:\r?\n|$))/;
export function split(source: string) { export function split(source: string) {
const match = frontmatter.exec(source); const match = frontmatter.exec(source);
if (!match && /^\uFEFF?---[ \t]*\r?\n/.test(source)) if (!match && /^\uFEFF?---[ \t]*\r?\n/.test(source))
throw new Error( throw new Error(message("Close the YAML properties block before editing this note."));
"Close the YAML properties block before editing this note.",
);
const doc = match const doc = match
? parseDocument(match[3], { uniqueKeys: true, keepSourceTokens: true }) ? parseDocument(match[3], { uniqueKeys: true, keepSourceTokens: true })
: new Document({}); : new Document({});
if (doc.errors.length || doc.warnings.length) if (doc.errors.length || doc.warnings.length)
throw new Error( throw new Error(message("Fix invalid or unsupported YAML properties before editing this note."));
"Fix invalid or unsupported YAML properties before editing this note.",
);
if (!isMap(doc.contents)) if (!isMap(doc.contents))
throw new Error("Note properties must be a YAML mapping."); throw new Error(message("Note properties must be a YAML mapping."));
return { return {
match, match,
doc, doc,
@@ -48,22 +45,22 @@ export function readTask(path: string, source: string): Task | null {
typeof pm.id !== "string" || typeof pm.id !== "string" ||
!pm.id.trim() !pm.id.trim()
) { ) {
throw new Error("This note has an unsupported Project Management schema, kind, or ID."); throw new Error(message("This note has an unsupported Project Management schema, kind, or ID."));
} }
if (pm.archived !== undefined && typeof pm.archived !== "boolean") if (pm.archived !== undefined && typeof pm.archived !== "boolean")
throw new Error("Archive state must be true or false."); throw new Error(message("The archive state must be true or false."));
if ( if (
pm.due !== undefined && pm.due !== undefined &&
(!record(pm.due) || typeof pm.due.date !== "string") (!record(pm.due) || typeof pm.due.date !== "string")
) )
throw new Error("This preview supports date-only deadlines."); throw new Error(message("This preview supports date-only deadlines."));
if ( if (
pm.plan !== undefined && pm.plan !== undefined &&
(!record(pm.plan) || (!record(pm.plan) ||
typeof pm.plan.start !== "string" || typeof pm.plan.start !== "string" ||
typeof pm.plan.end !== "string") typeof pm.plan.end !== "string")
) )
throw new Error("The plan needs a start and an exclusive end date."); throw new Error(message("The plan needs a start and an exclusive end date."));
if ( if (
pm.sessions !== undefined && pm.sessions !== undefined &&
(!Array.isArray(pm.sessions) || (!Array.isArray(pm.sessions) ||
@@ -76,7 +73,7 @@ export function readTask(path: string, source: string): Task | null {
typeof value.timeZone !== "string", typeof value.timeZone !== "string",
)) ))
) { ) {
throw new Error("Sessions need an ID, start, end, and time zone."); throw new Error(message("Sessions need an ID, start, end, and time zone."));
} }
const task: Task = { const task: Task = {
id: pm.id, id: pm.id,
@@ -126,7 +123,7 @@ export function editTask(
): string { ): string {
const fields = { ...task, title: undefined, ...patch }; const fields = { ...task, title: undefined, ...patch };
if (Object.hasOwn(patch, "createdAt") && patch.createdAt !== task.createdAt) if (Object.hasOwn(patch, "createdAt") && patch.createdAt !== task.createdAt)
throw new Error("The card creation timestamp cannot change."); throw new Error(message("The card creation timestamp cannot change."));
validateFields(fields); validateFields(fields);
const { doc, match, newline } = split(task.source); const { doc, match, newline } = split(task.source);
for (const key of [ for (const key of [
@@ -180,7 +177,7 @@ export function newTask(
/[. ]$/.test(title) || /[. ]$/.test(title) ||
/^(con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(title) /^(con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(title)
) )
throw new Error("Use a valid note name of 1 to 100 characters."); throw new Error(message("Use a valid note name of 1 to 100 characters."));
validateFields(fields); validateFields(fields);
const doc = new Document({ const doc = new Document({
runestone_pm: { schema: 1, id, kind: "task", ...fields, createdAt: fields.createdAt ?? new Date().toISOString() }, runestone_pm: { schema: 1, id, kind: "task", ...fields, createdAt: fields.createdAt ?? new Date().toISOString() },
@@ -194,9 +191,7 @@ export function adoptNote(path: string, source: string): string {
if (readTask(path, source)) return source; if (readTask(path, source)) return source;
const { doc, body, match, newline } = split(source); const { doc, body, match, newline } = split(source);
if (doc.has("runestone_pm")) if (doc.has("runestone_pm"))
throw new Error( throw new Error(message("This document already contains Project Management data and cannot become a task."));
"This document already contains Project Management data and cannot become a task.",
);
doc.set("runestone_pm", { doc.set("runestone_pm", {
schema: 1, schema: 1,
id: crypto.randomUUID(), id: crypto.randomUUID(),
+2 -1
View File
@@ -1,4 +1,5 @@
import type { Task } from "../model/model.ts"; import type { Task } from "../model/model.ts";
import { message } from "./message.ts";
const digits = "0123456789abcdefghijklmnopqrstuvwxyz"; const digits = "0123456789abcdefghijklmnopqrstuvwxyz";
const encode = (text: string) => const encode = (text: string) =>
@@ -27,7 +28,7 @@ export function compareCards(a: Task, b: Task, boardId?: string): number {
export function orderBetween(lower?: string, upper?: string): string { export function orderBetween(lower?: string, upper?: string): string {
if (lower !== undefined && upper !== undefined && lower >= upper) if (lower !== undefined && upper !== undefined && lower >= upper)
throw new Error("The card order changed. Refresh the board."); throw new Error(message("The card order changed. Refresh the board."));
let result = ""; let result = "";
for (let index = 0; ; index++) { for (let index = 0; ; index++) {
const low = const low =
+4 -5
View File
@@ -1,4 +1,5 @@
import type { Workspace } from "../model/model.ts"; import type { Workspace } from "../model/model.ts";
import { message } from "./message.ts";
export const storageRoot = ".runestone/pm"; export const storageRoot = ".runestone/pm";
export const privateRulesPath = `${storageRoot}/.gitignore`; export const privateRulesPath = `${storageRoot}/.gitignore`;
@@ -10,7 +11,7 @@ export const isHiddenCard = (path: string) =>
/** Install the local exclusion before publishing any private Project Management data. */ /** Install the local exclusion before publishing any private Project Management data. */
export async function ensurePrivateStorage(workspace: Workspace) { export async function ensurePrivateStorage(workspace: Workspace) {
if (!workspace.readOptional || !workspace.create) if (!workspace.readOptional || !workspace.create)
throw new Error("Update RuneStone to use hidden Project Management storage."); throw new Error(message("Update RuneStone to use hidden Project Management storage."));
const expected = await workspace.readOptional(privateRulesPath); const expected = await workspace.readOptional(privateRulesPath);
const rules = expected const rules = expected
?.split(/\r?\n/) ?.split(/\r?\n/)
@@ -28,9 +29,7 @@ export async function ensurePrivateStorage(workspace: Workspace) {
} }
} else await workspace.write(privateRulesPath, source, expected); } else await workspace.write(privateRulesPath, source, expected);
if ((await workspace.readOptional(privateRulesPath)) !== source) if ((await workspace.readOptional(privateRulesPath)) !== source)
throw new Error( throw new Error(message("The Project Management Git exclusion changed. Retry before saving private data."));
"The Project Management Git exclusion changed. Retry before saving private data.",
);
} }
/** Older hosts cannot discover hidden files through the root listing. */ /** Older hosts cannot discover hidden files through the root listing. */
@@ -55,7 +54,7 @@ export async function saveDocument(
await ensurePrivateStorage(workspace); await ensurePrivateStorage(workspace);
if (expected === null) { if (expected === null) {
if (!workspace.create) if (!workspace.create)
throw new Error("Update RuneStone to create Project Management storage."); throw new Error(message("Update RuneStone to create Project Management storage."));
await workspace.create(path, source); await workspace.create(path, source);
} else await workspace.write(path, source, expected); } else await workspace.write(path, source, expected);
} }
+2 -1
View File
@@ -1,4 +1,5 @@
import type { Workspace } from "../model/model.ts"; import type { Workspace } from "../model/model.ts";
import { message } from "./message.ts";
// Limit concurrent bridge requests, including large workspaces with many notes. // Limit concurrent bridge requests, including large workspaces with many notes.
export const scanConcurrency = 8; export const scanConcurrency = 8;
@@ -12,7 +13,7 @@ export async function readSources(workspace: Workspace, paths: string[]) {
const rows = await workspace.readMany(batch); const rows = await workspace.readMany(batch);
for (const path of batch) { for (const path of batch) {
const row = rows.find(row => row.path === path); const row = rows.find(row => row.path === path);
results.set(path, row && (typeof row.source === "string" || row.error) ? row : { error: "The batch did not return this file." }); results.set(path, row && (typeof row.source === "string" || row.error) ? row : { error: message("The batch did not return this file.") });
} }
} }
} else { } else {
+3 -2
View File
@@ -1,4 +1,5 @@
import type { MenuHost } from "./host.ts"; import type { MenuHost } from "./host.ts";
import { tr } from "../../../i18n/index.ts";
/** Keep form values native while the host renders every choice menu. */ /** Keep form values native while the host renders every choice menu. */
export function createSharedChoices(root: HTMLElement, ui: MenuHost) { export function createSharedChoices(root: HTMLElement, ui: MenuHost) {
@@ -20,7 +21,7 @@ export function createSharedChoices(root: HTMLElement, ui: MenuHost) {
use(select: HTMLSelectElement) { use(select: HTMLSelectElement) {
const existing = choices.get(select); const existing = choices.get(select);
if (existing) { existing.update(); return existing.trigger; } if (existing) { existing.update(); return existing.trigger; }
const label = select.getAttribute("aria-label") ?? select.closest("label")?.firstChild?.textContent?.trim() ?? "Choose"; const label = select.getAttribute("aria-label") ?? select.closest("label")?.firstChild?.textContent?.trim() ?? tr("Choose");
const trigger = document.createElement("button"); const trigger = document.createElement("button");
trigger.type = "button"; trigger.type = "button";
trigger.className = "pm-button pm-choice-button"; trigger.className = "pm-button pm-choice-button";
@@ -31,7 +32,7 @@ export function createSharedChoices(root: HTMLElement, ui: MenuHost) {
icon.innerHTML = '<svg viewBox="0 0 24 24" aria-hidden="true"><path d="m6 9 6 6 6-6"/></svg>'; icon.innerHTML = '<svg viewBox="0 0 24 24" aria-hidden="true"><path d="m6 9 6 6 6-6"/></svg>';
trigger.append(text, icon); trigger.append(text, icon);
const update = () => { const update = () => {
const value = select.selectedOptions[0]?.textContent ?? "Choose"; const value = select.selectedOptions[0]?.textContent ?? tr("Choose");
if (text.textContent !== value) text.textContent = value; if (text.textContent !== value) text.textContent = value;
if (trigger.disabled !== select.disabled) trigger.disabled = select.disabled; if (trigger.disabled !== select.disabled) trigger.disabled = select.disabled;
}; };
+16 -3
View File
@@ -1,6 +1,21 @@
import { cardColors } from "../model/model.ts"; import { cardColors } from "../model/model.ts";
import { message, tr } from "../../../i18n/index.ts";
// Labels retain the saved color names and use a vivid palette for recognition. /** The English name of each saved color, a catalog key. `colorName()` translates it. */
export const colorNames: Record<keyof typeof cardColors, string> = {
red: message("Red"), orange: message("Orange"), amber: message("Amber"), yellow: message("Yellow"),
lime: message("Lime"), green: message("Green"), teal: message("Teal"), cyan: message("Cyan"),
blue: message("Blue"), indigo: message("Indigo"), purple: message("Purple"), magenta: message("Magenta"),
pink: message("Pink"), brown: message("Brown"), slate: message("Slate"), gray: message("Gray"),
};
/** The name of a saved color in the language of the interface. An empty value is no color. */
export function colorName(value: string): string {
if (!value) return tr("None");
return Object.hasOwn(colorNames, value) ? tr(colorNames[value as keyof typeof cardColors]) : value;
}
// Labels keep the saved color names and use a vivid palette, so that the user can recognize them.
export const labelColors: Record<keyof typeof cardColors, string> = { export const labelColors: Record<keyof typeof cardColors, string> = {
red: "#ff0000", orange: "#ff8000", amber: "#ffb000", yellow: "#ffe000", red: "#ff0000", orange: "#ff8000", amber: "#ffb000", yellow: "#ffe000",
lime: "#99ee00", green: "#00cc66", teal: "#00bfa5", cyan: "#00ccff", lime: "#99ee00", green: "#00cc66", teal: "#00bfa5", cyan: "#00ccff",
@@ -37,8 +52,6 @@ export function createColorPalette(
current.setAttribute("aria-hidden", "true"); current.setAttribute("aria-hidden", "true");
const group = "pm-colors-" + crypto.randomUUID(); const group = "pm-colors-" + crypto.randomUUID();
const inputs: HTMLInputElement[] = []; const inputs: HTMLInputElement[] = [];
const colorName = (value: string) =>
value ? value[0].toUpperCase() + value.slice(1) : "None";
const values = [...(allowNone ? [""] : []), ...Object.keys(cardColors)]; const values = [...(allowNone ? [""] : []), ...Object.keys(cardColors)];
let selected = initial; let selected = initial;
const set = (value: string) => { const set = (value: string) => {
+15 -12
View File
@@ -1,15 +1,18 @@
import { tooltip } from "./host.ts"; import { tooltip } from "./host.ts";
/** Find within the Markdown field, using the host's shared Find presentation. */ import { tr } from "../../../i18n/index.ts";
/** Find in the Markdown field, with the shared Find presentation of the host. */
export function createDescriptionFind(textarea: HTMLTextAreaElement) { export function createDescriptionFind(textarea: HTMLTextAreaElement) {
const element = document.createElement("section"); const element = document.createElement("section");
element.className = "rs-find-bar"; element.className = "rs-find-bar";
element.setAttribute("aria-label", "Find in description"); element.setAttribute("aria-label", tr("Find in description"));
element.hidden = true; element.hidden = true;
element.innerHTML = `<div class="rs-find-row"> element.innerHTML = `<div class="rs-find-row">
<div class="rs-find-field"><span class="pm-icon" aria-hidden="true"><svg viewBox="0 0 24 24"><circle cx="10" cy="10" r="7"/><path d="m15 15 6 6"/></svg></span><input type="text" name="search" autocomplete="off" aria-label="Find in description" placeholder="Find in description"></div> <div class="rs-find-field"><span class="pm-icon" aria-hidden="true"><svg viewBox="0 0 24 24"><circle cx="10" cy="10" r="7"/><path d="m15 15 6 6"/></svg></span><input type="text" name="search" autocomplete="off"></div>
<div class="rs-find-actions"></div> <div class="rs-find-actions"></div>
</div><div class="rs-find-options"></div>`; </div><div class="rs-find-options"></div>`;
const input = element.querySelector("input")!; const input = element.querySelector("input")!;
input.setAttribute("aria-label", tr("Find in description"));
input.placeholder = tr("Find in description");
const actions = element.querySelector(".rs-find-actions")!; const actions = element.querySelector(".rs-find-actions")!;
const options = element.querySelector(".rs-find-options")!; const options = element.querySelector(".rs-find-options")!;
const status = document.createElement("span"); const status = document.createElement("span");
@@ -45,9 +48,9 @@ export function createDescriptionFind(textarea: HTMLTextAreaElement) {
wrapper.append(checkbox, document.createTextNode(label)); options.append(wrapper); wrapper.append(checkbox, document.createTextNode(label)); options.append(wrapper);
return checkbox; return checkbox;
} }
const matchCase = option("Match case"); const matchCase = option(tr("Match case"));
const wholeWord = option("Whole word"); const wholeWord = option(tr("Whole word"));
const regex = option("Regex"); const regex = option(tr("Regex"));
options.append(status); options.append(status);
function close() { function close() {
hide(); hide();
@@ -64,11 +67,11 @@ export function createDescriptionFind(textarea: HTMLTextAreaElement) {
button.onclick = run; actions.append(button); button.onclick = run; actions.append(button);
return button; return button;
} }
const previous = action("Previous match (Shift+Enter)", "m18 15-6-6-6 6", () => next(true)); const previous = action(tr("Previous match (Shift+Enter)"), "m18 15-6-6-6 6", () => next(true));
const following = action("Next match (Enter)", "m6 9 6 6 6-6", () => next()); const following = action(tr("Next match (Enter)"), "m6 9 6 6 6-6", () => next());
action("Close find (Escape)", "m6 6 12 12M18 6 6 18", close); action(tr("Close find (Escape)"), "m6 6 12 12M18 6 6 18", close);
function announce() { function announce() {
status.textContent = input.value ? (matches.length ? `${current < 0 ? 0 : current + 1} of ${matches.length}` : "No matches") : ""; status.textContent = input.value ? (matches.length ? tr("{current} of {total}", { current: current < 0 ? 0 : current + 1, total: matches.length }) : tr("No matches")) : "";
} }
function refresh() { function refresh() {
current = -1; matches = []; current = -1; matches = [];
@@ -85,7 +88,7 @@ export function createDescriptionFind(textarea: HTMLTextAreaElement) {
} }
} }
previous.disabled = following.disabled = !matches.length; previous.disabled = following.disabled = !matches.length;
if (input.getAttribute("aria-invalid") === "true") status.textContent = "Invalid expression"; if (input.getAttribute("aria-invalid") === "true") status.textContent = tr("Invalid expression");
else announce(); else announce();
paint(); paint();
} }
@@ -95,7 +98,7 @@ export function createDescriptionFind(textarea: HTMLTextAreaElement) {
const match = matches[current]; const match = matches[current];
returnStart = match.from; returnEnd = match.to; returnStart = match.from; returnEnd = match.to;
textarea.setSelectionRange(match.from, match.to); textarea.setSelectionRange(match.from, match.to);
// Reveal the matching line without moving focus out of the Find controls. // Show the matching line, but keep the focus in the Find controls.
const style = getComputedStyle(textarea); const style = getComputedStyle(textarea);
const mirror = document.createElement("div"); const mirror = document.createElement("div");
mirror.style.cssText = `position:absolute;visibility:hidden;white-space:pre-wrap;overflow-wrap:break-word;box-sizing:border-box;width:${textarea.clientWidth}px;font:${style.font};line-height:${style.lineHeight};padding:${style.padding}`; mirror.style.cssText = `position:absolute;visibility:hidden;white-space:pre-wrap;overflow-wrap:break-word;box-sizing:border-box;width:${textarea.clientWidth}px;font:${style.font};line-height:${style.lineHeight};padding:${style.padding}`;
+27 -23
View File
@@ -3,37 +3,41 @@ import type { createCardImages } from "./images-ui.ts";
import { renderMarkdown } from "../model/markdown.ts"; import { renderMarkdown } from "../model/markdown.ts";
import { headingEdit } from "../model/description-format.ts"; import { headingEdit } from "../model/description-format.ts";
import { createDescriptionFind } from "./description-find.ts"; import { createDescriptionFind } from "./description-find.ts";
import { tr } from "../../../i18n/index.ts";
import { message } from "../storage/message.ts";
/** Description edits and formatted content share the card detail view. */ /** Description edits and formatted content share the card detail view. */
export function createDescriptionEditor( export function createDescriptionEditor(
textarea: HTMLTextAreaElement, textarea: HTMLTextAreaElement,
images: ReturnType<typeof createCardImages>, images: ReturnType<typeof createCardImages>,
/** Make a control. `name` is a catalog key in English. The control shows its translation. */
control: (name: string, action: () => void) => HTMLButtonElement, control: (name: string, action: () => void) => HTMLButtonElement,
persistence?: { save(): Promise<void>; cancel(): Promise<string>; }, persistence?: { save(): Promise<void>; cancel(): Promise<string>; },
) { ) {
const element = document.createElement("section"); const element = document.createElement("section");
element.className = "pm-description-editor pm-wide"; element.className = "pm-description-editor pm-wide";
element.setAttribute("aria-label", "Description"); element.setAttribute("aria-label", tr("Description"));
const header = document.createElement("div"); const header = document.createElement("div");
header.className = "pm-description-heading"; header.className = "pm-description-heading";
const heading = document.createElement("h3"); const heading = document.createElement("h3");
const toggleSection = document.createElement("button"); const toggleSection = document.createElement("button");
toggleSection.type = "button"; toggleSection.className = "pm-section-toggle"; toggleSection.type = "button"; toggleSection.className = "pm-section-toggle";
toggleSection.innerHTML = '<svg viewBox="0 0 24 24" aria-hidden="true"><path d="m6 9 6 6 6-6"/></svg><span>Description</span>'; toggleSection.innerHTML = '<svg viewBox="0 0 24 24" aria-hidden="true"><path d="m6 9 6 6 6-6"/></svg><span></span>';
toggleSection.lastElementChild!.textContent = tr("Description");
toggleSection.setAttribute("aria-expanded", "true"); heading.append(toggleSection); toggleSection.setAttribute("aria-expanded", "true"); heading.append(toggleSection);
const source = document.createElement("label"); const source = document.createElement("label");
source.className = "pm-field pm-description-source"; source.className = "pm-field pm-description-source";
textarea.setAttribute("aria-label", "Details (Markdown)"); textarea.setAttribute("aria-label", tr("Details (Markdown)"));
source.append(textarea); source.append(textarea);
const find = createDescriptionFind(textarea); const find = createDescriptionFind(textarea);
const preview = document.createElement("div"); const preview = document.createElement("div");
preview.className = "pm-markdown-preview"; preview.className = "pm-markdown-preview";
preview.setAttribute("role", "region"); preview.setAttribute("role", "region");
preview.setAttribute("aria-label", "Description preview"); preview.setAttribute("aria-label", tr("Description preview"));
const toolbar = document.createElement("div"); const toolbar = document.createElement("div");
toolbar.className = "pm-description-toolbar"; toolbar.className = "pm-description-toolbar";
toolbar.setAttribute("role", "group"); toolbar.setAttribute("role", "group");
toolbar.setAttribute("aria-label", "Markdown formatting"); toolbar.setAttribute("aria-label", tr("Markdown formatting"));
textarea.spellcheck = true; textarea.spellcheck = true;
const resize = () => { const resize = () => {
if (source.hidden || !textarea.isConnected) return; if (source.hidden || !textarea.isConnected) return;
@@ -57,7 +61,7 @@ export function createDescriptionEditor(
let pending = false; let pending = false;
const unsaved = document.createElement("span"); const unsaved = document.createElement("span");
unsaved.className = "pm-description-unsaved"; unsaved.className = "pm-description-unsaved";
unsaved.textContent = "Unsaved changes"; unsaved.textContent = tr("Unsaved changes");
unsaved.hidden = true; unsaved.hidden = true;
unsaved.setAttribute("aria-live", "polite"); unsaved.setAttribute("aria-live", "polite");
function insert(before: string, after: string, placeholder: string) { function insert(before: string, after: string, placeholder: string) {
@@ -69,7 +73,7 @@ export function createDescriptionEditor(
textarea.focus(); textarea.focus();
} }
const formatting = [ const formatting = [
control("Heading", () => { control(message("Heading"), () => {
const edit = headingEdit(textarea.value, textarea.selectionStart, textarea.selectionEnd); const edit = headingEdit(textarea.value, textarea.selectionStart, textarea.selectionEnd);
const direction = textarea.selectionDirection; const direction = textarea.selectionDirection;
textarea.setRangeText(edit.text, edit.start, edit.end, "preserve"); textarea.setRangeText(edit.text, edit.start, edit.end, "preserve");
@@ -77,52 +81,52 @@ export function createDescriptionEditor(
textarea.dispatchEvent(new Event("input", { bubbles: true })); textarea.dispatchEvent(new Event("input", { bubbles: true }));
textarea.focus(); textarea.focus();
}), }),
control("Bold", () => insert("**", "**", "Bold text")), control(message("Bold"), () => insert("**", "**", tr("Bold text"))),
control("Italic", () => insert("*", "*", "Italic text")), control(message("Italic"), () => insert("*", "*", tr("Italic text"))),
control("Bullet list", () => insert("\n- ", "\n", "List item")), control(message("Bullet list"), () => insert("\n- ", "\n", tr("List item"))),
control("Link", () => insert("[", "](https://example.com)", "Link text")), control(message("Link"), () => insert("[", "](https://example.com)", tr("Link text"))),
control("Code", () => insert("`", "`", "Code")), control(message("Code"), () => insert("`", "`", tr("Code"))),
]; ];
async function render() { async function render() {
const current = ++revision; const current = ++revision;
const body = persistence && !editing ? original : textarea.value; const body = persistence && !editing ? original : textarea.value;
preview.innerHTML = renderMarkdown(body); preview.innerHTML = renderMarkdown(body);
if (!body.trim()) preview.textContent = "Add a description."; if (!body.trim()) preview.textContent = tr("Add a description.");
for (const image of preview.querySelectorAll<HTMLImageElement>("img[data-pm-image]")) { for (const image of preview.querySelectorAll<HTMLImageElement>("img[data-pm-image]")) {
const trigger = document.createElement("button"); const trigger = document.createElement("button");
trigger.type = "button"; trigger.type = "button";
trigger.className = "pm-image-preview-trigger"; trigger.className = "pm-image-preview-trigger";
trigger.setAttribute("aria-label", `View image ${image.alt}`); trigger.setAttribute("aria-label", tr("View image {name}", { name: image.alt }));
image.removeAttribute("title"); image.removeAttribute("title");
trigger.onclick = () => images.showImage(image, trigger); trigger.onclick = () => images.showImage(image, trigger);
image.replaceWith(trigger); image.replaceWith(trigger);
tooltip(trigger, `View image ${image.alt}`); tooltip(trigger, tr("View image {name}", { name: image.alt }));
trigger.append(image); trigger.append(image);
const fail = (message: string) => trigger.replaceWith(document.createTextNode(message)); const fail = (message: string) => trigger.replaceWith(document.createTextNode(message));
try { try {
const data = await images.resolveImage(image.dataset.pmImage!); const data = await images.resolveImage(image.dataset.pmImage!);
if (disposed || current !== revision) return; if (disposed || current !== revision) return;
image.src = data; image.src = data;
image.onerror = () => fail(`Cannot display image: ${image.alt}`); image.onerror = () => fail(tr("Cannot display image: {name}", { name: image.alt }));
} catch { } catch {
if (!disposed && current === revision) if (!disposed && current === revision)
fail(`Cannot load image: ${image.alt}`); fail(tr("Cannot load image: {name}", { name: image.alt }));
} }
} }
} }
const edit = control("Edit", () => { const edit = control(message("Edit"), () => {
if (!persistence) original = textarea.value; if (!persistence) original = textarea.value;
editing = true; editing = true;
update(); update();
textarea.focus(); textarea.focus();
resize(); resize();
}); });
const toggle = control("Preview", () => { const toggle = control(message("Preview"), () => {
if (!find.element.hidden) find.close(); if (!find.element.hidden) find.close();
source.hidden = !source.hidden; source.hidden = !source.hidden;
preview.hidden = !source.hidden; preview.hidden = !source.hidden;
images.setEditing(!source.hidden); images.setEditing(!source.hidden);
toggle.lastChild!.textContent = source.hidden ? "Edit Markdown" : "Preview"; toggle.lastChild!.textContent = source.hidden ? tr("Edit Markdown") : tr("Preview");
toggle.setAttribute("aria-pressed", String(source.hidden)); toggle.setAttribute("aria-pressed", String(source.hidden));
if (source.hidden) void render(); if (source.hidden) void render();
updateLoading(); updateLoading();
@@ -147,8 +151,8 @@ export function createDescriptionEditor(
} catch { /* The card editor shows the persistence error. */ } } catch { /* The card editor shows the persistence error. */ }
finally { pending = false; updateLoading(); } finally { pending = false; updateLoading(); }
}; };
const cancel = control("Cancel", () => { void finish(true); }); const cancel = control(message("Cancel"), () => { void finish(true); });
const apply = control("Save", () => { void finish(false); }); const apply = control(message("Save"), () => { void finish(false); });
actions.append(cancel, apply); actions.append(cancel, apply);
for (const item of [...formatting, images.addControl]) { for (const item of [...formatting, images.addControl]) {
const name = item.textContent ?? ""; const name = item.textContent ?? "";
@@ -187,7 +191,7 @@ export function createDescriptionEditor(
source.hidden = !editing; source.hidden = !editing;
images.setEditing(editing); images.setEditing(editing);
preview.hidden = editing; preview.hidden = editing;
toggle.lastChild!.textContent = "Preview"; toggle.lastChild!.textContent = tr("Preview");
toggle.setAttribute("aria-pressed", "false"); toggle.setAttribute("aria-pressed", "false");
updateLoading(); updateLoading();
if (!editing) void render(); if (!editing) void render();
+7 -5
View File
@@ -1,19 +1,21 @@
/** A searchable field picker. Field forms stay inside the card draft. */ import { tr } from "../../../i18n/index.ts";
/** A field picker with a search. The field forms stay in the card draft. */
export function createDetailsPicker(trigger: HTMLButtonElement) { export function createDetailsPicker(trigger: HTMLButtonElement) {
const panel = document.createElement("div"); const panel = document.createElement("div");
panel.className = "pm-label-options pm-details-picker rs-picker"; panel.className = "pm-label-options pm-details-picker rs-picker";
panel.id = `pm-details-${crypto.randomUUID()}`; panel.id = `pm-details-${crypto.randomUUID()}`;
panel.popover = "auto"; panel.popover = "auto";
panel.setAttribute("role", "dialog"); panel.setAttribute("role", "dialog");
panel.setAttribute("aria-label", "Add card details"); panel.setAttribute("aria-label", tr("Add card details"));
const search = document.createElement("input"); const search = document.createElement("input");
search.type = "search"; search.type = "search";
search.placeholder = "Find a detail"; search.placeholder = tr("Find a detail");
search.setAttribute("aria-label", "Find a detail"); search.setAttribute("aria-label", tr("Find a detail"));
const choices = document.createElement("div"); const choices = document.createElement("div");
choices.className = "pm-detail-choices"; choices.className = "pm-detail-choices";
const empty = document.createElement("p"); const empty = document.createElement("p");
empty.textContent = "No matching details."; empty.textContent = tr("No matching details.");
empty.hidden = true; empty.hidden = true;
panel.append(search, choices, empty); panel.append(search, choices, empty);
trigger.popoverTargetElement = panel; trigger.popoverTargetElement = panel;
+27 -28
View File
@@ -1,4 +1,6 @@
import { tooltip } from "./host.ts"; import { tooltip } from "./host.ts";
import { message, tr } from "../../../i18n/index.ts";
import { errorText } from "./text.ts";
import type { Workspace, TaskFields } from "../model/model.ts"; import type { Workspace, TaskFields } from "../model/model.ts";
import { import {
imageMarkdown, imageMarkdown,
@@ -10,10 +12,11 @@ import {
saveImages, saveImages,
} from "../storage/images.ts"; } from "../storage/images.ts";
/** Image data stays outside card Markdown and loads only in the open editor. */ /** The image data stays outside the card Markdown and loads only in the open editor. */
export function createCardImages( export function createCardImages(
workspace: Workspace, workspace: Workspace,
description: HTMLTextAreaElement, description: HTMLTextAreaElement,
/** Make a control. `name` is a catalog key in English. The control shows its translation. */
control: (name: string, action: () => void) => HTMLButtonElement, control: (name: string, action: () => void) => HTMLButtonElement,
removeControl: (name: string, action: () => void) => HTMLButtonElement, removeControl: (name: string, action: () => void) => HTMLButtonElement,
changed: (loading: boolean) => void, changed: (loading: boolean) => void,
@@ -25,8 +28,7 @@ export function createCardImages(
const hint = document.createElement("p"); const hint = document.createElement("p");
hint.className = "pm-muted"; hint.className = "pm-muted";
hint.id = `pm-image-hint-${crypto.randomUUID()}`; hint.id = `pm-image-hint-${crypto.randomUUID()}`;
hint.textContent = hint.textContent = tr("Paste or drop an image into Details, or choose Add image. PNG, JPEG, GIF, or WebP. Up to 50 MiB each.");
"Paste or drop an image into Details, or choose Add image. PNG, JPEG, GIF, or WebP. Up to 50 MiB each.";
description.setAttribute("aria-describedby", hint.id); description.setAttribute("aria-describedby", hint.id);
const error = document.createElement("p"); const error = document.createElement("p");
error.className = "pm-error"; error.className = "pm-error";
@@ -34,24 +36,24 @@ export function createCardImages(
const gallery = document.createElement("div"); const gallery = document.createElement("div");
gallery.className = "pm-image-gallery"; gallery.className = "pm-image-gallery";
gallery.setAttribute("role", "group"); gallery.setAttribute("role", "group");
gallery.setAttribute("aria-label", "Images in card details"); gallery.setAttribute("aria-label", tr("Images in card details"));
const input = document.createElement("input"); const input = document.createElement("input");
input.type = "file"; input.type = "file";
input.accept = imageTypes.join(","); input.accept = imageTypes.join(",");
input.multiple = true; input.multiple = true;
input.hidden = true; input.hidden = true;
input.setAttribute("aria-label", "Insert images in description"); input.setAttribute("aria-label", tr("Insert images in description"));
const add = control("Add image", () => input.click()); const add = control(message("Add image"), () => input.click());
const attachmentInput = input.cloneNode() as HTMLInputElement; const attachmentInput = input.cloneNode() as HTMLInputElement;
attachmentInput.setAttribute("aria-label", "Attach images to card"); attachmentInput.setAttribute("aria-label", tr("Attach images to card"));
const attach = control("Attach image", () => attachmentInput.click()); const attach = control(message("Attach image"), () => attachmentInput.click());
const heading = document.createElement("h3"); heading.textContent = "Attachments"; const heading = document.createElement("h3"); heading.textContent = tr("Attachments");
const header = document.createElement("div"); header.className = "pm-attachment-heading"; const header = document.createElement("div"); header.className = "pm-attachment-heading";
header.append(heading, attach); header.append(heading, attach);
const attachmentGallery = document.createElement("div"); attachmentGallery.className = "pm-image-gallery"; const attachmentGallery = document.createElement("div"); attachmentGallery.className = "pm-image-gallery";
attachmentGallery.setAttribute("role", "group"); attachmentGallery.setAttribute("aria-label", "Image attachments"); attachmentGallery.setAttribute("role", "group"); attachmentGallery.setAttribute("aria-label", tr("Image attachments"));
const attachmentsElement = document.createElement("section"); attachmentsElement.className = "pm-attachments pm-wide"; const attachmentsElement = document.createElement("section"); attachmentsElement.className = "pm-attachments pm-wide";
attachmentsElement.setAttribute("aria-label", "Attachments"); attachmentsElement.setAttribute("aria-label", tr("Attachments"));
const attachmentError = document.createElement("p"); attachmentError.className = "pm-error"; attachmentError.setAttribute("role", "alert"); const attachmentError = document.createElement("p"); attachmentError.className = "pm-error"; attachmentError.setAttribute("role", "alert");
attachmentsElement.append(header, attachmentInput, attachmentError, attachmentGallery); attachmentsElement.append(header, attachmentInput, attachmentError, attachmentGallery);
element.append(input, hint, error, gallery); element.append(input, hint, error, gallery);
@@ -87,13 +89,13 @@ export function createCardImages(
full.src = source.src; full.src = source.src;
full.alt = source.alt; full.alt = source.alt;
frame.append(full); frame.append(full);
const size = control("Actual size", () => { const size = control(message("Actual size"), () => {
const actual = frame.classList.toggle("pm-image-actual"); const actual = frame.classList.toggle("pm-image-actual");
size.setAttribute("aria-pressed", String(actual)); size.setAttribute("aria-pressed", String(actual));
placeControls(); placeControls();
}); });
size.setAttribute("aria-pressed", "false"); size.setAttribute("aria-pressed", "false");
const close = removeControl("Close image", () => dialog.close()); const close = removeControl(tr("Close image"), () => dialog.close());
header.append(title, size, close); header.append(title, size, close);
dialog.append(header, frame); dialog.append(header, frame);
const placeControls = () => { const placeControls = () => {
@@ -119,7 +121,7 @@ export function createCardImages(
viewer = undefined; viewer = undefined;
if (!disposed && trigger.isConnected) trigger.focus({ preventScroll: true }); if (!disposed && trigger.isConnected) trigger.focus({ preventScroll: true });
}; };
// Keep the viewer outside the gallery, which is hidden in description previews. // Keep the viewer outside the gallery, because the description preview hides the gallery.
(description.closest(".pm-editor") ?? element.parentElement ?? element).append(dialog); (description.closest(".pm-editor") ?? element.parentElement ?? element).append(dialog);
const outside = (target: EventTarget | null) => target === dialog || target === frame; const outside = (target: EventTarget | null) => target === dialog || target === frame;
let outsidePointer = false; let outsidePointer = false;
@@ -147,7 +149,7 @@ export function createCardImages(
}); });
dialog.showModal(); dialog.showModal();
placeControls(); placeControls();
// Focus the surface first so pointer users can see an unobstructed image. // Focus the surface first, so that a pointer user can see all of the image.
dialog.tabIndex = -1; dialog.tabIndex = -1;
dialog.focus(); dialog.focus();
idleTimer = setTimeout(() => dialog.classList.add("pm-image-controls-idle"), 2000); idleTimer = setTimeout(() => dialog.classList.add("pm-image-controls-idle"), 2000);
@@ -165,7 +167,7 @@ export function createCardImages(
name.title = ref.name; name.title = ref.name;
caption.append( caption.append(
name, name,
removeControl(`Remove image ${ref.name}`, () => { removeControl(tr("Remove image {name}", { name: ref.name }), () => {
if (attached) { if (attached) {
attachments.splice(attachments.findIndex(item => item.id === ref.id), 1); attachments.splice(attachments.findIndex(item => item.id === ref.id), 1);
description.dispatchEvent(new Event("input", { bubbles: true })); description.dispatchEvent(new Event("input", { bubbles: true }));
@@ -192,8 +194,8 @@ export function createCardImages(
const thumbnail = document.createElement("button"); const thumbnail = document.createElement("button");
thumbnail.type = "button"; thumbnail.type = "button";
thumbnail.className = "pm-image-thumbnail"; thumbnail.className = "pm-image-thumbnail";
thumbnail.setAttribute("aria-label", `View image ${ref.name}`); thumbnail.setAttribute("aria-label", tr("View image {name}", { name: ref.name }));
tooltip(thumbnail, `View image ${ref.name}`); tooltip(thumbnail, tr("View image {name}", { name: ref.name }));
thumbnail.onclick = () => showImage(image, thumbnail); thumbnail.onclick = () => showImage(image, thumbnail);
thumbnail.append(image); thumbnail.append(image);
const failure = document.createElement("p"); const failure = document.createElement("p");
@@ -201,7 +203,7 @@ export function createCardImages(
failure.setAttribute("role", "alert"); failure.setAttribute("role", "alert");
const fail = () => { const fail = () => {
thumbnail.remove(); thumbnail.remove();
failure.textContent = `Cannot display ${ref.name}. Restore the image file or remove its reference.`; failure.textContent = tr("Cannot display {name}. Restore the image file or remove its reference.", { name: ref.name });
}; };
image.onerror = fail; image.onerror = fail;
figure.append(thumbnail, caption, failure); figure.append(thumbnail, caption, failure);
@@ -237,9 +239,9 @@ export function createCardImages(
const staged: { id: string; name: string; data: string }[] = []; const staged: { id: string; name: string; data: string }[] = [];
for (const file of files) { for (const file of files) {
if (!imageTypes.includes(file.type)) if (!imageTypes.includes(file.type))
throw new Error("Use a PNG, JPEG, GIF, or WebP image."); throw new Error(message("Use a PNG, JPEG, GIF, or WebP image."));
if (!file.size || file.size > maxImageBytes) if (!file.size || file.size > maxImageBytes)
throw new Error("Use an image between 1 byte and 50 MiB."); throw new Error(message("Use an image between 1 byte and 50 MiB."));
const bytes = new Uint8Array(await file.arrayBuffer()); const bytes = new Uint8Array(await file.arrayBuffer());
let binary = ""; let binary = "";
for (let offset = 0; offset < bytes.length; offset += 8192) for (let offset = 0; offset < bytes.length; offset += 8192)
@@ -247,17 +249,15 @@ export function createCardImages(
...bytes.subarray(offset, offset + 8192), ...bytes.subarray(offset, offset + 8192),
); );
const data = `data:${file.type};base64,${btoa(binary)}`; const data = `data:${file.type};base64,${btoa(binary)}`;
// Decode before inserting a reference, so invalid clipboard files preserve the draft. // Decode the image before the reference goes in, so that an invalid clipboard file keeps the draft.
const image = new Image(); const image = new Image();
image.src = data; image.src = data;
await image.decode().catch(() => { await image.decode().catch(() => {
throw new Error( throw new Error(message("The image cannot be read. Copy it again or choose another file."));
"The image cannot be read. Copy it again or choose another file.",
);
}); });
staged.push({ staged.push({
id: crypto.randomUUID(), id: crypto.randomUUID(),
name: (file.name || "Pasted image").slice(0, 255), name: (file.name || tr("Pasted image")).slice(0, 255),
data, data,
}); });
} }
@@ -271,8 +271,7 @@ export function createCardImages(
description.dispatchEvent(new Event("input", { bubbles: true })); description.dispatchEvent(new Event("input", { bubbles: true }));
} catch (reason) { } catch (reason) {
if (!disposed) if (!disposed)
(attachOnly ? attachmentError : error).textContent = (attachOnly ? attachmentError : error).textContent = errorText(reason);
reason instanceof Error ? reason.message : String(reason);
} finally { } finally {
loading = false; loading = false;
if (!disposed) { if (!disposed) {
+43 -40
View File
@@ -1,6 +1,8 @@
import { type LabelStore, type SavedLabel } from "../storage/labels.ts"; import { type LabelStore, type SavedLabel } from "../storage/labels.ts";
import { actionIcons, tooltip } from "./host.ts"; import { actionIcons, tooltip } from "./host.ts";
import { createColorPalette, labelColors } from "./colors.ts"; import { colorName, createColorPalette, labelColors } from "./colors.ts";
import { tr } from "../../../i18n/index.ts";
import { errorText, localize } from "./text.ts";
function node<K extends keyof HTMLElementTagNameMap>( function node<K extends keyof HTMLElementTagNameMap>(
tag: K, tag: K,
@@ -21,14 +23,14 @@ function control(text: string, action: () => void) {
export function labelBadge(label?: SavedLabel, id = "") { export function labelBadge(label?: SavedLabel, id = "") {
const badge = node( const badge = node(
"span", "span",
label?.name ?? "Unavailable label", label?.name ?? tr("Unavailable label"),
"pm-label-badge", "pm-label-badge",
); );
if (label) if (label)
badge.style.setProperty("--pm-label-color", labelColors[label.color]); badge.style.setProperty("--pm-label-color", labelColors[label.color]);
badge.setAttribute("aria-label", label badge.setAttribute("aria-label", label
? `${label.name} · ${label.color}${label.archived ? " · Archived" : ""}` ? tr(label.archived ? "{name}, {color}, archived" : "{name}, {color}", { name: label.name, color: colorName(label.color) })
: `Unavailable label: ${id}`); : tr("Unavailable label: {id}", { id }));
return badge; return badge;
} }
@@ -39,39 +41,39 @@ export function createLabelPicker(
quickAccess = false, quickAccess = false,
) { ) {
const element = node("section", "", "pm-label-picker pm-wide"); const element = node("section", "", "pm-label-picker pm-wide");
element.setAttribute("aria-label", "Card labels"); element.setAttribute("aria-label", tr("Card labels"));
const selected = new Set(initial); const selected = new Set(initial);
const known = new Set(catalog.value.map((label) => label.id)); const known = new Set(catalog.value.map((label) => label.id));
const chips = node("div", "", "pm-label-chips"); const chips = node("div", "", "pm-label-chips");
chips.setAttribute("role", "group"); chips.setAttribute("role", "group");
chips.setAttribute("aria-label", "Selected labels"); chips.setAttribute("aria-label", tr("Selected labels"));
const panel = node("div", "", "pm-label-options rs-picker"); const panel = node("div", "", "pm-label-options rs-picker");
panel.id = "pm-labels-" + crypto.randomUUID(); panel.id = "pm-labels-" + crypto.randomUUID();
panel.popover = "auto"; panel.popover = "auto";
panel.setAttribute("role", "dialog"); panel.setAttribute("role", "dialog");
panel.setAttribute("aria-label", "Choose labels"); panel.setAttribute("aria-label", tr("Choose labels"));
const toggle = control("", () => {}); const toggle = control("", () => {});
toggle.classList.add("pm-label-add"); toggle.classList.add("pm-label-add");
const plus = node("span", "", "pm-icon"); const plus = node("span", "", "pm-icon");
plus.innerHTML = quickAccess plus.innerHTML = quickAccess
? '<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M3 3h8l10 10-8 8L3 11z"/><circle cx="7.5" cy="7.5" r="1"/></svg>' ? '<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M3 3h8l10 10-8 8L3 11z"/><circle cx="7.5" cy="7.5" r="1"/></svg>'
: `<svg viewBox="0 0 24 24" aria-hidden="true">${actionIcons.plus}</svg>`; : `<svg viewBox="0 0 24 24" aria-hidden="true">${actionIcons.plus}</svg>`;
const toggleText = node("span", quickAccess ? "Labels" : "Add labels"); const toggleText = node("span", tr(quickAccess ? "Labels" : "Add labels"));
toggle.append(plus, toggleText); toggle.append(plus, toggleText);
toggle.setAttribute("aria-label", quickAccess ? "Labels" : "Add labels"); toggle.setAttribute("aria-label", tr(quickAccess ? "Labels" : "Add labels"));
toggle.popoverTargetElement = panel; toggle.popoverTargetElement = panel;
toggle.setAttribute("aria-controls", panel.id); toggle.setAttribute("aria-controls", panel.id);
toggle.setAttribute("aria-expanded", "false"); toggle.setAttribute("aria-expanded", "false");
toggle.setAttribute("aria-haspopup", "dialog"); toggle.setAttribute("aria-haspopup", "dialog");
const search = node("input"); const search = node("input");
search.type = "search"; search.type = "search";
search.placeholder = "Find a label"; search.placeholder = tr("Find a label");
search.setAttribute("aria-label", "Find a label"); search.setAttribute("aria-label", tr("Find a label"));
const choices = node("div", "", "pm-label-choices"); const choices = node("div", "", "pm-label-choices");
choices.setAttribute("role", "group"); choices.setAttribute("role", "group");
choices.setAttribute("aria-label", "Available labels"); choices.setAttribute("aria-label", tr("Available labels"));
const hint = node("p", "", "pm-muted"); const hint = node("p", "", "pm-muted");
const manageButton = control("Manage labels", () => { const manageButton = control(tr("Manage labels"), () => {
close(); close();
toggle.focus(); toggle.focus();
manage(); manage();
@@ -151,17 +153,17 @@ export function createLabelPicker(
}); });
}); });
row.className = "pm-label-option rs-picker-row"; row.className = "pm-label-option rs-picker-row";
row.setAttribute("aria-label", "Add label " + label.name); row.setAttribute("aria-label", tr("Add label {name}", { name: label.name }));
row.append(labelBadge(label)); row.append(labelBadge(label));
choices.append(row); choices.append(row);
}); });
hint.textContent = hint.textContent =
catalog.error || localize(catalog.error) ||
(matches.length (matches.length
? "" ? ""
: search.value.trim() : search.value.trim()
? "No matching labels." ? tr("No matching labels.")
: "No available labels."); : tr("No available labels."));
hint.hidden = !hint.textContent; hint.hidden = !hint.textContent;
manageButton.disabled = catalog.source === undefined; manageButton.disabled = catalog.source === undefined;
position(); position();
@@ -177,7 +179,7 @@ export function createLabelPicker(
drawChoices(); drawChoices();
toggle.focus(); toggle.focus();
}); });
remove.setAttribute("aria-label", "Remove label " + (label?.name ?? id)); remove.setAttribute("aria-label", tr("Remove label {name}", { name: label?.name ?? id }));
tooltip(remove, remove.getAttribute("aria-label")!); tooltip(remove, remove.getAttribute("aria-label")!);
chip.append(remove); chip.append(remove);
chips.insertBefore(chip, toggle.parentElement === chips ? toggle : null); chips.insertBefore(chip, toggle.parentElement === chips ? toggle : null);
@@ -231,61 +233,63 @@ export function createLabelManager(
close: () => void, close: () => void,
) { ) {
const dialog = node("dialog", "", "pm-editor pm-label-manager"); const dialog = node("dialog", "", "pm-editor pm-label-manager");
dialog.setAttribute("aria-label", "Manage labels"); dialog.setAttribute("aria-label", tr("Manage labels"));
const form = node("form"); const form = node("form");
const draft = structuredClone(catalog.value); const draft = structuredClone(catalog.value);
const expected = catalog.source; const expected = catalog.source;
const rows = node("div", "", "pm-label-definitions"); const rows = node("div", "", "pm-label-definitions");
const error = node("p", catalog.error, "pm-error"); const error = node("p", localize(catalog.error), "pm-error");
error.setAttribute("role", "alert"); error.setAttribute("role", "alert");
let saving = false; let saving = false;
const addRow = (label: SavedLabel) => { const addRow = (label: SavedLabel) => {
const row = node("fieldset", "", "pm-label-definition"); const row = node("fieldset", "", "pm-label-definition");
row.setAttribute("aria-label", "Label " + (label.name || "New label")); row.setAttribute("aria-label", tr("Label {name}", { name: label.name || tr("New label") }));
const legend = node("legend"); const legend = node("legend");
const badge = labelBadge(label); const badge = labelBadge(label);
legend.append(badge); legend.append(badge);
const fields = node("div", "", "pm-label-definition-fields"); const fields = node("div", "", "pm-label-definition-fields");
const nameWrap = node("label", "Name", "pm-field"); const nameWrap = node("label", tr("Name"), "pm-field");
const name = node("input"); const name = node("input");
name.value = label.name; name.value = label.name;
name.required = true; name.required = true;
name.maxLength = 80; name.maxLength = 80;
nameWrap.append(name); nameWrap.append(name);
const color = createColorPalette("Color", label.color, (value) => { const color = createColorPalette(tr("Color"), label.color, (value) => {
label.color = value as SavedLabel["color"]; label.color = value as SavedLabel["color"];
update(); update();
}, false, labelColors); }, false, labelColors);
const state = node("span", "", "pm-muted"); const state = node("span", "", "pm-muted");
const update = () => { const update = () => {
row.setAttribute("aria-label", "Label " + (label.name || "New label")); const title = label.name || tr("New label");
badge.textContent = label.name || "New label"; row.setAttribute("aria-label", tr("Label {name}", { name: title }));
badge.textContent = title;
badge.style.setProperty("--pm-label-color", labelColors[label.color]); badge.style.setProperty("--pm-label-color", labelColors[label.color]);
badge.setAttribute("aria-label", `${label.name || "New label"} · ${label.color}`); badge.setAttribute("aria-label", tr("{name}, {color}", { name: title, color: colorName(label.color) }));
state.textContent = label.archived ? "Archived" : ""; state.textContent = label.archived ? tr("Archived") : "";
remove.setAttribute("aria-label", `Delete ${label.name || "new label"}`); remove.setAttribute("aria-label", deleteName());
tooltip(remove, `Delete ${label.name || "new label"}`); tooltip(remove, deleteName());
}; };
name.oninput = () => { name.oninput = () => {
label.name = name.value; label.name = name.value;
update(); update();
}; };
const remove = control("Delete", () => { const deleteName = () => label.name ? tr("Delete {name}", { name: label.name }) : tr("Delete the new label");
const remove = control(tr("Delete"), () => {
draft.splice(draft.indexOf(label), 1); draft.splice(draft.indexOf(label), 1);
row.remove(); row.remove();
add.focus(); add.focus();
}); });
remove.setAttribute("aria-label", `Delete ${label.name || "new label"}`); remove.setAttribute("aria-label", deleteName());
remove.classList.add("pm-icon-button"); remove.classList.add("pm-icon-button");
remove.innerHTML = `<span class="pm-icon"><svg viewBox="0 0 24 24" aria-hidden="true">${actionIcons.trash}</svg></span>`; remove.innerHTML = `<span class="pm-icon"><svg viewBox="0 0 24 24" aria-hidden="true">${actionIcons.trash}</svg></span>`;
tooltip(remove, `Delete ${label.name || "new label"}`); tooltip(remove, deleteName());
fields.append(nameWrap, remove, color.element); fields.append(nameWrap, remove, color.element);
row.append(legend, fields, state); row.append(legend, fields, state);
rows.append(row); rows.append(row);
update(); update();
return name; return name;
}; };
const add = control("New label", () => { const add = control(tr("New label"), () => {
const label: SavedLabel = { const label: SavedLabel = {
id: crypto.randomUUID(), id: crypto.randomUUID(),
name: "", name: "",
@@ -296,25 +300,25 @@ export function createLabelManager(
}); });
draft.forEach(addRow); draft.forEach(addRow);
const actions = node("div", "", "pm-editor-actions"); const actions = node("div", "", "pm-editor-actions");
const cancel = control("Cancel", () => { const cancel = control(tr("Cancel"), () => {
if (!saving) dialog.close(); if (!saving) dialog.close();
}); });
const submit = control("Save labels", () => {}); const submit = control(tr("Save labels"), () => {});
submit.type = "submit"; submit.type = "submit";
submit.classList.add("pm-primary"); submit.classList.add("pm-primary");
actions.append(cancel, submit); actions.append(cancel, submit);
form.append( form.append(
node("h2", "Manage labels"), node("h2", tr("Manage labels")),
node( node(
"p", "p",
"Labels are shared across all boards in this workspace. Name and color changes apply to every card that uses a label.", tr("All boards in this workspace share the labels. A change of name or color applies to each card with the label."),
"pm-muted", "pm-muted",
), ),
rows, rows,
add, add,
node( node(
"p", "p",
"Deleting a label removes it from every card when you save.", tr("When you save, RuneStone removes each deleted label from all cards."),
"pm-muted", "pm-muted",
), ),
error, error,
@@ -335,8 +339,7 @@ export function createLabelManager(
await save(draft, expected); await save(draft, expected);
if (dialog.isConnected) dialog.close(); if (dialog.isConnected) dialog.close();
} catch (reason) { } catch (reason) {
error.textContent = error.textContent = errorText(reason);
reason instanceof Error ? reason.message : String(reason);
} finally { } finally {
saving = false; saving = false;
controls.forEach((control) => { controls.forEach((control) => {
+9 -3
View File
@@ -1,5 +1,11 @@
import type { MenuHost } from "./host.ts"; import type { MenuHost } from "./host.ts";
import { availablePriorities, priorityNames, type Priority, type PriorityLevels } from "../model/model.ts"; import { availablePriorities, priorityNames, type Priority, type PriorityLevels } from "../model/model.ts";
import { tr } from "../../../i18n/index.ts";
/** The name of a priority in the language of the interface, for example "High priority". */
export function priorityLabel(value: Priority | null): string {
return value ? tr("{priority} priority", { priority: tr(priorityNames[value]) }) : tr("No priority");
}
export const priorityIcons: Record<Priority, string> = { export const priorityIcons: Record<Priority, string> = {
highest: '<path d="m6 9 6-6 6 6M6 15l6-6 6 6M6 21l6-6 6 6"/>', highest: '<path d="m6 9 6-6 6 6M6 15l6-6 6 6M6 21l6-6 6 6"/>',
@@ -25,14 +31,14 @@ export function createPriorityPicker(
let changed = false; let changed = false;
trigger.setAttribute("aria-haspopup", "menu"); trigger.setAttribute("aria-haspopup", "menu");
const update = () => { const update = () => {
trigger.lastChild!.textContent = value ? `${priorityNames[value]} priority` : "Priority"; trigger.lastChild!.textContent = value ? priorityLabel(value) : tr("Priority");
setPriorityAppearance(trigger, value); setPriorityAppearance(trigger, value);
}; };
let menu: { close(): void } | undefined; let menu: { close(): void } | undefined;
const open = () => { const open = () => {
menu?.close(); const bounds = trigger.getBoundingClientRect(); menu?.close(); const bounds = trigger.getBoundingClientRect();
menu = ui.showActionMenu({ x: bounds.left, y: bounds.bottom + 4, label: "Choose priority", parent: trigger.closest("dialog") ?? undefined, menu = ui.showActionMenu({ x: bounds.left, y: bounds.bottom + 4, label: tr("Choose priority"), parent: trigger.closest("dialog") ?? undefined,
items: [...availablePriorities(levels), null].map(priority => ({ label: priority ? `${priorityNames[priority]} priority` : "No priority", checked: value === priority, radio: true, items: [...availablePriorities(levels), null].map(priority => ({ label: priorityLabel(priority), checked: value === priority, radio: true,
run: () => { value = priority; changed = true; update(); } })) }); run: () => { value = priority; changed = true; update(); } })) });
}; };
trigger.onclick = open; trigger.onclick = open;
+37 -31
View File
@@ -1,6 +1,12 @@
import { priorityNames, type Task, type TaskFields } from "../model/model.ts"; import type { Task, TaskFields } from "../model/model.ts";
import type { BoardDocument } from "../storage/board.ts"; import type { BoardDocument } from "../storage/board.ts";
import { setPriorityAppearance } from "./priority-ui.ts"; import { priorityLabel, setPriorityAppearance } from "./priority-ui.ts";
import { tr } from "../../../i18n/index.ts";
/** The board and the list of a card placement. A missing name shows as unavailable. */
function placementText(board: string | undefined, list: string | null | undefined): string {
return tr("{board}: {list}", { board: board ?? tr("Unavailable board"), list: list === null ? tr("Unlisted") : list ?? tr("Unavailable list") });
}
export function createRelations( export function createRelations(
task: Task | undefined, tasks: Task[], task: Task | undefined, tasks: Task[],
@@ -20,20 +26,20 @@ export function createRelations(
const removedIncoming = new Map<string, Task>(); const removedIncoming = new Map<string, Task>();
const cardRow = (target: Task | undefined, title: string, action: () => void, relation?: string) => { const cardRow = (target: Task | undefined, title: string, action: () => void, relation?: string) => {
const button = document.createElement("button"); button.type = "button"; button.className = "pm-related-card"; const button = document.createElement("button"); button.type = "button"; button.className = "pm-related-card";
button.setAttribute("aria-label", `Open ${title}`); button.onclick = action; button.setAttribute("aria-label", tr("Open {name}", { name: title })); button.onclick = action;
const name = document.createElement("span"); name.className = "pm-related-title"; const name = document.createElement("span"); name.className = "pm-related-title";
name.textContent = relation ? `${relation}: ${title}` : title; name.textContent = relation ? tr("{relation}: {title}", { relation, title }) : title;
const metadata = document.createElement("span"); metadata.className = "pm-related-metadata"; const metadata = document.createElement("span"); metadata.className = "pm-related-metadata";
const placement = document.createElement("span"); const placement = document.createElement("span");
const positions = Object.entries(target?.placements ?? {}).map(([boardId, position]) => { const positions = Object.entries(target?.placements ?? {}).map(([boardId, position]) => {
const board = boards.find(board => board.id === boardId); const board = boards.find(board => board.id === boardId);
const list = board?.value.lists.find(list => list.id === position.listId); const list = board?.value.lists.find(list => list.id === position.listId);
return `${board?.name ?? "Unavailable board"}: ${position.listId === null ? "Unlisted" : list?.name ?? "Unavailable list"}`; return placementText(board?.name, position.listId === null ? null : list?.name);
}); });
placement.textContent = positions.length ? positions.join(" · ") : "Unlisted"; placement.textContent = positions.length ? positions.join(" · ") : tr("Unlisted");
const priority = document.createElement("span"); priority.className = "pm-related-priority"; const priority = document.createElement("span"); priority.className = "pm-related-priority";
priority.innerHTML = '<span class="pm-icon"></span>'; priority.innerHTML = '<span class="pm-icon"></span>';
priority.append(document.createTextNode(target?.priority ? `${priorityNames[target.priority]} priority` : "No priority")); priority.append(document.createTextNode(priorityLabel(target?.priority ?? null)));
setPriorityAppearance(priority, target?.priority ?? null); setPriorityAppearance(priority, target?.priority ?? null);
metadata.append(placement, priority); button.append(name, metadata); metadata.append(placement, priority); button.append(name, metadata);
return button; return button;
@@ -52,7 +58,7 @@ export function createRelations(
heading.append(toggle); header.append(heading); root.append(header, content); element.append(root); heading.append(toggle); header.append(heading); root.append(header, content); element.append(root);
return { header, content, toggle, expand() { content.hidden = false; toggle.setAttribute("aria-expanded", "true"); } }; return { header, content, toggle, expand() { content.hidden = false; toggle.setAttribute("aria-expanded", "true"); } };
}; };
const sub = section("Subtasks"); const sub = section(tr("Subtasks"));
const rows = document.createElement("div"); rows.className = "pm-subtask-rows"; const rows = document.createElement("div"); rows.className = "pm-subtask-rows";
const count = document.createElement("span"); count.className = "pm-muted"; sub.header.append(count); const count = document.createElement("span"); count.className = "pm-muted"; sub.header.append(count);
const render = () => { const render = () => {
@@ -63,17 +69,17 @@ export function createRelations(
const target = tasks.find(task => task.id === item.taskId); const target = tasks.find(task => task.id === item.taskId);
const done = document.createElement("input"); done.type = "checkbox"; done.checked = target ? target.status === "done" : item.done; const done = document.createElement("input"); done.type = "checkbox"; done.checked = target ? target.status === "done" : item.done;
done.disabled = !!item.taskId; done.disabled = !!item.taskId;
done.setAttribute("aria-label", `Complete ${item.title}`); done.onchange = () => { item.done = done.checked; count.textContent = `${subtasks.filter(item => item.done).length}/${subtasks.length}`; }; done.setAttribute("aria-label", tr("Complete {name}", { name: item.title })); done.onchange = () => { item.done = done.checked; count.textContent = `${subtasks.filter(item => item.done).length}/${subtasks.length}`; };
const title = cardRow(target, target?.title ?? item.title, () => open({ subtaskId: item.id })); const title = cardRow(target, target?.title ?? item.title, () => open({ subtaskId: item.id }));
row.append(done, title, removeControl(`Delete subtask ${item.title}`, () => { subtasks.splice(subtasks.indexOf(item), 1); render(); })); row.append(done, title, removeControl(tr("Delete subtask {name}", { name: item.title }), () => { subtasks.splice(subtasks.indexOf(item), 1); render(); }));
rows.append(row); rows.append(row);
} }
}; };
const draft = document.createElement("input"); draft.placeholder = "New subtask"; draft.maxLength = 200; draft.setAttribute("aria-label", "New subtask"); const draft = document.createElement("input"); draft.placeholder = tr("New subtask"); draft.maxLength = 200; draft.setAttribute("aria-label", tr("New subtask"));
const addRow = document.createElement("div"); addRow.className = "pm-relation-row"; addRow.hidden = true; const addRow = document.createElement("div"); addRow.className = "pm-relation-row"; addRow.hidden = true;
const reveal = control("Add subtask", () => { sub.expand(); addRow.hidden = false; reveal.hidden = true; draft.focus(); }); const reveal = control(tr("Add subtask"), () => { sub.expand(); addRow.hidden = false; reveal.hidden = true; draft.focus(); });
const dismiss = () => { draft.value = ""; add.disabled = true; addRow.hidden = true; reveal.hidden = false; reveal.focus(); }; const dismiss = () => { draft.value = ""; add.disabled = true; addRow.hidden = true; reveal.hidden = false; reveal.focus(); };
const add = control("Create subtask", () => { const add = control(tr("Create subtask"), () => {
if (!draft.value.trim()) return; if (!draft.value.trim()) return;
subtasks.push({ id: crypto.randomUUID(), title: draft.value.trim(), done: false }); render(); dismiss(); subtasks.push({ id: crypto.randomUUID(), title: draft.value.trim(), done: false }); render(); dismiss();
}); });
@@ -83,20 +89,20 @@ export function createRelations(
if (event.key === "Enter") { event.preventDefault(); add.click(); } if (event.key === "Enter") { event.preventDefault(); add.click(); }
if (event.key === "Escape") { event.preventDefault(); event.stopPropagation(); dismiss(); } if (event.key === "Escape") { event.preventDefault(); event.stopPropagation(); dismiss(); }
}; };
addRow.append(draft, add, removeControl("Cancel subtask", dismiss)); addRow.append(draft, add, removeControl(tr("Cancel subtask"), dismiss));
sub.header.append(reveal); sub.content.append(rows, addRow); sub.header.append(reveal); sub.content.append(rows, addRow);
const linkedSection = section("Linked cards"); const linkedSection = section(tr("Linked cards"));
const linked = document.createElement("div"); const linked = document.createElement("div");
const names = { relates: "Relates to", blocks: "Blocks", "blocked-by": "Blocked by" }; const names = { relates: tr("Relates to"), blocks: tr("Blocks"), "blocked-by": tr("Blocked by") };
const search = document.createElement("input"); search.type = "search"; search.placeholder = "Find a card"; search.setAttribute("aria-label", "Find a card to link"); const search = document.createElement("input"); search.type = "search"; search.placeholder = tr("Find a card"); search.setAttribute("aria-label", tr("Find a card to link"));
const choices = document.createElement("div"); choices.className = "pm-link-results rs-picker"; const choices = document.createElement("div"); choices.className = "pm-link-results rs-picker";
choices.id = "pm-link-results-" + crypto.randomUUID(); choices.id = "pm-link-results-" + crypto.randomUUID();
choices.setAttribute("role", "group"); choices.setAttribute("aria-label", "Matching cards"); choices.setAttribute("role", "group"); choices.setAttribute("aria-label", tr("Matching cards"));
search.setAttribute("aria-controls", choices.id); search.setAttribute("aria-controls", choices.id);
const resultStatus = document.createElement("p"); resultStatus.className = "rs-picker-hint"; const resultStatus = document.createElement("p"); resultStatus.className = "rs-picker-hint";
resultStatus.setAttribute("role", "status"); resultStatus.setAttribute("aria-live", "polite"); resultStatus.setAttribute("role", "status"); resultStatus.setAttribute("aria-live", "polite");
const relation = document.createElement("select"); relation.setAttribute("aria-label", "Relationship"); const relation = document.createElement("select"); relation.setAttribute("aria-label", tr("Relationship"));
for (const [value, name] of Object.entries(names)) { const option = document.createElement("option"); option.value = value; option.textContent = name; relation.append(option); } for (const [value, name] of Object.entries(names)) { const option = document.createElement("option"); option.value = value; option.textContent = name; relation.append(option); }
const candidates = () => tasks.filter(item => item.id !== task?.id && !item.archived const candidates = () => tasks.filter(item => item.id !== task?.id && !item.archived
&& !links.some(link => link.taskId === item.id) && !links.some(link => link.taskId === item.id)
@@ -107,7 +113,7 @@ export function createRelations(
const matches = candidates(); const matches = candidates();
for (const item of matches) { for (const item of matches) {
const row = document.createElement("button"); row.type = "button"; row.className = "rs-picker-row"; const row = document.createElement("button"); row.type = "button"; row.className = "rs-picker-row";
row.setAttribute("aria-label", `Link ${item.title}`); row.setAttribute("aria-label", tr("Link {name}", { name: item.title }));
const icon = document.createElement("span"); icon.className = "pm-icon rs-picker-icon"; const icon = document.createElement("span"); icon.className = "pm-icon rs-picker-icon";
icon.innerHTML = '<svg viewBox="0 0 24 24" aria-hidden="true"><path d="m10 13 4-4M8 16l-1 1a4 4 0 0 1-6-6l4-4a4 4 0 0 1 6 0m2 1 1-1a4 4 0 0 1 6 6l-4 4a4 4 0 0 1-6 0"/></svg>'; icon.innerHTML = '<svg viewBox="0 0 24 24" aria-hidden="true"><path d="m10 13 4-4M8 16l-1 1a4 4 0 0 1-6-6l4-4a4 4 0 0 1 6 0m2 1 1-1a4 4 0 0 1 6 6l-4 4a4 4 0 0 1-6 0"/></svg>';
const text = document.createElement("span"); text.className = "pm-link-result-text"; const text = document.createElement("span"); text.className = "pm-link-result-text";
@@ -115,8 +121,8 @@ export function createRelations(
const hint = document.createElement("span"); hint.className = "rs-picker-hint"; const hint = document.createElement("span"); hint.className = "rs-picker-hint";
hint.textContent = Object.entries(item.placements ?? {}).map(([id, position]) => { hint.textContent = Object.entries(item.placements ?? {}).map(([id, position]) => {
const board = boards.find(board => board.id === id); const board = boards.find(board => board.id === id);
return `${board?.name ?? "Unavailable board"}: ${position.listId === null ? "Unlisted" : board?.value.lists.find(list => list.id === position.listId)?.name ?? "Unavailable list"}`; return placementText(board?.name, position.listId === null ? null : board?.value.lists.find(list => list.id === position.listId)?.name);
}).join(" · ") || "Unlisted"; }).join(" · ") || tr("Unlisted");
text.append(title, hint); row.append(icon, text); text.append(title, hint); row.append(icon, text);
row.onclick = () => { row.onclick = () => {
if (!candidates().some(candidate => candidate.id === item.id)) return; if (!candidates().some(candidate => candidate.id === item.id)) return;
@@ -125,7 +131,7 @@ export function createRelations(
}; };
choices.append(row); choices.append(row);
} }
resultStatus.textContent = matches.length ? "" : search.value.trim() ? "No matching cards." : "No available cards to link."; resultStatus.textContent = matches.length ? "" : search.value.trim() ? tr("No matching cards.") : tr("No available cards to link.");
resultStatus.hidden = matches.length > 0; resultStatus.hidden = matches.length > 0;
choices.hidden = matches.length === 0; choices.hidden = matches.length === 0;
}; };
@@ -134,25 +140,25 @@ export function createRelations(
for (const item of links) { for (const item of links) {
const row = document.createElement("div"); row.className = "pm-relation-row"; const row = document.createElement("div"); row.className = "pm-relation-row";
const target = tasks.find(candidate => candidate.id === item.taskId); const target = tasks.find(candidate => candidate.id === item.taskId);
const text = cardRow(target, target?.title ?? "Unavailable card", () => open({ taskId: item.taskId }), names[item.relation]); const text = cardRow(target, target?.title ?? tr("Unavailable card"), () => open({ taskId: item.taskId }), names[item.relation]);
text.disabled = !target; text.disabled = !target;
row.append(text, removeControl(`Unlink ${target?.title ?? "card"}`, () => { links.splice(links.indexOf(item), 1); drawLinks(); })); linked.append(row); row.append(text, removeControl(target ? tr("Unlink {name}", { name: target.title }) : tr("Unlink the card"), () => { links.splice(links.indexOf(item), 1); drawLinks(); })); linked.append(row);
} }
// Inverse links remain visible without duplicate writes to another card. // The inverse links stay visible, but the editor does not write them to the other card.
for (const source of tasks) for (const link of source.links ?? []) if (link.taskId === task?.id && !removedIncoming.has(source.id) && !links.some(item => item.taskId === source.id)) { for (const source of tasks) for (const link of source.links ?? []) if (link.taskId === task?.id && !removedIncoming.has(source.id) && !links.some(item => item.taskId === source.id)) {
const row = document.createElement("div"); row.className = "pm-relation-row"; const row = document.createElement("div"); row.className = "pm-relation-row";
row.append(cardRow(source, source.title, () => open({ taskId: source.id }), link.relation === "blocks" ? "Blocked by" : link.relation === "blocked-by" ? "Blocks" : "Relates to")); row.append(cardRow(source, source.title, () => open({ taskId: source.id }), link.relation === "blocks" ? names["blocked-by"] : link.relation === "blocked-by" ? names.blocks : names.relates));
row.append(removeControl(`Unlink ${source.title}`, () => { removedIncoming.set(source.id, source); drawLinks(); })); row.append(removeControl(tr("Unlink {name}", { name: source.title }), () => { removedIncoming.set(source.id, source); drawLinks(); }));
linked.append(row); linked.append(row);
} }
for (const parent of tasks.filter(source => task && source.subtasks?.some(item => item.taskId === task.id))) { for (const parent of tasks.filter(source => task && source.subtasks?.some(item => item.taskId === task.id))) {
const row = document.createElement("div"); row.className = "pm-relation-row"; const row = document.createElement("div"); row.className = "pm-relation-row";
row.append(cardRow(parent, parent.title, () => open({ taskId: parent.id }), "Subtask of")); linked.append(row); row.append(cardRow(parent, parent.title, () => open({ taskId: parent.id }), tr("Subtask of"))); linked.append(row);
} }
drawChoices(); drawChoices();
}; };
const linkEditor = document.createElement("div"); linkEditor.className = "pm-link-editor"; linkEditor.hidden = true; const linkEditor = document.createElement("div"); linkEditor.className = "pm-link-editor"; linkEditor.hidden = true;
const revealLink = control("Add linked card", () => { linkedSection.expand(); linkEditor.hidden = false; revealLink.hidden = true; search.focus(); }); const revealLink = control(tr("Add linked card"), () => { linkedSection.expand(); linkEditor.hidden = false; revealLink.hidden = true; search.focus(); });
const dismissLink = () => { search.value = ""; drawChoices(); linkEditor.hidden = true; revealLink.hidden = false; revealLink.focus(); }; const dismissLink = () => { search.value = ""; drawChoices(); linkEditor.hidden = true; revealLink.hidden = false; revealLink.focus(); };
search.oninput = drawChoices; search.oninput = drawChoices;
search.onkeydown = event => { search.onkeydown = event => {
@@ -172,7 +178,7 @@ export function createRelations(
rows[event.key === "Home" ? 0 : event.key === "End" ? rows.length - 1 : (index + (event.key === "ArrowDown" ? 1 : rows.length - 1)) % rows.length]?.focus(); rows[event.key === "Home" ? 0 : event.key === "End" ? rows.length - 1 : (index + (event.key === "ArrowDown" ? 1 : rows.length - 1)) % rows.length]?.focus();
}; };
linkEditor.addEventListener("keydown", event => { if (event.key === "Escape") { event.preventDefault(); event.stopPropagation(); dismissLink(); } }); linkEditor.addEventListener("keydown", event => { if (event.key === "Escape") { event.preventDefault(); event.stopPropagation(); dismissLink(); } });
const linkRow = document.createElement("div"); linkRow.className = "pm-relation-row"; linkRow.append(search, relation, removeControl("Cancel linked card", dismissLink)); const linkRow = document.createElement("div"); linkRow.className = "pm-relation-row"; linkRow.append(search, relation, removeControl(tr("Cancel linked card"), dismissLink));
useSharedChoices?.(relation); useSharedChoices?.(relation);
linkEditor.append(linkRow, choices, resultStatus); linkedSection.header.append(revealLink); linkedSection.content.append(linked, linkEditor); linkEditor.append(linkRow, choices, resultStatus); linkedSection.header.append(revealLink); linkedSection.content.append(linked, linkEditor);
render(); drawLinks(); render(); drawLinks();
+8 -7
View File
@@ -1,17 +1,19 @@
import { tr } from "../../../i18n/index.ts";
export function createTagInput(initial: string[], existing: string[]) { export function createTagInput(initial: string[], existing: string[]) {
const element = document.createElement("div"); const element = document.createElement("div");
element.className = "pm-tag-editor pm-wide"; element.className = "pm-tag-editor pm-wide";
const chips = document.createElement("div"); const chips = document.createElement("div");
chips.className = "pm-tag-chips"; chips.className = "pm-tag-chips";
chips.setAttribute("role", "list"); chips.setAttribute("role", "list");
chips.setAttribute("aria-label", "Selected tags"); chips.setAttribute("aria-label", tr("Selected tags"));
const label = document.createElement("label"); const label = document.createElement("label");
label.className = "pm-field"; label.className = "pm-field";
label.textContent = "Add a tag"; label.textContent = tr("Add a tag");
const input = document.createElement("input"); const input = document.createElement("input");
input.type = "text"; input.type = "text";
input.autocomplete = "off"; input.autocomplete = "off";
input.placeholder = "Type a tag and press Enter"; input.placeholder = tr("Type a tag and press Enter");
input.setAttribute("role", "combobox"); input.setAttribute("role", "combobox");
input.setAttribute("aria-autocomplete", "list"); input.setAttribute("aria-autocomplete", "list");
input.setAttribute("aria-expanded", "false"); input.setAttribute("aria-expanded", "false");
@@ -19,14 +21,13 @@ export function createTagInput(initial: string[], existing: string[]) {
suggestions.className = "pm-tag-suggestions rs-picker"; suggestions.className = "pm-tag-suggestions rs-picker";
suggestions.id = "pm-tags-" + crypto.randomUUID(); suggestions.id = "pm-tags-" + crypto.randomUUID();
suggestions.setAttribute("role", "listbox"); suggestions.setAttribute("role", "listbox");
suggestions.setAttribute("aria-label", "Existing tags"); suggestions.setAttribute("aria-label", tr("Existing tags"));
suggestions.hidden = true; suggestions.hidden = true;
input.setAttribute("aria-controls", suggestions.id); input.setAttribute("aria-controls", suggestions.id);
const hint = document.createElement("p"); const hint = document.createElement("p");
hint.className = "pm-muted"; hint.className = "pm-muted";
hint.id = suggestions.id + "-hint"; hint.id = suggestions.id + "-hint";
hint.textContent = hint.textContent = tr("Press Enter to add a tag. Use the arrow keys to choose an existing tag.");
"Press Enter to add a tag. Use the arrow keys to choose an existing tag.";
input.setAttribute("aria-describedby", hint.id); input.setAttribute("aria-describedby", hint.id);
label.append(input); label.append(input);
element.append(chips, label, suggestions, hint); element.append(chips, label, suggestions, hint);
@@ -112,7 +113,7 @@ export function createTagInput(initial: string[], existing: string[]) {
const remove = document.createElement("button"); const remove = document.createElement("button");
remove.type = "button"; remove.type = "button";
remove.textContent = "×"; remove.textContent = "×";
remove.setAttribute("aria-label", "Remove tag " + tag); remove.setAttribute("aria-label", tr("Remove tag {name}", { name: tag }));
remove.onclick = () => { remove.onclick = () => {
selected = selected.filter((value) => value !== tag); selected = selected.filter((value) => value !== tag);
renderChips(); renderChips();
+49
View File
@@ -0,0 +1,49 @@
// The translation of text that the storage code and the domain code give to the interface: error messages, workspace
// issues, and names. That code stays English (`../storage/message.ts`). It fills the `{name}` placeholders of a catalog
// key with `format()`, so this module finds the key again and translates the text and its values.
import { get } from "svelte/store";
import { locale, translate } from "../../../i18n/index.ts";
import { catalogs, messageRows } from "../../../i18n/messages.ts";
interface Pattern { key: string; names: string[]; regex: RegExp; literal: number }
let patterns: Pattern[] | undefined;
/** The catalog keys with placeholders, as patterns. A key with more fixed text comes first. */
function templatePatterns(): Pattern[] {
patterns ??= messageRows.map(row => row[0]).flatMap(key => {
const literal = key.replace(/\{\w+\}/g, "").length;
// A key that is almost only placeholders matches too much text.
if (literal < 4 || !/\{\w+\}/.test(key) || /\}\{/.test(key)) return [];
const names: string[] = [];
const source = key.split(/(\{\w+\})/).map(part => {
const name = /^\{(\w+)\}$/.exec(part)?.[1];
if (name) { names.push(name); return "([\\s\\S]+?)"; }
return part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}).join("");
return [{ key, names, regex: new RegExp(`^${source}$`), literal }];
}).sort((a, b) => b.literal - a.literal);
return patterns;
}
/**
* The text in the language of the interface. A catalog key translates at once. A text that `format()` made from a key
* translates with its values, and a value that is a catalog text also translates. Other text stays as it is.
*/
export function localize(text: string, depth = 0): string {
const language = get(locale);
if (language === "en") return text;
if (Object.hasOwn(catalogs[language], text)) return catalogs[language][text];
if (depth > 2) return text;
for (const pattern of templatePatterns()) {
const match = pattern.regex.exec(text);
if (!match) continue;
const values = Object.fromEntries(pattern.names.map((name, index) => [name, localize(match[index + 1], depth + 1)]));
return translate(language, pattern.key, values);
}
return text;
}
/** The translated message of an error or another thrown value. */
export function errorText(reason: unknown): string {
return localize(reason instanceof Error ? reason.message : String(reason));
}
File diff suppressed because it is too large Load Diff
+4 -3
View File
@@ -3,6 +3,7 @@
// It reads JSON only. The feature code (`src/lib/features/pm/storage/catalog.ts`) owns the full format and validation. // It reads JSON only. The feature code (`src/lib/features/pm/storage/catalog.ts`) owns the full format and validation.
import { invoke } from "@tauri-apps/api/core"; import { invoke } from "@tauri-apps/api/core";
import { workspaceWrite } from "../workspace/api.ts"; import { workspaceWrite } from "../workspace/api.ts";
import { message } from "../i18n/index.ts";
export const BOARD_CATALOG_PATH = ".runestone/pm/workspace.json"; export const BOARD_CATALOG_PATH = ".runestone/pm/workspace.json";
@@ -37,7 +38,7 @@ function record(value: unknown): Record<string, unknown> | null {
export function parseBoardCatalog(source: string | null): BoardCatalog { export function parseBoardCatalog(source: string | null): BoardCatalog {
if (source === null) return { boards: [], defaultBoardId: null, source }; if (source === null) return { boards: [], defaultBoardId: null, source };
const data = record(JSON.parse(source)); const data = record(JSON.parse(source));
if (!data || data.schema !== 1 || !Array.isArray(data.boards)) throw new Error("The Project Management storage format is unsupported."); if (!data || data.schema !== 1 || !Array.isArray(data.boards)) throw new Error(message("The Project Management storage format is unsupported."));
const boards: BoardSummary[] = []; const boards: BoardSummary[] = [];
for (const row of data.boards) { for (const row of data.boards) {
const board = record(row), value = record(board?.value); const board = record(row), value = record(board?.value);
@@ -62,9 +63,9 @@ export async function writeDefaultBoard(id: string | null, read: ReadOptional =
const catalog = parseBoardCatalog(source); const catalog = parseBoardCatalog(source);
if (source === null) { if (source === null) {
if (id === null) return; if (id === null) return;
throw new Error("This board is unavailable. Refresh Project Management."); throw new Error(message("This board is unavailable. Refresh Project Management."));
} }
if (id !== null && !catalog.boards.some(board => board.id === id)) throw new Error("This board is unavailable. Refresh Project Management."); if (id !== null && !catalog.boards.some(board => board.id === id)) throw new Error(message("This board is unavailable. Refresh Project Management."));
const data = JSON.parse(source) as Record<string, unknown>; const data = JSON.parse(source) as Record<string, unknown>;
data.defaultBoardId = id; data.defaultBoardId = id;
data.defaultBoardPath = id === null ? null : `pm-board:${id}`; data.defaultBoardPath = id === null ? null : `pm-board:${id}`;
+543 -1
View File
@@ -3681,9 +3681,551 @@ export const messageRows: [string, string, string, string][] = [
["Cannot display this PDF. {reason}", "Impossible d’afficher ce PDF. {reason}", "この PDF を表示できません。{reason}", "无法显示此 PDF。{reason}"], ["Cannot display this PDF. {reason}", "Impossible d’afficher ce PDF. {reason}", "この PDF を表示できません。{reason}", "无法显示此 PDF。{reason}"],
// The native features without the desktop host. // The native features without the desktop host.
["This feature needs the desktop app.", "Cette fonctionnalité nécessite l’application de bureau.", "この機能にはデスクトップアプリが必要です。", "此功能需要桌面应用。"], ["This feature needs the desktop app.", "Cette fonctionnalité nécessite l’application de bureau.", "この機能にはデスクトップアプリが必要です。", "此功能需要桌面应用。"],
// Project Management (src/lib/features/catalog.ts, PluginRibbon.svelte, SettingsDialog.svelte). Part B of stage 7-5 translates the board interface. // Project Management (src/lib/features/catalog.ts, PluginRibbon.svelte, SettingsDialog.svelte).
["Project Management", "Project Management", "Project Management", "Project Management"], ["Project Management", "Project Management", "Project Management", "Project Management"],
["Plan work on Kanban boards, in All tasks, and on Gantt and calendar views. The cards stay in the workspace.", "Planifiez le travail sur des tableaux Kanban, dans Toutes les tâches, et dans les vues Gantt et calendrier. Les cartes restent dans l’espace de travail.", "Kanban ボード、すべてのタスク、ガントビューとカレンダービューで作業を計画します。カードはワークスペースに保存されます。", "在看板、所有任务以及甘特图和日历视图中规划工作。卡片保存在工作区中。"], ["Plan work on Kanban boards, in All tasks, and on Gantt and calendar views. The cards stay in the workspace.", "Planifiez le travail sur des tableaux Kanban, dans Toutes les tâches, et dans les vues Gantt et calendrier. Les cartes restent dans l’espace de travail.", "Kanban ボード、すべてのタスク、ガントビューとカレンダービューで作業を計画します。カードはワークスペースに保存されます。", "在看板、所有任务以及甘特图和日历视图中规划工作。卡片保存在工作区中。"],
// Project Management boards (src/lib/features/pm/ui/ui.ts)
["A selected card changed. Refresh and select the cards again.", "Une carte sélectionnée a changé. Actualisez, puis sélectionnez à nouveau les cartes.", "選択したカードが変更されました。更新してから、もう一度カードを選択してください。", "所选卡片已更改。请刷新后重新选择卡片。"],
["Actions for {name}", "Actions pour {name}", "{name} の操作", "{name} 的操作"],
["Active cards in {list}: {count}. The maximum is {maximum}.", "Cartes actives dans {list} : {count}. Le maximum est {maximum}.", "{list} のアクティブなカード: {count}。上限は {maximum} です。", "{list} 中的活动卡片:{count}。上限为 {maximum}。"],
["Active cards in {list}: {count}. The maximum is {maximum}. The list is at the limit.", "Cartes actives dans {list} : {count}. Le maximum est {maximum}. La liste a atteint la limite.", "{list} のアクティブなカード: {count}。上限は {maximum} です。リストは上限に達しています。", "{list} 中的活动卡片:{count}。上限为 {maximum}。列表已达到上限。"],
["Active cards in {list}: {count}. The maximum is {maximum}. The list is over the limit.", "Cartes actives dans {list} : {count}. Le maximum est {maximum}. La liste dépasse la limite.", "{list} のアクティブなカード: {count}。上限は {maximum} です。リストは上限を超えています。", "{list} 中的活动卡片:{count}。上限为 {maximum}。列表已超出上限。"],
["Add a card", "Ajouter une carte", "カードを追加", "添加卡片"],
["Add a list", "Ajouter une liste", "リストを追加", "添加列表"],
["Add an existing note", "Ajouter une note existante", "既存のノートを追加", "添加现有笔记"],
["Add card", "Ajouter la carte", "カードを追加", "添加卡片"],
["Add details", "Ajouter des détails", "詳細を追加", "添加详细信息"],
["Add existing note", "Ajouter une note existante", "既存のノートを追加", "添加现有笔记"],
["Add list", "Ajouter la liste", "リストを追加", "添加列表"],
["Add note", "Ajouter la note", "ノートを追加", "添加笔记"],
["Add or change the assignments.", "Ajouter ou modifier les responsables.", "担当者を追加または変更します。", "添加或更改负责人。"],
["Add or change the color.", "Ajouter ou modifier la couleur.", "色を追加または変更します。", "添加或更改颜色。"],
["Add or change the deadline.", "Ajouter ou modifier l’échéance.", "期限を追加または変更します。", "添加或更改截止日期。"],
["Add or change the planned dates.", "Ajouter ou modifier les dates prévues.", "予定日を追加または変更します。", "添加或更改计划日期。"],
["Add or change the tags.", "Ajouter ou modifier les tags.", "タグを追加または変更します。", "添加或更改标记。"],
["Add or change the work session.", "Ajouter ou modifier la session de travail.", "作業セッションを追加または変更します。", "添加或更改工作时段。"],
["All tasks", "Toutes les tâches", "すべてのタスク", "所有任务"],
["Archive", "Archiver", "アーカイブ", "归档"],
["Archive all cards", "Archiver toutes les cartes", "すべてのカードをアーカイブ", "归档所有卡片"],
["Archive board", "Archiver le tableau", "ボードをアーカイブ", "归档看板"],
["Assigned to {name}", "Attribuée à {name}", "担当者: {name}", "负责人:{name}"],
["Assignments", "Responsables", "担当者", "负责人"],
["Background actions", "Actions de l’arrière-plan", "背景の操作", "背景操作"],
["Background image", "Image d’arrière-plan", "背景画像", "背景图片"],
["Background removed.", "Arrière-plan supprimé.", "背景を削除しました。", "已删除背景。"],
["Background saved.", "Arrière-plan enregistré.", "背景を保存しました。", "已保存背景。"],
["Board", "Tableau", "ボード", "看板"],
["Board archive state saved.", "État d’archivage du tableau enregistré.", "ボードのアーカイブ状態を保存しました。", "已保存看板的归档状态。"],
["Board created.", "Tableau créé.", "ボードを作成しました。", "已创建看板。"],
["Board deleted. Cards stay in All tasks.", "Tableau supprimé. Les cartes restent dans Toutes les tâches.", "ボードを削除しました。カードはすべてのタスクに残ります。", "已删除看板。卡片保留在所有任务中。"],
["Board name", "Nom du tableau", "ボード名", "看板名称"],
["Board renamed.", "Tableau renommé.", "ボードの名前を変更しました。", "已重命名看板。"],
["Board scope", "Portée du tableau", "ボードの範囲", "看板范围"],
["Board scope: {name}", "Portée du tableau : {name}", "ボードの範囲: {name}", "看板范围:{name}"],
["Calendar", "Calendrier", "カレンダー", "日历"],
["Cancel new card", "Annuler la nouvelle carte", "新しいカードをキャンセル", "取消新卡片"],
["Cannot read this image.", "Impossible de lire cette image.", "この画像を読み込めません。", "无法读取此图片。"],
["Card actions", "Actions de la carte", "カードの操作", "卡片操作"],
["Card color", "Couleur de la carte", "カードの色", "卡片颜色"],
["Card cover", "Couverture de la carte", "カードのカバー", "卡片封面"],
["Card deleted.", "Carte supprimée.", "カードを削除しました。", "已删除卡片。"],
["Card details", "Détails de la carte", "カードの詳細", "卡片详细信息"],
["Card moved to the selected board.", "Carte déplacée vers le tableau sélectionné.", "カードを選択したボードに移動しました。", "已将卡片移至所选看板。"],
["Card moved.", "Carte déplacée.", "カードを移動しました。", "已移动卡片。"],
["Card preview", "Aperçu de la carte", "カードのプレビュー", "卡片预览"],
["Card removed from this board. The task note stays.", "Carte retirée de ce tableau. La note de tâche reste.", "カードをこのボードから外しました。タスクノートは残ります。", "已从此看板移除卡片。任务笔记保留。"],
["Card saved.", "Carte enregistrée.", "カードを保存しました。", "已保存卡片。"],
["Card title", "Titre de la carte", "カードのタイトル", "卡片标题"],
["Cards archived.", "Cartes archivées.", "カードをアーカイブしました。", "已归档卡片。"],
["Cards deleted: {count}.", "Cartes supprimées : {count}.", "削除したカード: {count}。", "已删除卡片:{count}。"],
["Cards moved: {count}.", "Cartes déplacées : {count}.", "移動したカード: {count}。", "已移动卡片:{count}。"],
["Cards stay in All tasks. Notes, backups, and memberships on other boards stay unchanged. You cannot undo this action.", "Les cartes restent dans Toutes les tâches. Les notes, les sauvegardes et l’appartenance à d’autres tableaux restent inchangées. Vous ne pouvez pas annuler cette action.", "カードはすべてのタスクに残ります。ノート、バックアップ、他のボードへの所属は変わりません。この操作は元に戻せません。", "卡片保留在所有任务中。笔记、备份以及在其他看板上的成员关系保持不变。此操作无法撤消。"],
["Cards that move to Unlisted: {count}. Their notes and status stay unchanged.", "Cartes déplacées vers Hors liste : {count}. Leurs notes et leur statut restent inchangés.", "リスト外に移動するカード: {count}。ノートとステータスは変わりません。", "将移至未分配列表的卡片:{count}。其笔记和状态保持不变。"],
["Choose", "Choisir", "選択", "选择"],
["Choose a PNG, JPEG, GIF, or WebP image up to 50 MiB.", "Choisissez une image PNG, JPEG, GIF ou WebP de 50 Mio au maximum.", "50 MiB 以下の PNG、JPEG、GIF、または WebP 画像を選択してください。", "请选择不超过 50 MiB 的 PNG、JPEG、GIF 或 WebP 图片。"],
["Choose a board", "Choisir un tableau", "ボードを選択", "选择看板"],
["Choose a board for this card.", "Choisissez un tableau pour cette carte.", "このカードのボードを選択してください。", "请为此卡片选择看板。"],
["Choose a supported image no larger than 50 MiB.", "Choisissez une image prise en charge de 50 Mio au maximum.", "50 MiB 以下の対応している画像を選択してください。", "请选择不超过 50 MiB 的受支持图片。"],
["Choose an image from this card.", "Choisissez une image de cette carte.", "このカードの画像を選択します。", "从此卡片中选择一张图片。"],
["Choose the board for this card.", "Choisissez le tableau de cette carte.", "このカードのボードを選択してください。", "选择此卡片所在的看板。"],
["Clear selection", "Effacer la sélection", "選択を解除", "清除选择"],
["Close card", "Fermer la carte", "カードを閉じる", "关闭卡片"],
["Color", "Couleur", "色", "颜色"],
["Could not list notes. Enter a workspace note path below.", "Impossible de lister les notes. Saisissez ci-dessous le chemin d’une note de l’espace de travail.", "ノートを一覧表示できませんでした。下にワークスペースのノートのパスを入力してください。", "无法列出笔记。请在下方输入工作区笔记路径。"],
["Create a board before you add cards.", "Créez un tableau avant d’ajouter des cartes.", "カードを追加する前にボードを作成してください。", "请先创建看板,再添加卡片。"],
["Create a card due {date}", "Créer une carte avec l’échéance {date}", "期限が {date} のカードを作成", "创建截止日期为 {date} 的卡片"],
["Create a work session on {date} at {time}", "Créer une session de travail le {date} à {time}", "{date} {time} に作業セッションを作成", "在 {date} {time} 创建工作时段"],
["Create another board before you move this card.", "Créez un autre tableau avant de déplacer cette carte.", "このカードを移動する前に、別のボードを作成してください。", "请先创建另一个看板,再移动此卡片。"],
["Create board", "Créer le tableau", "ボードを作成", "创建看板"],
["Create card", "Créer la carte", "カードを作成", "创建卡片"],
["Create your first board", "Créer votre premier tableau", "最初のボードを作成", "创建第一个看板"],
["Created: {date}", "Créée : {date}", "作成日時: {date}", "创建时间:{date}"],
["Creates a private workspace card.", "Crée une carte privée de l’espace de travail.", "ワークスペースの非公開カードを作成します。", "创建一张工作区私有卡片。"],
["Custom field", "Champ personnalisé", "カスタムフィールド", "自定义字段"],
["Customize background", "Personnaliser l’arrière-plan", "背景をカスタマイズ", "自定义背景"],
["Day", "Jour", "日", "日"],
["Deadline", "Échéance", "期限", "截止日期"],
["Delete board", "Supprimer le tableau", "ボードを削除", "删除看板"],
["Delete card", "Supprimer la carte", "カードを削除", "删除卡片"],
["Delete cards", "Supprimer les cartes", "カードを削除", "删除卡片"],
["Delete list", "Supprimer la liste", "リストを削除", "删除列表"],
["Delete selected", "Supprimer la sélection", "選択項目を削除", "删除所选项"],
["Delete selected cards", "Supprimer les cartes sélectionnées", "選択したカードを削除", "删除所选卡片"],
["Delete these cards from all boards. Saved source notes and images stay in the workspace.", "Supprimer ces cartes de tous les tableaux. Les notes sources et les images enregistrées restent dans l’espace de travail.", "これらのカードをすべてのボードから削除します。保存済みの元のノートと画像はワークスペースに残ります。", "从所有看板中删除这些卡片。已保存的源笔记和图片保留在工作区中。"],
["Delete “{name}”?", "Supprimer « {name} » ?", "「{name}」を削除しますか?", "删除“{name}”?"],
["Description draft needs recovery", "Le brouillon de la description doit être récupéré", "説明の下書きの復元が必要です", "描述草稿需要恢复"],
["Destination board", "Tableau de destination", "移動先のボード", "目标看板"],
["Destination list", "Liste de destination", "移動先のリスト", "目标列表"],
["Do not change status", "Ne pas changer le statut", "ステータスを変更しない", "不更改状态"],
["Done", "Terminé", "完了", "完成"],
["Edit", "Modifier", "編集", "编辑"],
["Edit card", "Modifier la carte", "カードを編集", "编辑卡片"],
["Edit list", "Modifier la liste", "リストを編集", "编辑列表"],
["Enter a card title to save this draft.", "Saisissez un titre de carte pour enregistrer ce brouillon.", "この下書きを保存するには、カードのタイトルを入力してください。", "请输入卡片标题以保存此草稿。"],
["Enter a title for this card", "Saisissez un titre pour cette carte", "このカードのタイトルを入力", "输入此卡片的标题"],
["Enter both planned dates, or clear both fields.", "Saisissez les deux dates prévues, ou videz les deux champs.", "予定日を両方入力するか、両方のフィールドを空にしてください。", "请输入两个计划日期,或清空这两个字段。"],
["Enter both session times, or clear both fields.", "Saisissez les deux heures de la session, ou videz les deux champs.", "セッションの時刻を両方入力するか、両方のフィールドを空にしてください。", "请输入两个时段时间,或清空这两个字段。"],
["Field name", "Nom du champ", "フィールド名", "字段名称"],
["Field value", "Valeur du champ", "フィールドの値", "字段值"],
["Find a note or card", "Rechercher une note ou une carte", "ノートまたはカードを検索", "查找笔记或卡片"],
["Finish selection", "Terminer la sélection", "選択を終了", "完成选择"],
["Gantt", "Gantt", "ガント", "甘特图"],
["Hide {name}", "Masquer {name}", "{name} を非表示", "隐藏{name}"],
["Kanban", "Kanban", "カンバン", "看板视图"],
["Labels", "Étiquettes", "ラベル", "标签"],
["Labels saved.", "Étiquettes enregistrées.", "ラベルを保存しました。", "已保存标签。"],
["Leave the field empty for no limit. A warning shows at the maximum. Cards can still enter this list.", "Laissez le champ vide pour aucune limite. Un avertissement s’affiche au maximum. Les cartes peuvent toujours entrer dans cette liste.", "上限を設けない場合はフィールドを空にします。上限に達すると警告が表示されます。カードは引き続きこのリストに追加できます。", "将字段留空表示不限制。达到上限时会显示警告。卡片仍可进入此列表。"],
["Linked note: {path}", "Note liée : {path}", "リンクされたノート: {path}", "链接的笔记:{path}"],
["List", "Liste", "リスト", "列表"],
["List actions", "Actions de la liste", "リストの操作", "列表操作"],
["List actions for {name}", "Actions de la liste {name}", "{name} のリスト操作", "{name} 的列表操作"],
["List added.", "Liste ajoutée.", "リストを追加しました。", "已添加列表。"],
["List deleted. The task notes stay.", "Liste supprimée. Les notes de tâche restent.", "リストを削除しました。タスクノートは残ります。", "已删除列表。任务笔记保留。"],
["List limit saved.", "Limite de la liste enregistrée.", "リストの上限を保存しました。", "已保存列表上限。"],
["List moved.", "Liste déplacée.", "リストを移動しました。", "已移动列表。"],
["List name", "Nom de la liste", "リスト名", "列表名称"],
["List saved.", "Liste enregistrée.", "リストを保存しました。", "已保存列表。"],
["List updated.", "Liste mise à jour.", "リストを更新しました。", "已更新列表。"],
["Loading notes…", "Chargement des notes…", "ノートを読み込み中…", "正在加载笔记…"],
["Manage labels", "Gérer les étiquettes", "ラベルを管理", "管理标签"],
["Matches: {count}. Choose a note, then select Add note.", "Résultats : {count}. Choisissez une note, puis sélectionnez Ajouter la note.", "一致: {count}。ノートを選択してから、[ノートを追加] を選択してください。", "匹配项:{count}。请选择一个笔记,然后选择“添加笔记”。"],
["Matches: {count}. The first 100 show. Make your search more specific.", "Résultats : {count}. Les 100 premiers s’affichent. Précisez votre recherche.", "一致: {count}。最初の 100 件を表示しています。検索条件を絞り込んでください。", "匹配项:{count}。仅显示前 100 项。请缩小搜索范围。"],
["Matching notes and cards", "Notes et cartes correspondantes", "一致するノートとカード", "匹配的笔记和卡片"],
["Maximum cards", "Nombre maximal de cartes", "カードの上限", "卡片上限"],
["Migrate", "Migrer", "移行", "迁移"],
["Migrate Project Management data", "Migrer les données de Project Management", "Project Management のデータを移行", "迁移 Project Management 数据"],
["Migration complete", "Migration terminée", "移行が完了しました", "迁移完成"],
["Migration complete.", "Migration terminée.", "移行が完了しました。", "迁移完成。"],
["Month", "Mois", "月", "月"],
["More actions", "Plus d’actions", "その他の操作", "更多操作"],
["Move card", "Déplacer la carte", "カードを移動", "移动卡片"],
["Move card to board", "Déplacer la carte vers un tableau", "カードをボードに移動", "将卡片移至看板"],
["Move cards", "Déplacer les cartes", "カードを移動", "移动卡片"],
["Move down", "Descendre", "下へ移動", "下移"],
["Move left", "Déplacer à gauche", "左へ移動", "左移"],
["Move left to lighten the image or right to darken it.", "Déplacez vers la gauche pour éclaircir l’image, ou vers la droite pour l’assombrir.", "左に動かすと画像が明るくなり、右に動かすと暗くなります。", "向左移动可使图片变亮,向右移动可使其变暗。"],
["Move list {name}", "Déplacer la liste {name}", "リスト {name} を移動", "移动列表 {name}"],
["Move right", "Déplacer à droite", "右へ移動", "右移"],
["Move selected cards to board", "Déplacer les cartes sélectionnées vers un tableau", "選択したカードをボードに移動", "将所选卡片移至看板"],
["Move selected cards to list", "Déplacer les cartes sélectionnées vers une liste", "選択したカードをリストに移動", "将所选卡片移至列表"],
["Move to board", "Déplacer vers un tableau", "ボードに移動", "移至看板"],
["Move to list", "Déplacer vers une liste", "リストに移動", "移至列表"],
["Move up", "Monter", "上へ移動", "上移"],
["Move {name}", "Déplacer {name}", "{name} を移動", "移动 {name}"],
["Move {name} to list", "Déplacer {name} vers une liste", "{name} をリストに移動", "将 {name} 移至列表"],
["Move “{name}”", "Déplacer « {name} »", "「{name}」を移動", "移动“{name}”"],
["Names (comma separated)", "Noms (séparés par des virgules)", "名前 (カンマ区切り)", "名称(以逗号分隔)"],
["New board", "Nouveau tableau", "新しいボード", "新建看板"],
["New card", "Nouvelle carte", "新しいカード", "新建卡片"],
["New card in {list}", "Nouvelle carte dans {list}", "{list} の新しいカード", "{list} 中的新卡片"],
["Next", "Suivant", "次へ", "下一个"],
["No active board", "Aucun tableau actif", "アクティブなボードがありません", "没有活动看板"],
["No cover", "Aucune couverture", "カバーなし", "无封面"],
["No limit", "Aucune limite", "上限なし", "无上限"],
["No matching notes. Change the search or enter a path below.", "Aucune note correspondante. Modifiez la recherche ou saisissez un chemin ci-dessous.", "一致するノートがありません。検索条件を変更するか、下にパスを入力してください。", "没有匹配的笔记。请更改搜索内容或在下方输入路径。"],
["No notes found. Enter a workspace note path below.", "Aucune note trouvée. Saisissez ci-dessous le chemin d’une note de l’espace de travail.", "ノートが見つかりません。下にワークスペースのノートのパスを入力してください。", "未找到笔记。请在下方输入工作区笔记路径。"],
["No other active boards", "Aucun autre tableau actif", "他にアクティブなボードがありません", "没有其他活动看板"],
["No tasks match this search.", "Aucune tâche ne correspond à cette recherche.", "この検索に一致するタスクはありません。", "没有与此搜索匹配的任务。"],
["Not now", "Pas maintenant", "後で", "以后再说"],
["Note added.", "Note ajoutée.", "ノートを追加しました。", "已添加笔记。"],
["Notes that need attention: {count}", "Notes à vérifier : {count}", "確認が必要なノート: {count}", "需要注意的笔记:{count}"],
["Notes with invalid Project Management properties: {notes}. Repair them before the migration.", "Notes avec des propriétés Project Management non valides : {notes}. Réparez-les avant la migration.", "Project Management のプロパティが無効なノート: {notes}。移行の前に修復してください。", "包含无效 Project Management 属性的笔记:{notes}。请在迁移前修复它们。"],
["Notes/My task.md", "Notes/Ma tâche.md", "Notes/マイタスク.md", "Notes/我的任务.md"],
["Open this card and save or cancel the description changes.", "Ouvrez cette carte, puis enregistrez ou annulez les modifications de la description.", "このカードを開いて、説明の変更を保存またはキャンセルしてください。", "请打开此卡片,然后保存或取消对描述的更改。"],
["Open {name}", "Ouvrir {name}", "{name} を開く", "打开 {name}"],
["Organize cards with saved labels.", "Organisez les cartes avec des étiquettes enregistrées.", "保存済みのラベルでカードを整理します。", "使用已保存的标签整理卡片。"],
["Original board files stay on disk, but Project Management no longer lists this board.", "Les fichiers d’origine du tableau restent sur le disque, mais Project Management n’affiche plus ce tableau.", "元のボードファイルはディスクに残りますが、Project Management にはこのボードが表示されなくなります。", "原始看板文件保留在磁盘上,但 Project Management 不再列出此看板。"],
["People, teams, or customers", "Personnes, équipes ou clients", "人、チーム、または顧客", "人员、团队或客户"],
["Planned dates", "Dates prévues", "予定日", "计划日期"],
["Planned last day", "Dernier jour prévu", "予定の最終日", "计划最后一天"],
["Planned start", "Début prévu", "予定の開始日", "计划开始"],
["Previous", "Précédent", "前へ", "上一个"],
["Priority", "Priorité", "優先度", "优先级"],
["Private card", "Carte privée", "非公開カード", "私有卡片"],
["Private workspace card", "Carte privée de l’espace de travail", "ワークスペースの非公開カード", "工作区私有卡片"],
["Project Management copied the data to hidden storage.", "Project Management a copié les données dans le stockage masqué.", "Project Management はデータを非表示ストレージにコピーしました。", "Project Management 已将数据复制到隐藏存储。"],
["Project Management copied the data to hidden storage. The original files stay unchanged. Examine the boards, then remove these original files:", "Project Management a copié les données dans le stockage masqué. Les fichiers d’origine restent inchangés. Vérifiez les tableaux, puis supprimez ces fichiers d’origine :", "Project Management はデータを非表示ストレージにコピーしました。元のファイルは変更されていません。ボードを確認してから、次の元のファイルを削除してください:", "Project Management 已将数据复制到隐藏存储。原始文件保持不变。请检查看板,然后删除以下原始文件:"],
["Project Management settings", "Paramètres de Project Management", "Project Management の設定", "Project Management 设置"],
["Project Management views", "Vues de Project Management", "Project Management のビュー", "Project Management 视图"],
["Remove background", "Supprimer l’arrière-plan", "背景を削除", "删除背景"],
["Remove custom field", "Supprimer le champ personnalisé", "カスタムフィールドを削除", "删除自定义字段"],
["Remove from board", "Retirer du tableau", "ボードから外す", "从看板中移除"],
["Remove this card from {board} and put it on the selected board. Card details, status, and other board memberships stay unchanged.", "Retirer cette carte de {board} et la placer sur le tableau sélectionné. Les détails de la carte, son statut et son appartenance à d’autres tableaux restent inchangés.", "このカードを {board} から外して、選択したボードに置きます。カードの詳細、ステータス、他のボードへの所属は変わりません。", "将此卡片从 {board} 中移除,并放到所选看板上。卡片详细信息、状态以及在其他看板上的成员关系保持不变。"],
["Remove {name}", "Supprimer {name}", "{name} を削除", "删除{name}"],
["Rename board", "Renommer le tableau", "ボードの名前を変更", "重命名看板"],
["Rename board: {name}", "Renommer le tableau : {name}", "ボードの名前を変更: {name}", "重命名看板:{name}"],
["Restore", "Restaurer", "元に戻す", "还原"],
["Restore board", "Restaurer le tableau", "ボードを元に戻す", "还原看板"],
["Save card", "Enregistrer la carte", "カードを保存", "保存卡片"],
["Save limit", "Enregistrer la limite", "上限を保存", "保存上限"],
["Save list", "Enregistrer la liste", "リストを保存", "保存列表"],
["Search by title or path", "Rechercher par titre ou chemin", "タイトルまたはパスで検索", "按标题或路径搜索"],
["Search tasks", "Rechercher des tâches", "タスクを検索", "搜索任务"],
["Search tasks, labels, and tags", "Rechercher des tâches, des étiquettes et des tags", "タスク、ラベル、タグを検索", "搜索任务、标签和标记"],
["Select all cards", "Sélectionner toutes les cartes", "すべてのカードを選択", "选择所有卡片"],
["Select cards", "Sélectionner des cartes", "カードを選択", "选择卡片"],
["Select {name}", "Sélectionner {name}", "{name} を選択", "选择 {name}"],
["Selected cards", "Cartes sélectionnées", "選択したカード", "所选卡片"],
["Selected cards: {count}", "Cartes sélectionnées : {count}", "選択したカード: {count}", "所选卡片:{count}"],
["Selected: {count}", "Sélection : {count}", "選択: {count}", "已选择:{count}"],
["Session times use {zone}. This editor changes only the first session.", "Les heures des sessions utilisent {zone}. Cet éditeur modifie uniquement la première session.", "セッションの時刻は {zone} を使用します。このエディターは最初のセッションだけを変更します。", "时段时间使用 {zone}。此编辑器仅更改第一个时段。"],
["Set list limit", "Définir la limite de la liste", "リストの上限を設定", "设置列表上限"],
["Set urgency without changing labels.", "Définissez l’urgence sans modifier les étiquettes.", "ラベルを変更せずに緊急度を設定します。", "设置紧急程度,不更改标签。"],
["Show active", "Afficher les actives", "アクティブを表示", "显示活动项"],
["Show archived", "Afficher les archives", "アーカイブを表示", "显示已归档项"],
["Status on move", "Statut au déplacement", "移動時のステータス", "移动时的状态"],
["Status when a card enters this list", "Statut quand une carte entre dans cette liste", "カードがこのリストに入ったときのステータス", "卡片进入此列表时的状态"],
["Store a named value on this card.", "Enregistrez une valeur nommée sur cette carte.", "名前付きの値をこのカードに保存します。", "在此卡片上存储一个命名值。"],
["Stored notes and images stay on disk for recovery. Linked cards and subtasks stay separate cards.", "Les notes et images stockées restent sur le disque pour une récupération. Les cartes liées et les sous-tâches restent des cartes distinctes.", "保存済みのノートと画像は復元用にディスクに残ります。リンクされたカードとサブタスクは別のカードとして残ります。", "已存储的笔记和图片保留在磁盘上以便恢复。链接的卡片和子任务仍是独立的卡片。"],
["Subtasks and linked cards", "Sous-tâches et cartes liées", "サブタスクとリンクされたカード", "子任务和链接的卡片"],
["Tags", "Tags", "タグ", "标记"],
["Task / planned dates", "Tâche / dates prévues", "タスク / 予定日", "任务 / 计划日期"],
["Task archived.", "Tâche archivée.", "タスクをアーカイブしました。", "已归档任务。"],
["Task restored.", "Tâche restaurée.", "タスクを元に戻しました。", "已还原任务。"],
["Task timeline", "Chronologie des tâches", "タスクのタイムライン", "任务时间线"],
["Tasks reloaded.", "Tâches rechargées.", "タスクを再読み込みしました。", "已重新加载任务。"],
["The card goes to the end of the selected list.", "La carte va à la fin de la liste sélectionnée.", "カードは選択したリストの末尾に移動します。", "卡片将移至所选列表的末尾。"],
["The linked card is not available. Refresh the board.", "La carte liée n’est pas disponible. Actualisez le tableau.", "リンクされたカードを使用できません。ボードを更新してください。", "链接的卡片不可用。请刷新看板。"],
["The note picker is closed.", "Le sélecteur de notes est fermé.", "ノートの選択画面は閉じています。", "笔记选择器已关闭。"],
["The saved card is not available. Refresh the board.", "La carte enregistrée n’est pas disponible. Actualisez le tableau.", "保存したカードを使用できません。ボードを更新してください。", "已保存的卡片不可用。请刷新看板。"],
["This card is already on that board. The selected list replaces its current placement.", "Cette carte est déjà sur ce tableau. La liste sélectionnée remplace son emplacement actuel.", "このカードはすでにそのボードにあります。選択したリストが現在の配置に置き換わります。", "此卡片已在该看板上。所选列表将替换其当前位置。"],
["This removes the card from all boards, All tasks, and the archive. You cannot undo this action.", "Cette action retire la carte de tous les tableaux, de Toutes les tâches et des archives. Vous ne pouvez pas annuler cette action.", "カードをすべてのボード、すべてのタスク、アーカイブから削除します。この操作は元に戻せません。", "这会将卡片从所有看板、所有任务和归档中删除。此操作无法撤消。"],
["This removes the empty list.", "Cette action supprime la liste vide.", "空のリストを削除します。", "这会删除空列表。"],
["This workspace has Project Management data in visible files. Project Management now reads only hidden storage in {folder}. The migration copies the data there with exact backups. The original files stay unchanged.", "Cet espace de travail contient des données Project Management dans des fichiers visibles. Project Management lit désormais uniquement le stockage masqué dans {folder}. La migration y copie les données avec des sauvegardes exactes. Les fichiers d’origine restent inchangés.", "このワークスペースには、表示されているファイルに Project Management のデータがあります。Project Management は現在、{folder} の非表示ストレージだけを読み込みます。移行では、正確なバックアップを付けてデータをそこにコピーします。元のファイルは変更されません。", "此工作区的可见文件中有 Project Management 数据。Project Management 现在只读取 {folder} 中的隐藏存储。迁移会将数据复制到该位置并创建精确备份。原始文件保持不变。"],
["This workspace has Project Management data in visible files: {items}. Project Management now reads only hidden storage in {folder}. The migration copies the data there with exact backups. The original files stay unchanged.", "Cet espace de travail contient des données Project Management dans des fichiers visibles : {items}. Project Management lit désormais uniquement le stockage masqué dans {folder}. La migration y copie les données avec des sauvegardes exactes. Les fichiers d’origine restent inchangés.", "このワークスペースには、表示されているファイルに Project Management のデータがあります: {items}。Project Management は現在、{folder} の非表示ストレージだけを読み込みます。移行では、正確なバックアップを付けてデータをそこにコピーします。元のファイルは変更されません。", "此工作区的可见文件中有 Project Management 数据:{items}。Project Management 现在只读取 {folder} 中的隐藏存储。迁移会将数据复制到该位置并创建精确备份。原始文件保持不变。"],
["Title", "Titre", "タイトル", "标题"],
["Today", "Aujourd’hui", "今日", "今天"],
["Track smaller tasks and card dependencies.", "Suivez les petites tâches et les dépendances entre cartes.", "小さなタスクとカードの依存関係を管理します。", "跟踪较小的任务和卡片依赖关系。"],
["Unknown", "Inconnue", "不明", "未知"],
["Unlisted", "Hors liste", "リスト外", "未分配列表"],
["Unsaved description", "Description non enregistrée", "未保存の説明", "未保存的描述"],
["Unscheduled", "Non planifiée", "未予定", "未安排"],
["Use a board to organize cards and move them between lists.", "Utilisez un tableau pour organiser les cartes et les déplacer entre les listes.", "ボードを使ってカードを整理し、リスト間で移動します。", "使用看板整理卡片,并在列表之间移动它们。"],
["View opened.", "Vue ouverte.", "ビューを開きました。", "已打开视图。"],
["Visible date", "Date affichée", "表示する日付", "显示的日期"],
["Wait until the card is saved.", "Attendez l’enregistrement de la carte.", "カードが保存されるまでお待ちください。", "请等待卡片保存完成。"],
["Wait until the images are loaded, then try again.", "Attendez le chargement des images, puis réessayez.", "画像が読み込まれるまで待ってから、もう一度お試しください。", "请等待图片加载完成,然后重试。"],
["Week", "Semaine", "週", "周"],
["Work session", "Session de travail", "作業セッション", "工作时段"],
["Work session end", "Fin de la session de travail", "作業セッションの終了", "工作时段结束"],
["Work session start", "Début de la session de travail", "作業セッションの開始", "工作时段开始"],
["Workspace loaded.", "Espace de travail chargé.", "ワークスペースを読み込みました。", "已加载工作区。"],
["Workspace note path", "Chemin de la note dans l’espace de travail", "ワークスペースのノートのパス", "工作区笔记路径"],
["the label file {path}", "le fichier d’étiquettes {path}", "ラベルファイル {path}", "标签文件 {path}"],
["{count} boards", "{count} tableaux", "{count} 個のボード", "{count} 个看板"],
["{count} task notes", "{count} notes de tâche", "{count} 個のタスクノート", "{count} 个任务笔记"],
["{done} of {total} cards changed. {error}", "{done} cartes sur {total} modifiées. {error}", "{total} 枚中 {done} 枚のカードを変更しました。{error}", "已更改 {done}/{total} 张卡片。{error}"],
["{name} (archived)", "{name} (archivé)", "{name} (アーカイブ済み)", "{name}(已归档)"],
["{name} fields", "Champs : {name}", "{name} のフィールド", "{name}字段"],
["{name} · Archived", "{name} · Archives", "{name} · アーカイブ", "{name} · 已归档"],
["{name}, deadline {date}", "{name}, échéance {date}", "{name}、期限 {date}", "{name},截止日期 {date}"],
["{name}, {color}", "{name}, {color}", "{name}、{color}", "{name},{color}"],
["{name}: {start} to {end}", "{name} : du {start} au {end}", "{name}: {start} ~ {end}", "{name}:{start} 至 {end}"],
["{priority} priority", "Priorité {priority}", "優先度 {priority}", "优先级:{priority}"],
["◆ Due: {name}", "◆ Échéance : {name}", "◆ 期限: {name}", "◆ 截止:{name}"],
// Project Management pickers, editors, and Settings (src/lib/features/pm/ui/, ProjectManagementSettings.svelte, pmBoards.ts)
["2 — High and Low", "2 — Haute et Basse", "2 — 高と低", "2 — 高和低"],
["3 — High, Medium, and Low", "3 — Haute, Moyenne et Basse", "3 — 高、中、低", "3 — 高、中、低"],
["5 — Highest through Lowest", "5 — De Très haute à Très basse", "5 — 最高から最低まで", "5 — 从最高到最低"],
["Highest", "Très haute", "最高", "最高"],
["High", "Haute", "高", "高"],
["Medium", "Moyenne", "中", "中"],
["Low", "Basse", "低", "低"],
["Lowest", "Très basse", "最低", "最低"],
["Add a description.", "Ajoutez une description.", "説明を追加してください。", "请添加描述。"],
["Add a tag", "Ajouter un tag", "タグを追加", "添加标记"],
["Add card details", "Ajouter des détails à la carte", "カードの詳細を追加", "添加卡片详细信息"],
["Add image", "Ajouter une image", "画像を追加", "添加图片"],
["Add label {name}", "Ajouter l’étiquette {name}", "ラベル {name} を追加", "添加标签 {name}"],
["Add labels", "Ajouter des étiquettes", "ラベルを追加", "添加标签"],
["Add linked card", "Ajouter une carte liée", "リンクされたカードを追加", "添加关联卡片"],
["Add subtask", "Ajouter une sous-tâche", "サブタスクを追加", "添加子任务"],
["All boards in this workspace share the labels. A change of name or color applies to each card with the label.", "Tous les tableaux de cet espace de travail partagent les étiquettes. Un changement de nom ou de couleur s’applique à chaque carte qui porte l’étiquette.", "このワークスペースのすべてのボードがラベルを共有します。名前または色の変更は、そのラベルを持つすべてのカードに適用されます。", "此工作区中的所有看板共享这些标签。名称或颜色的更改会应用到带有该标签的每张卡片。"],
["Red", "Rouge", "赤", "红色"],
["Orange", "Orange", "オレンジ", "橙色"],
["Amber", "Ambre", "琥珀", "琥珀色"],
["Yellow", "Jaune", "黄", "黄色"],
["Lime", "Citron vert", "ライム", "青柠色"],
["Green", "Vert", "緑", "绿色"],
["Teal", "Sarcelle", "ティール", "青绿色"],
["Cyan", "Cyan", "シアン", "青色"],
["Blue", "Bleu", "青", "蓝色"],
["Indigo", "Indigo", "藍", "靛蓝色"],
["Purple", "Violet", "紫", "紫色"],
["Magenta", "Magenta", "マゼンタ", "品红色"],
["Pink", "Rose", "ピンク", "粉色"],
["Brown", "Marron", "茶", "棕色"],
["Slate", "Ardoise", "スレート", "石板色"],
["Gray", "Gris", "灰", "灰色"],
["Archived", "Archivée", "アーカイブ済み", "已归档"],
["Attach image", "Joindre une image", "画像を添付", "附加图片"],
["Attach images to card", "Joindre des images à la carte", "カードに画像を添付", "将图片附加到卡片"],
["Attachments", "Pièces jointes", "添付ファイル", "附件"],
["Available labels", "Étiquettes disponibles", "使用できるラベル", "可用标签"],
["Blocked by", "Bloquée par", "ブロック元", "被阻止于"],
["Blocks", "Bloque", "ブロック先", "阻止"],
["Bold text", "Texte en gras", "太字のテキスト", "粗体文本"],
["Cancel linked card", "Annuler la carte liée", "リンクされたカードをキャンセル", "取消关联卡片"],
["Cancel subtask", "Annuler la sous-tâche", "サブタスクをキャンセル", "取消子任务"],
["Cannot display image: {name}", "Impossible d’afficher l’image : {name}", "画像を表示できません: {name}", "无法显示图片:{name}"],
["Cannot display {name}. Restore the image file or remove its reference.", "Impossible d’afficher {name}. Restaurez le fichier image ou supprimez sa référence.", "{name} を表示できません。画像ファイルを復元するか、その参照を削除してください。", "无法显示 {name}。请恢复图片文件,或删除其引用。"],
["Cannot load image: {name}", "Impossible de charger l’image : {name}", "画像を読み込めません: {name}", "无法加载图片:{name}"],
["Card labels", "Étiquettes de la carte", "カードのラベル", "卡片标签"],
["Choose labels", "Choisir des étiquettes", "ラベルを選択", "选择标签"],
["Choose priority", "Choisir la priorité", "優先度を選択", "选择优先级"],
["Choose the board that opens in this workspace. Restored tabs keep their board.", "Choisissez le tableau qui s’ouvre dans cet espace de travail. Les onglets restaurés gardent leur tableau.", "このワークスペースで開くボードを選択します。復元されたタブは元のボードを保持します。", "选择在此工作区中打开的看板。恢复的标签页保留其看板。"],
["Complete {name}", "Terminer {name}", "{name} を完了", "完成 {name}"],
["Create subtask", "Créer la sous-tâche", "サブタスクを作成", "创建子任务"],
["Default board", "Tableau par défaut", "既定のボード", "默认看板"],
["Delete subtask {name}", "Supprimer la sous-tâche {name}", "サブタスク {name} を削除", "删除子任务 {name}"],
["Delete the new label", "Supprimer la nouvelle étiquette", "新しいラベルを削除", "删除新标签"],
["Description", "Description", "説明", "描述"],
["Description preview", "Aperçu de la description", "説明のプレビュー", "描述预览"],
["Details (Markdown)", "Détails (Markdown)", "詳細 (Markdown)", "详细信息 (Markdown)"],
["Edit Markdown", "Modifier le Markdown", "Markdown を編集", "编辑 Markdown"],
["Existing card priorities stay unchanged when you change this setting.", "Les priorités existantes des cartes restent inchangées quand vous modifiez ce réglage.", "この設定を変更しても、既存のカードの優先度は変わりません。", "更改此设置时,现有卡片的优先级保持不变。"],
["Existing tags", "Tags existants", "既存のタグ", "现有标记"],
["Find a card", "Rechercher une carte", "カードを検索", "查找卡片"],
["Find a card to link", "Rechercher une carte à lier", "リンクするカードを検索", "查找要关联的卡片"],
["Find a detail", "Rechercher un détail", "詳細を検索", "查找详细信息"],
["Find a label", "Rechercher une étiquette", "ラベルを検索", "查找标签"],
["Find in description", "Rechercher dans la description", "説明内を検索", "在描述中查找"],
["Heading", "Titre", "見出し", "标题"],
["Image attachments", "Images jointes", "添付画像", "图片附件"],
["Images in card details", "Images des détails de la carte", "カードの詳細の画像", "卡片详细信息中的图片"],
["Insert images in description", "Insérer des images dans la description", "説明に画像を挿入", "在描述中插入图片"],
["Italic text", "Texte en italique", "斜体のテキスト", "斜体文本"],
["Label {name}", "Étiquette {name}", "ラベル {name}", "标签 {name}"],
["Link text", "Texte du lien", "リンクのテキスト", "链接文本"],
["Link {name}", "Lier {name}", "{name} をリンク", "关联 {name}"],
["Linked cards", "Cartes liées", "リンクされたカード", "关联卡片"],
["List item", "Élément de liste", "リスト項目", "列表项"],
["Markdown formatting", "Mise en forme Markdown", "Markdown の書式", "Markdown 格式"],
["Matching cards", "Cartes correspondantes", "一致するカード", "匹配的卡片"],
["Name", "Nom", "名前", "名称"],
["New label", "Nouvelle étiquette", "新しいラベル", "新标签"],
["New subtask", "Nouvelle sous-tâche", "新しいサブタスク", "新子任务"],
["No available cards to link.", "Aucune carte disponible à lier.", "リンクできるカードはありません。", "没有可关联的卡片。"],
["No available labels.", "Aucune étiquette disponible.", "使用できるラベルはありません。", "没有可用标签。"],
["No matches", "Aucun résultat", "一致なし", "无匹配项"],
["No matching cards.", "Aucune carte correspondante.", "一致するカードはありません。", "没有匹配的卡片。"],
["No matching details.", "Aucun détail correspondant.", "一致する詳細はありません。", "没有匹配的详细信息。"],
["No matching labels.", "Aucune étiquette correspondante.", "一致するラベルはありません。", "没有匹配的标签。"],
["No priority", "Aucune priorité", "優先度なし", "无优先级"],
["Open a workspace to choose its default board.", "Ouvrez un espace de travail pour choisir son tableau par défaut.", "既定のボードを選択するには、ワークスペースを開いてください。", "打开工作区以选择其默认看板。"],
["Paste or drop an image into Details, or choose Add image. PNG, JPEG, GIF, or WebP. Up to 50 MiB each.", "Collez ou déposez une image dans Détails, ou choisissez Ajouter une image. PNG, JPEG, GIF ou WebP. Jusqu’à 50 Mio chacune.", "詳細に画像を貼り付けるかドロップするか、「画像を追加」を選択してください。PNG、JPEG、GIF、WebP。各 50 MiB まで。", "将图片粘贴或拖放到详细信息中,或选择“添加图片”。PNG、JPEG、GIF 或 WebP。每张最多 50 MiB。"],
["Pasted image", "Image collée", "貼り付けた画像", "粘贴的图片"],
["Press Enter to add a tag. Use the arrow keys to choose an existing tag.", "Appuyez sur Entrée pour ajouter un tag. Utilisez les flèches pour choisir un tag existant.", "Enter キーでタグを追加します。矢印キーで既存のタグを選択します。", "按 Enter 键添加标记。使用方向键选择现有标记。"],
["Preview", "Aperçu", "プレビュー", "预览"],
["Priority levels", "Niveaux de priorité", "優先度のレベル", "优先级级别"],
["Project Management is off.", "Project Management est désactivé.", "Project Management はオフです。", "Project Management 已关闭。"],
["Relates to", "Liée à", "関連", "相关于"],
["Relationship", "Relation", "関係", "关系"],
["Remove image {name}", "Supprimer l’image {name}", "画像 {name} を削除", "删除图片 {name}"],
["Remove label {name}", "Retirer l’étiquette {name}", "ラベル {name} を外す", "移除标签 {name}"],
["Remove tag {name}", "Retirer le tag {name}", "タグ {name} を外す", "移除标记 {name}"],
["Save labels", "Enregistrer les étiquettes", "ラベルを保存", "保存标签"],
["Selected labels", "Étiquettes sélectionnées", "選択したラベル", "已选标签"],
["Selected tags", "Tags sélectionnés", "選択したタグ", "已选标记"],
["Subtask of", "Sous-tâche de", "親カード", "子任务所属"],
["Subtasks", "Sous-tâches", "サブタスク", "子任务"],
["The Project Management storage format is unsupported.", "Le format de stockage de Project Management n’est pas pris en charge.", "Project Management のストレージ形式はサポートされていません。", "不支持此 Project Management 存储格式。"],
["The boards of each workspace stay in {folder} in the workspace.", "Les tableaux de chaque espace de travail restent dans {folder} de l’espace de travail.", "各ワークスペースのボードは、ワークスペース内の {folder} に保存されます。", "每个工作区的看板保存在该工作区的 {folder} 中。"],
["The image cannot be read. Copy it again or choose another file.", "Impossible de lire l’image. Copiez-la à nouveau ou choisissez un autre fichier.", "画像を読み取れません。もう一度コピーするか、別のファイルを選択してください。", "无法读取图片。请重新复制,或选择其他文件。"],
["This board is unavailable. Refresh Project Management.", "Ce tableau est indisponible. Actualisez Project Management.", "このボードは利用できません。Project Management を更新してください。", "此看板不可用。请刷新 Project Management。"],
["Type a tag and press Enter", "Saisissez un tag et appuyez sur Entrée", "タグを入力して Enter キーを押します", "输入标记并按 Enter 键"],
["Unavailable board", "Tableau indisponible", "利用できないボード", "不可用的看板"],
["Unavailable board (opens All tasks)", "Tableau indisponible (ouvre Toutes les tâches)", "利用できないボード (すべてのタスクを開きます)", "不可用的看板(打开所有任务)"],
["Unavailable card", "Carte indisponible", "利用できないカード", "不可用的卡片"],
["Unavailable label", "Étiquette indisponible", "利用できないラベル", "不可用的标签"],
["Unavailable label: {id}", "Étiquette indisponible : {id}", "利用できないラベル: {id}", "不可用的标签:{id}"],
["Unavailable list", "Liste indisponible", "利用できないリスト", "不可用的列表"],
["Unlink the card", "Délier la carte", "カードのリンクを解除", "取消关联卡片"],
["Unlink {name}", "Délier {name}", "{name} のリンクを解除", "取消关联 {name}"],
["Unsaved changes", "Modifications non enregistrées", "未保存の変更", "未保存的更改"],
["Use a PNG, JPEG, GIF, or WebP image.", "Utilisez une image PNG, JPEG, GIF ou WebP.", "PNG、JPEG、GIF、WebP のいずれかの画像を使用してください。", "请使用 PNG、JPEG、GIF 或 WebP 图片。"],
["Use an image between 1 byte and 50 MiB.", "Utilisez une image entre 1 octet et 50 Mio.", "1 バイトから 50 MiB までの画像を使用してください。", "请使用 1 字节到 50 MiB 之间的图片。"],
["View image {name}", "Afficher l’image {name}", "画像 {name} を表示", "查看图片 {name}"],
["When you save, RuneStone removes each deleted label from all cards.", "Lors de l’enregistrement, RuneStone retire chaque étiquette supprimée de toutes les cartes.", "保存すると、RuneStone は削除したラベルをすべてのカードから外します。", "保存时,RuneStone 会从所有卡片中移除每个已删除的标签。"],
["{board}: {list}", "{board} : {list}", "{board}: {list}", "{board}:{list}"],
["{current} of {total}", "{current} sur {total}", "{current} / {total}", "第 {current} 个,共 {total} 个"],
["{name}, {color}, archived", "{name}, {color}, archivée", "{name}、{color}、アーカイブ済み", "{name},{color},已归档"],
["{relation}: {title}", "{relation} : {title}", "{relation}: {title}", "{relation}:{title}"],
// Project Management storage and domain messages (src/lib/features/pm/storage/, src/lib/features/pm/model/). The interface translates them with localize().
["To do", "À faire", "未着手", "待办"],
["In progress", "En cours", "進行中", "进行中"],
["The board file has an unsupported format. Restore or repair it before editing lists.", "Le fichier du tableau a un format non pris en charge. Restaurez-le ou réparez-le avant de modifier les listes.", "ボードのファイルはサポートされていない形式です。リストを編集する前に、ファイルを復元または修復してください。", "看板文件的格式不受支持。请先恢复或修复该文件,再编辑列表。"],
["The board background image is invalid.", "L’image d’arrière-plan du tableau n’est pas valide.", "ボードの背景画像が無効です。", "看板背景图片无效。"],
["The board contains an invalid list. Repair the board file before editing.", "Le tableau contient une liste non valide. Réparez le fichier du tableau avant de le modifier.", "ボードに無効なリストがあります。編集する前にボードのファイルを修復してください。", "看板包含无效的列表。请先修复看板文件,再进行编辑。"],
["The board has an invalid default list.", "Le tableau a une liste par défaut non valide.", "ボードの既定のリストが無効です。", "看板的默认列表无效。"],
["This board was deleted. Open All tasks to find its cards.", "Ce tableau a été supprimé. Ouvrez Toutes les tâches pour trouver ses cartes.", "このボードは削除されました。カードを見つけるには、すべてのタスクを開いてください。", "此看板已删除。请打开“所有任务”查找其卡片。"],
["The legacy board differs from hidden storage. Preserve both versions.", "L’ancien tableau diffère du stockage masqué. Conservez les deux versions.", "旧形式のボードが非表示ストレージと異なります。両方のバージョンを保持してください。", "旧版看板与隐藏存储不一致。请保留两个版本。"],
["The board changed. Reopen it from navigation.", "Le tableau a changé. Rouvrez-le depuis la navigation.", "ボードが変更されました。ナビゲーションからもう一度開いてください。", "看板已更改。请从导航中重新打开它。"],
["Open an available board to edit its lists.", "Ouvrez un tableau disponible pour modifier ses listes.", "リストを編集するには、使用できるボードを開いてください。", "请打开可用的看板以编辑其列表。"],
["This board moved to hidden storage. Refresh before editing.", "Ce tableau a été déplacé vers le stockage masqué. Actualisez avant de le modifier.", "このボードは非表示ストレージに移動しました。編集する前に更新してください。", "此看板已移至隐藏存储。请先刷新再编辑。"],
["The board changed. Refresh before editing its lists.", "Le tableau a changé. Actualisez avant de modifier ses listes.", "ボードが変更されました。リストを編集する前に更新してください。", "看板已更改。请先刷新再编辑其列表。"],
["The board is unavailable.", "Le tableau n’est pas disponible.", "ボードを使用できません。", "看板不可用。"],
["Open an available board before deleting it.", "Ouvrez un tableau disponible avant de le supprimer.", "削除する前に、使用できるボードを開いてください。", "请先打开可用的看板,再将其删除。"],
["This board was already deleted. Refresh Project Management.", "Ce tableau a déjà été supprimé. Actualisez Project Management.", "このボードは既に削除されています。Project Management を更新してください。", "此看板已被删除。请刷新 Project Management。"],
["The board changed. Cancel, refresh, and review it before deleting.", "Le tableau a changé. Annulez, actualisez et vérifiez-le avant de le supprimer.", "ボードが変更されました。削除する前に、キャンセルして更新し、内容を確認してください。", "看板已更改。删除前请取消、刷新并检查它。"],
["The board is unavailable. Refresh Project Management.", "Le tableau n’est pas disponible. Actualisez Project Management.", "ボードを使用できません。Project Management を更新してください。", "看板不可用。请刷新 Project Management。"],
["This board moved to hidden storage. Refresh before deleting.", "Ce tableau a été déplacé vers le stockage masqué. Actualisez avant de le supprimer.", "このボードは非表示ストレージに移動しました。削除する前に更新してください。", "此看板已移至隐藏存储。请先刷新再删除。"],
["Migrate this board before managing hidden storage.", "Migrez ce tableau avant de gérer le stockage masqué.", "非表示ストレージを管理する前に、このボードを移行してください。", "请先迁移此看板,再管理隐藏存储。"],
["The board changed. Refresh before saving.", "Le tableau a changé. Actualisez avant d’enregistrer.", "ボードが変更されました。保存する前に更新してください。", "看板已更改。请先刷新再保存。"],
["A board with this name already exists.", "Un tableau portant ce nom existe déjà.", "この名前のボードは既に存在します。", "已存在同名看板。"],
["Enter a whole number of at least 1, or leave the maximum blank.", "Saisissez un nombre entier supérieur ou égal à 1, ou laissez le maximum vide.", "1 以上の整数を入力するか、上限を空欄のままにしてください。", "请输入不小于 1 的整数,或将上限留空。"],
["This list no longer exists. Refresh the board.", "Cette liste n’existe plus. Actualisez le tableau.", "このリストはもう存在しません。ボードを更新してください。", "此列表已不存在。请刷新看板。"],
["Enter a list name of 1 to 80 characters.", "Saisissez un nom de liste de 1 à 80 caractères.", "1~80 文字のリスト名を入力してください。", "请输入 1 到 80 个字符的列表名称。"],
["A list with this name already exists.", "Une liste portant ce nom existe déjà.", "この名前のリストは既に存在します。", "已存在同名列表。"],
["In {path}: {problem}", "Dans {path} : {problem}", "{path}: {problem}", "{path}:{problem}"],
["The card migration record is invalid. Keep the original note.", "L’enregistrement de migration de la carte n’est pas valide. Conservez la note d’origine.", "カードの移行記録が無効です。元のノートを保持してください。", "卡片的迁移记录无效。请保留原始笔记。"],
["The hidden card ID does not match its storage path.", "L’ID de la carte masquée ne correspond pas à son chemin de stockage.", "非表示カードの ID が保存先のパスと一致しません。", "隐藏卡片的 ID 与其存储路径不匹配。"],
["The card is unavailable.", "La carte n’est pas disponible.", "カードを使用できません。", "卡片不可用。"],
["The card changed: {path}. Refresh before migration.", "La carte a changé : {path}. Actualisez avant la migration.", "カードが変更されました: {path}。移行の前に更新してください。", "卡片已更改:{path}。请在迁移前刷新。"],
["A different hidden card already uses the ID from {path}.", "Une autre carte masquée utilise déjà l’ID de {path}.", "別の非表示カードが {path} の ID を既に使用しています。", "另一张隐藏卡片已在使用 {path} 的 ID。"],
["The note already contains a migration record: {path}. Review it before migration.", "La note contient déjà un enregistrement de migration : {path}. Vérifiez-la avant la migration.", "ノートには既に移行記録があります: {path}。移行の前に確認してください。", "笔记已包含迁移记录:{path}。请在迁移前检查它。"],
["The card copy differs from {path}. Keep the original.", "La copie de la carte diffère de {path}. Conservez l’original.", "カードのコピーが {path} と異なります。元のファイルを保持してください。", "卡片副本与 {path} 不一致。请保留原始文件。"],
["The card changed: {path}. Retry migration.", "La carte a changé : {path}. Relancez la migration.", "カードが変更されました: {path}。移行をやり直してください。", "卡片已更改:{path}。请重试迁移。"],
["The saved card check failed: {path}. Keep the original.", "La vérification de la carte enregistrée a échoué : {path}. Conservez l’original.", "保存したカードの確認に失敗しました: {path}。元のファイルを保持してください。", "已保存卡片的检查失败:{path}。请保留原始文件。"],
["Enter a board name of 1 to 100 characters.", "Saisissez un nom de tableau de 1 à 100 caractères.", "1~100 文字のボード名を入力してください。", "请输入 1 到 100 个字符的看板名称。"],
["The Project Management storage format is unsupported. Restore a backup or update Project Management.", "Le format de stockage de Project Management n’est pas pris en charge. Restaurez une sauvegarde ou mettez à jour Project Management.", "Project Management の保存形式はサポートされていません。バックアップを復元するか、Project Management を更新してください。", "不支持该 Project Management 存储格式。请恢复备份或更新 Project Management。"],
["The deleted board record is invalid.", "L’enregistrement des tableaux supprimés n’est pas valide.", "削除したボードの記録が無効です。", "已删除看板的记录无效。"],
["A saved board has no name.", "Un tableau enregistré n’a pas de nom.", "保存したボードに名前がありません。", "某个已保存的看板没有名称。"],
["Project Management storage contains duplicate board IDs.", "Le stockage de Project Management contient des ID de tableau en double.", "Project Management のストレージに重複したボード ID があります。", "Project Management 存储包含重复的看板 ID。"],
["A deleted board still has an active storage entry.", "Un tableau supprimé a encore une entrée de stockage active.", "削除したボードに有効なストレージ項目が残っています。", "某个已删除的看板仍有活动的存储条目。"],
["The board archive state is invalid.", "L’état d’archivage du tableau n’est pas valide.", "ボードのアーカイブ状態が無効です。", "看板的归档状态无效。"],
["The board migration record is invalid.", "L’enregistrement de migration du tableau n’est pas valide.", "ボードの移行記録が無効です。", "看板的迁移记录无效。"],
["Update RuneStone to use hidden Project Management storage.", "Mettez à jour RuneStone pour utiliser le stockage masqué de Project Management.", "Project Management の非表示ストレージを使用するには、RuneStone を更新してください。", "请更新 RuneStone 以使用 Project Management 的隐藏存储。"],
["The migration source path is invalid.", "Le chemin source de la migration n’est pas valide.", "移行元のパスが無効です。", "迁移源路径无效。"],
["The backup differs from {path}. Preserve both versions before migration.", "La sauvegarde diffère de {path}. Conservez les deux versions avant la migration.", "バックアップが {path} と異なります。移行の前に両方のバージョンを保持してください。", "备份与 {path} 不一致。请在迁移前保留两个版本。"],
["The backup check failed for {path}.", "La vérification de la sauvegarde a échoué pour {path}.", "{path} のバックアップの確認に失敗しました。", "{path} 的备份检查失败。"],
["The deleted card record is invalid. Restore it before editing cards.", "L’enregistrement des cartes supprimées n’est pas valide. Restaurez-le avant de modifier des cartes.", "削除したカードの記録が無効です。カードを編集する前に記録を復元してください。", "已删除卡片的记录无效。请先恢复该记录,再编辑卡片。"],
["The description draft is invalid. Preserve it before recovery.", "Le brouillon de la description n’est pas valide. Conservez-le avant la récupération.", "説明の下書きが無効です。復旧する前に下書きを保持してください。", "描述草稿无效。请在恢复前保留该草稿。"],
["The image ID is invalid.", "L’ID de l’image n’est pas valide.", "画像の ID が無効です。", "图片 ID 无效。"],
["The saved image exceeds the 50 MiB limit.", "L’image enregistrée dépasse la limite de 50 Mio.", "保存した画像が 50 MiB の上限を超えています。", "已保存的图片超过 50 MiB 的上限。"],
["The saved image is invalid.", "L’image enregistrée n’est pas valide.", "保存した画像が無効です。", "已保存的图片无效。"],
["The saved image is invalid or exceeds 50 MiB.", "L’image enregistrée n’est pas valide ou dépasse 50 Mio.", "保存した画像が無効か、50 MiB を超えています。", "已保存的图片无效或超过 50 MiB。"],
["Saved labels must be a list.", "Les étiquettes enregistrées doivent former une liste.", "保存したラベルはリストである必要があります。", "已保存的标签必须是列表。"],
["Each saved label needs a unique ID.", "Chaque étiquette enregistrée doit avoir un ID unique.", "保存した各ラベルには一意の ID が必要です。", "每个已保存的标签都需要唯一的 ID。"],
["Enter a label name of 1 to 80 characters.", "Saisissez un nom d’étiquette de 1 à 80 caractères.", "1~80 文字のラベル名を入力してください。", "请输入 1 到 80 个字符的标签名称。"],
["Use a different name for each label, including archived labels.", "Utilisez un nom différent pour chaque étiquette, y compris les étiquettes archivées.", "アーカイブしたラベルも含め、ラベルごとに異なる名前を使用してください。", "每个标签(包括已归档的标签)请使用不同的名称。"],
["Choose a supported label color.", "Choisissez une couleur d’étiquette prise en charge.", "サポートされているラベルの色を選択してください。", "请选择受支持的标签颜色。"],
["The label archive state must be true or false.", "L’état d’archivage de l’étiquette doit être true ou false.", "ラベルのアーカイブ状態は true または false である必要があります。", "标签的归档状态必须为 true 或 false。"],
["Fix the saved labels file before editing labels.", "Corrigez le fichier des étiquettes enregistrées avant de modifier les étiquettes.", "ラベルを編集する前に、保存したラベルのファイルを修正してください。", "请先修复已保存的标签文件,再编辑标签。"],
["The saved labels file has an unsupported schema.", "Le fichier des étiquettes enregistrées a un schéma non pris en charge.", "保存したラベルのファイルはサポートされていないスキーマです。", "已保存的标签文件使用了不受支持的架构。"],
["Use the workspace migration tool before editing legacy labels. See the Project Management development guide.", "Utilisez l’outil de migration de l’espace de travail avant de modifier les anciennes étiquettes. Consultez le guide de développement de Project Management.", "旧形式のラベルを編集する前に、ワークスペースの移行ツールを使用してください。Project Management の開発ガイドを参照してください。", "编辑旧版标签前,请使用工作区迁移工具。请参阅 Project Management 开发指南。"],
["Saved labels are unavailable. Refresh before editing labels.", "Les étiquettes enregistrées ne sont pas disponibles. Actualisez avant de modifier les étiquettes.", "保存したラベルを使用できません。ラベルを編集する前に更新してください。", "已保存的标签不可用。请先刷新再编辑标签。"],
["Archive unused labels to preserve existing cards.", "Archivez les étiquettes inutilisées pour préserver les cartes existantes.", "既存のカードを保持するには、使用していないラベルをアーカイブしてください。", "请归档未使用的标签,以保留现有卡片。"],
["Update RuneStone before migrating Project Management storage.", "Mettez à jour RuneStone avant de migrer le stockage de Project Management.", "Project Management のストレージを移行する前に、RuneStone を更新してください。", "请先更新 RuneStone,再迁移 Project Management 存储。"],
["This board was deleted. Refresh Project Management before migration.", "Ce tableau a été supprimé. Actualisez Project Management avant la migration.", "このボードは削除されました。移行の前に Project Management を更新してください。", "此看板已删除。请在迁移前刷新 Project Management。"],
["The board changed: {path}. Refresh before migration.", "Le tableau a changé : {path}. Actualisez avant la migration.", "ボードが変更されました: {path}。移行の前に更新してください。", "看板已更改:{path}。请在迁移前刷新。"],
["A different board already uses the ID from {path}.", "Un autre tableau utilise déjà l’ID de {path}.", "別のボードが {path} の ID を既に使用しています。", "另一个看板已在使用 {path} 的 ID。"],
["Hidden labels and legacy labels both exist. Resolve their differences before migration.", "Des étiquettes masquées et d’anciennes étiquettes existent toutes deux. Résolvez leurs différences avant la migration.", "非表示のラベルと旧形式のラベルの両方があります。移行の前に違いを解消してください。", "隐藏标签和旧版标签同时存在。请在迁移前解决它们之间的差异。"],
["Legacy labels changed. Refresh before migration.", "Les anciennes étiquettes ont changé. Actualisez avant la migration.", "旧形式のラベルが変更されました。移行の前に更新してください。", "旧版标签已更改。请在迁移前刷新。"],
["The saved label check failed. Retry migration.", "La vérification des étiquettes enregistrées a échoué. Relancez la migration.", "保存したラベルの確認に失敗しました。移行をやり直してください。", "已保存标签的检查失败。请重试迁移。"],
["The saved board check failed. Retry migration.", "La vérification du tableau enregistré a échoué. Relancez la migration.", "保存したボードの確認に失敗しました。移行をやり直してください。", "已保存看板的检查失败。请重试迁移。"],
["The backup check failed for {path}. Keep the original.", "La vérification de la sauvegarde a échoué pour {path}. Conservez l’original.", "{path} のバックアップの確認に失敗しました。元のファイルを保持してください。", "{path} 的备份检查失败。请保留原始文件。"],
["The original changed: {path}. Keep both versions.", "L’original a changé : {path}. Conservez les deux versions.", "元のファイルが変更されました: {path}。両方のバージョンを保持してください。", "原始文件已更改:{path}。请保留两个版本。"],
["Close the YAML properties block before editing this note.", "Fermez le bloc des propriétés YAML avant de modifier cette note.", "このノートを編集する前に、YAML プロパティのブロックを閉じてください。", "编辑此笔记前,请先闭合 YAML 属性块。"],
["Fix invalid or unsupported YAML properties before editing this note.", "Corrigez les propriétés YAML non valides ou non prises en charge avant de modifier cette note.", "このノートを編集する前に、無効またはサポートされていない YAML プロパティを修正してください。", "编辑此笔记前,请修复无效或不受支持的 YAML 属性。"],
["Note properties must be a YAML mapping.", "Les propriétés de la note doivent former un mappage YAML.", "ノートのプロパティは YAML のマッピングである必要があります。", "笔记属性必须是 YAML 映射。"],
["This note has an unsupported Project Management schema, kind, or ID.", "Cette note a un schéma, un type ou un ID Project Management non pris en charge.", "このノートの Project Management のスキーマ、種類、または ID はサポートされていません。", "此笔记的 Project Management 架构、类型或 ID 不受支持。"],
["The archive state must be true or false.", "L’état d’archivage doit être true ou false.", "アーカイブ状態は true または false である必要があります。", "归档状态必须为 true 或 false。"],
["This preview supports date-only deadlines.", "Cette préversion prend en charge uniquement les échéances sans heure.", "このプレビューでは、日付のみの期限をサポートしています。", "此预览版仅支持只含日期的截止日期。"],
["The plan needs a start and an exclusive end date.", "Le plan doit avoir une date de début et une date de fin exclusive.", "計画には開始日と終了日 (終了日を含まない) が必要です。", "计划需要开始日期和结束日期(不含结束日期当天)。"],
["Sessions need an ID, start, end, and time zone.", "Les sessions doivent avoir un ID, un début, une fin et un fuseau horaire.", "セッションには ID、開始、終了、タイム ゾーンが必要です。", "会话需要 ID、开始时间、结束时间和时区。"],
["The card creation timestamp cannot change.", "L’horodatage de création de la carte ne peut pas changer.", "カードの作成日時は変更できません。", "卡片的创建时间戳不能更改。"],
["Use a valid note name of 1 to 100 characters.", "Utilisez un nom de note valide de 1 à 100 caractères.", "1~100 文字の有効なノート名を使用してください。", "请使用 1 到 100 个字符的有效笔记名称。"],
["This document already contains Project Management data and cannot become a task.", "Ce document contient déjà des données Project Management et ne peut pas devenir une tâche.", "このドキュメントには既に Project Management のデータがあるため、タスクにできません。", "此文档已包含 Project Management 数据,无法成为任务。"],
["The card order changed. Refresh the board.", "L’ordre des cartes a changé. Actualisez le tableau.", "カードの順序が変更されました。ボードを更新してください。", "卡片顺序已更改。请刷新看板。"],
["The Project Management Git exclusion changed. Retry before saving private data.", "L’exclusion Git de Project Management a changé. Réessayez avant d’enregistrer des données privées.", "Project Management の Git の除外設定が変更されました。非公開データを保存する前にもう一度試してください。", "Project Management 的 Git 排除规则已更改。请在保存私有数据前重试。"],
["Update RuneStone to create Project Management storage.", "Mettez à jour RuneStone pour créer le stockage de Project Management.", "Project Management のストレージを作成するには、RuneStone を更新してください。", "请更新 RuneStone 以创建 Project Management 存储。"],
["The batch did not return this file.", "Le lot n’a pas renvoyé ce fichier.", "バッチはこのファイルを返しませんでした。", "批量读取未返回此文件。"],
["Enter a valid calendar date.", "Saisissez une date de calendrier valide.", "有効な日付を入力してください。", "请输入有效的日历日期。"],
["Enter an existing local date and time.", "Saisissez une date et une heure locales existantes.", "存在するローカルの日付と時刻を入力してください。", "请输入存在的本地日期和时间。"],
["The card creation timestamp is invalid.", "L’horodatage de création de la carte n’est pas valide.", "カードの作成日時が無効です。", "卡片的创建时间戳无效。"],
["Each image attachment needs a unique image ID and a name of 1 to 255 characters.", "Chaque image jointe doit avoir un ID d’image unique et un nom de 1 à 255 caractères.", "各添付画像には、一意の画像 ID と 1~255 文字の名前が必要です。", "每个图片附件都需要唯一的图片 ID 和 1 到 255 个字符的名称。"],
["Choose a supported priority or No priority.", "Choisissez une priorité prise en charge ou Aucune priorité.", "サポートされている優先度か、優先度なしを選択してください。", "请选择受支持的优先级或“无优先级”。"],
["Each subtask needs a unique ID, a title, and a completion state.", "Chaque sous-tâche doit avoir un ID unique, un titre et un état d’achèvement.", "各サブタスクには、一意の ID、タイトル、完了状態が必要です。", "每个子任务都需要唯一的 ID、标题和完成状态。"],
["Choose each linked card once and select its relationship.", "Choisissez chaque carte liée une seule fois et sélectionnez sa relation.", "リンクする各カードを 1 回だけ選択し、関係を選択してください。", "每张链接的卡片只能选择一次,并请选择其关系。"],
["Enter a card title of 1 to 100 characters.", "Saisissez un titre de carte de 1 à 100 caractères.", "1~100 文字のカードのタイトルを入力してください。", "请输入 1 到 100 个字符的卡片标题。"],
["The card order is invalid. Refresh the board.", "L’ordre de la carte n’est pas valide. Actualisez le tableau.", "カードの順序が無効です。ボードを更新してください。", "卡片顺序无效。请刷新看板。"],
["Board placements must be a mapping.", "Les placements sur les tableaux doivent former un mappage.", "ボードの配置はマッピングである必要があります。", "看板位置必须是映射。"],
["Each board placement needs a board ID and a valid list ID.", "Chaque placement sur un tableau doit avoir un ID de tableau et un ID de liste valide.", "各ボードの配置には、ボード ID と有効なリスト ID が必要です。", "每个看板位置都需要看板 ID 和有效的列表 ID。"],
["Choose a supported card color.", "Choisissez une couleur de carte prise en charge.", "サポートされているカードの色を選択してください。", "请选择受支持的卡片颜色。"],
["Assignments must contain names.", "Les attributions doivent contenir des noms.", "割り当てには名前が必要です。", "分配必须包含名称。"],
["Each custom field needs a name and a text value.", "Chaque champ personnalisé doit avoir un nom et une valeur texte.", "各カスタム フィールドには、名前とテキストの値が必要です。", "每个自定义字段都需要名称和文本值。"],
["Use a different name for each custom field.", "Utilisez un nom différent pour chaque champ personnalisé.", "カスタム フィールドごとに異なる名前を使用してください。", "每个自定义字段请使用不同的名称。"],
["The task has an invalid list ID.", "La tâche a un ID de liste non valide.", "タスクのリスト ID が無効です。", "任务的列表 ID 无效。"],
["Choose a supported task status.", "Choisissez un statut de tâche pris en charge.", "サポートされているタスクの状態を選択してください。", "请选择受支持的任务状态。"],
["Tags must be text.", "Les balises doivent être du texte.", "タグはテキストである必要があります。", "标记必须是文本。"],
["Labels must contain unique saved label IDs.", "Les étiquettes doivent contenir des ID d’étiquettes enregistrées uniques.", "ラベルには、保存したラベルの一意の ID が必要です。", "标签必须包含唯一的已保存标签 ID。"],
["Enter a valid deadline date.", "Saisissez une date d’échéance valide.", "有効な期限の日付を入力してください。", "请输入有效的截止日期。"],
["The planned end must follow the start.", "La fin prévue doit suivre le début.", "予定の終了は開始より後である必要があります。", "计划结束时间必须晚于开始时间。"],
["Each session needs a unique ID and a valid time range.", "Chaque session doit avoir un ID unique et une plage horaire valide.", "各セッションには、一意の ID と有効な時間範囲が必要です。", "每个会话都需要唯一的 ID 和有效的时间范围。"],
["Duplicate task ID {id}: resolve the copied notes before editing them.", "ID de tâche en double {id} : résolvez les notes copiées avant de les modifier.", "重複したタスク ID {id}: 編集する前に、コピーしたノートを解決してください。", "重复的任务 ID {id}:请先处理复制的笔记,再进行编辑。"],
["The Project Management view is closed. Reopen it before saving.", "La vue Project Management est fermée. Rouvrez-la avant d’enregistrer.", "Project Management のビューは閉じています。保存する前にもう一度開いてください。", "Project Management 视图已关闭。请重新打开后再保存。"],
["Hidden cards: {error}", "Cartes masquées : {error}", "非表示のカード: {error}", "隐藏卡片:{error}"],
["Hidden Project Management storage: {error}", "Stockage masqué de Project Management : {error}", "Project Management の非表示ストレージ: {error}", "Project Management 隐藏存储:{error}"],
["Saved labels: {error}", "Étiquettes enregistrées : {error}", "保存したラベル: {error}", "已保存的标签:{error}"],
["Deleted cards: {error}", "Cartes supprimées : {error}", "削除したカード: {error}", "已删除的卡片:{error}"],
["This board is missing, invalid, or duplicated. Task notes remain available in All tasks.", "Ce tableau est manquant, non valide ou en double. Les notes de tâches restent disponibles dans Toutes les tâches.", "このボードは見つからないか、無効か、重複しています。タスクのノートは、すべてのタスクで引き続き使用できます。", "此看板缺失、无效或重复。任务笔记仍可在“所有任务”中使用。"],
["The file is unavailable.", "Le fichier n’est pas disponible.", "ファイルを使用できません。", "文件不可用。"],
["The original card differs from hidden storage: {path}. Preserve both versions.", "La carte d’origine diffère du stockage masqué : {path}. Conservez les deux versions.", "元のカードが非表示ストレージと異なります: {path}。両方のバージョンを保持してください。", "原始卡片与隐藏存储不一致:{path}。请保留两个版本。"],
["The legacy board differs from hidden storage: {path}. Preserve both versions before cleanup.", "L’ancien tableau diffère du stockage masqué : {path}. Conservez les deux versions avant le nettoyage.", "旧形式のボードが非表示ストレージと異なります: {path}。クリーンアップの前に両方のバージョンを保持してください。", "旧版看板与隐藏存储不一致:{path}。请在清理前保留两个版本。"],
["Duplicate board ID {id}: resolve the copied boards before editing them.", "ID de tableau en double {id} : résolvez les tableaux copiés avant de les modifier.", "重複したボード ID {id}: 編集する前に、コピーしたボードを解決してください。", "重复的看板 ID {id}:请先处理复制的看板,再进行编辑。"],
["The card changed or is unavailable. Refresh before deleting it.", "La carte a changé ou n’est pas disponible. Actualisez avant de la supprimer.", "カードが変更されたか、使用できません。削除する前に更新してください。", "卡片已更改或不可用。请先刷新再删除。"],
["A linked card changed. Refresh before removing its link.", "Une carte liée a changé. Actualisez avant de supprimer son lien.", "リンクされたカードが変更されました。リンクを削除する前に更新してください。", "某张链接的卡片已更改。请先刷新再删除其链接。"],
["The task changed or has a duplicate ID. Cancel, refresh, and review the note before saving.", "La tâche a changé ou a un ID en double. Annulez, actualisez et vérifiez la note avant d’enregistrer.", "タスクが変更されたか、ID が重複しています。保存する前に、キャンセルして更新し、ノートを確認してください。", "任务已更改或 ID 重复。保存前请取消、刷新并检查笔记。"],
["Restore this board before moving cards.", "Restaurez ce tableau avant de déplacer des cartes.", "カードを移動する前に、このボードを復元してください。", "请先恢复此看板,再移动卡片。"],
["The board is unavailable. Reopen it before saving.", "Le tableau n’est pas disponible. Rouvrez-le avant d’enregistrer.", "ボードを使用できません。保存する前にもう一度開いてください。", "看板不可用。请重新打开后再保存。"],
["The list is unavailable. Refresh the board.", "La liste n’est pas disponible. Actualisez le tableau.", "リストを使用できません。ボードを更新してください。", "列表不可用。请刷新看板。"],
["Resolve workspace issues before archiving cards: {issues}", "Résolvez les problèmes de l’espace de travail avant d’archiver des cartes : {issues}", "カードをアーカイブする前に、ワークスペースの問題を解決してください: {issues}", "归档卡片前,请解决工作区问题:{issues}"],
["The target card moved. Refresh the board.", "La carte cible a été déplacée. Actualisez le tableau.", "対象のカードが移動しました。ボードを更新してください。", "目标卡片已移动。请刷新看板。"],
["Use a relative Markdown path inside this workspace.", "Utilisez un chemin Markdown relatif dans cet espace de travail.", "このワークスペース内の相対 Markdown パスを使用してください。", "请使用此工作区内的相对 Markdown 路径。"],
["The linked card is unavailable. Refresh the board.", "La carte liée n’est pas disponible. Actualisez le tableau.", "リンクされたカードを使用できません。ボードを更新してください。", "链接的卡片不可用。请刷新看板。"],
["This RuneStone version cannot create plugin notes. Add an existing note or install the host bridge.", "Cette version de RuneStone ne peut pas créer de notes de plug-in. Ajoutez une note existante ou installez le pont de l’hôte.", "このバージョンの RuneStone はプラグインのノートを作成できません。既存のノートを追加するか、ホスト ブリッジをインストールしてください。", "此版本的 RuneStone 无法创建插件笔记。请添加现有笔记或安装主机桥接。"],
["Choose an available, active board for this card.", "Choisissez un tableau disponible et actif pour cette carte.", "このカードには、使用できるアクティブなボードを選択してください。", "请为此卡片选择可用的活动看板。"],
["Restore this board before adding cards.", "Restaurez ce tableau avant d’ajouter des cartes.", "カードを追加する前に、このボードを復元してください。", "请先恢复此看板,再添加卡片。"],
["The subtask is unavailable. Refresh the board.", "La sous-tâche n’est pas disponible. Actualisez le tableau.", "サブタスクを使用できません。ボードを更新してください。", "子任务不可用。请刷新看板。"],
["The subtask card is unavailable. Refresh the board.", "La carte de la sous-tâche n’est pas disponible. Actualisez le tableau.", "サブタスクのカードを使用できません。ボードを更新してください。", "子任务卡片不可用。请刷新看板。"],
["Open a board before removing a card.", "Ouvrez un tableau avant de retirer une carte.", "カードを削除する前に、ボードを開いてください。", "请先打开看板,再移除卡片。"],
["The destination board or list is unavailable. Refresh the board.", "Le tableau ou la liste de destination n’est pas disponible. Actualisez le tableau.", "移動先のボードまたはリストを使用できません。ボードを更新してください。", "目标看板或列表不可用。请刷新看板。"],
["Open an available, active board before moving a card.", "Ouvrez un tableau disponible et actif avant de déplacer une carte.", "カードを移動する前に、使用できるアクティブなボードを開いてください。", "请先打开可用的活动看板,再移动卡片。"],
["The card changed. Cancel, refresh, and review it before moving.", "La carte a changé. Annulez, actualisez et vérifiez-la avant de la déplacer.", "カードが変更されました。移動する前に、キャンセルして更新し、内容を確認してください。", "卡片已更改。移动前请取消、刷新并检查它。"],
["This card no longer belongs to the source board.", "Cette carte n’appartient plus au tableau source.", "このカードは移動元のボードにもう属していません。", "此卡片已不属于源看板。"],
["Choose a different destination board.", "Choisissez un autre tableau de destination.", "別の移動先ボードを選択してください。", "请选择其他目标看板。"],
["The destination board is unavailable or archived. Choose another board.", "Le tableau de destination n’est pas disponible ou est archivé. Choisissez un autre tableau.", "移動先のボードは使用できないか、アーカイブされています。別のボードを選択してください。", "目标看板不可用或已归档。请选择其他看板。"],
["The destination list no longer exists. Choose another list.", "La liste de destination n’existe plus. Choisissez une autre liste.", "移動先のリストはもう存在しません。別のリストを選択してください。", "目标列表已不存在。请选择其他列表。"],
["Saved labels changed. Refresh before deleting labels.", "Les étiquettes enregistrées ont changé. Actualisez avant de supprimer des étiquettes.", "保存したラベルが変更されました。ラベルを削除する前に更新してください。", "已保存的标签已更改。请先刷新再删除标签。"],
["Resolve workspace issues before deleting labels: {issues}", "Résolvez les problèmes de l’espace de travail avant de supprimer des étiquettes : {issues}", "ラベルを削除する前に、ワークスペースの問題を解決してください: {issues}", "删除标签前,请解决工作区问题:{issues}"],
["Resolve the workspace issues before migration: {issues}", "Résolvez les problèmes de l’espace de travail avant la migration : {issues}", "移行の前に、ワークスペースの問題を解決してください: {issues}", "迁移前,请解决工作区问题:{issues}"],
["A selected card is unavailable. Refresh before migration.", "Une carte sélectionnée n’est pas disponible. Actualisez avant la migration.", "選択したカードを使用できません。移行の前に更新してください。", "某张所选卡片不可用。请在迁移前刷新。"],
["Open an available board before renaming it.", "Ouvrez un tableau disponible avant de le renommer.", "名前を変更する前に、使用できるボードを開いてください。", "请先打开可用的看板,再重命名。"],
["Migrate this board before renaming it.", "Migrez ce tableau avant de le renommer.", "名前を変更する前に、このボードを移行してください。", "请先迁移此看板,再重命名。"],
["Choose a Markdown note from this workspace.", "Choisissez une note Markdown de cet espace de travail.", "このワークスペースの Markdown ノートを選択してください。", "请从此工作区选择 Markdown 笔记。"],
["The board is unavailable. Reopen it before adding a note.", "Le tableau n’est pas disponible. Rouvrez-le avant d’ajouter une note.", "ボードを使用できません。ノートを追加する前にもう一度開いてください。", "看板不可用。请重新打开后再添加笔记。"],
["Resolve this task's duplicate ID before adding it.", "Résolvez l’ID en double de cette tâche avant de l’ajouter.", "追加する前に、このタスクの重複した ID を解決してください。", "添加前,请先解决此任务的重复 ID。"],
]; ];
export const catalogs: Record<Exclude<Locale, 'en'>, Record<string, string>> = { export const catalogs: Record<Exclude<Locale, 'en'>, Record<string, string>> = {
fr: Object.fromEntries(messageRows.map(row => [row[0], row[1]])), fr: Object.fromEntries(messageRows.map(row => [row[0], row[1]])),
+4 -1
View File
@@ -375,7 +375,10 @@ export async function runPluginCommand(owner: string, id: string) {
try { await sessions.get(owner)?.session.run(id); } catch (error) { report(owner, error); throw error; } try { await sessions.get(owner)?.session.run(id); } catch (error) { report(owner, error); throw error; }
} }
export function openPluginView(owner: string, id: string) { export function openPluginView(owner: string, id: string) {
void sessions.get(owner)?.session.launch(id).catch(error => report(owner, error)); const launch = () => sessions.get(owner)?.session.launch(id);
if (sessions.has(owner)) { void launch()?.catch(error => report(owner, error)); return; }
// At window start, the ribbon shows a native feature before its session exists. Wait for the feature switches.
void whenStarted.then(() => queue).then(launch).catch(error => report(owner, error));
} }
export async function mountPluginView(owner: string, id: string, element: HTMLElement, document?: PluginDocumentContext, surface: "settings" | "view" = "view"): Promise<Dispose> { export async function mountPluginView(owner: string, id: string, element: HTMLElement, document?: PluginDocumentContext, surface: "settings" | "view" = "view"): Promise<Dispose> {
const session = sessions.get(owner)?.session; const session = sessions.get(owner)?.session;
+142
View File
@@ -0,0 +1,142 @@
// Shared setup of the Project Management smoke tests (tests/smoke/features/pm*.smoke.mjs): a workspace with two boards
// and five cards in hidden storage, a mock that keeps the workspace files through a page reload, and small helpers.
import { mockTauri, smokeUrl } from "./index.mjs";
export const roadmap = "6f4c2a3e-6a0b-4d57-9a3e-1c2b3d4e5f60";
export const bugs = "0c18bcdc-f41e-4a31-87f4-87c369f398c1";
export const catalogPath = ".runestone/pm/workspace.json";
export const deletedPath = ".runestone/pm/deleted-cards.json";
const hex = id => Buffer.from(id).toString("hex");
export const cardPath = id => `.runestone/pm/cards/${hex(id)}.md`;
export const draftPath = id => `.runestone/pm/drafts/${hex(id)}.json`;
/** The local date `offset` days from today, as YYYY-MM-DD. */
export function localDay(offset = 0) {
const date = new Date();
date.setDate(date.getDate() + offset);
return [date.getFullYear(), date.getMonth() + 1, date.getDate()].map(part => String(part).padStart(2, "0")).join("-");
}
/** A board with the three default lists and one review list. `review` gives the ID, the name, and the limit of that list. */
export function board(id, review = { id: "review", name: "Review" }) {
return {
schema: 1, kind: "board", id,
lists: [
{ id: "todo", name: "To do", status: "todo", collapsed: false },
{ id: "doing", name: "In progress", status: "doing", collapsed: false },
{ id: "done", name: "Done", status: "done", collapsed: false },
{ collapsed: false, status: null, ...review },
],
defaults: { todo: "todo", doing: "doing", done: "done" },
};
}
/** A card file. `placements` maps a board ID to a list ID. `extra` adds lines to the front matter. */
export function card(id, title, { placements = {}, status = "todo", order = id.slice(-1), extra = [] } = {}) {
const lines = ["---", "runestone_pm:", " schema: 1", ` id: ${id}`, " kind: task", ` title: ${title}`,
' createdAt: "2026-10-01T08:30:00.000Z"', ` order: "${order}"`, ` status: ${status}`, " tags: []", " sessions: []", " archived: false", ...extra];
if (Object.keys(placements).length) {
lines.push(" placements:");
for (const [boardId, listId] of Object.entries(placements)) lines.push(` ${boardId}:`, ` listId: ${listId}`, ` order: "${order}"`);
}
return [cardPath(id), [...lines, "---", `Body of ${title}.`, ""].join("\n")];
}
/**
* The workspace files. Roadmap: Card A and Card B in To do, Shared card in To do, and a limit of 2 on Review.
* Bugs: Card C in its "review" list, Shared card in To do. Loose card has no board. Card B has planned dates and a deadline.
*/
export function pmFiles({ boards = true, defaultBoardId } = {}) {
const catalog = { schema: 1, boards: [
{ name: "Roadmap", value: board(roadmap, { id: "review", name: "Review", maxCards: 2 }) },
{ name: "Bugs", value: board(bugs, { id: "qa", name: "review" }) },
], ...(defaultBoardId ? { defaultBoardId, defaultBoardPath: `pm-board:${defaultBoardId}` } : {}) };
return Object.fromEntries([
["note.md", "# Note\n"],
[".runestone/pm/.gitignore", "# RuneStone Project Management local data\n*\n"],
[".runestone/pm/cards/.gitignore", "*\n"],
...boards ? [[catalogPath, JSON.stringify(catalog, null, 2) + "\n"]] : [],
card("card-a", "Card A", { placements: { [roadmap]: "todo" }, order: "a" }),
card("card-b", "Card B", { placements: { [roadmap]: "todo" }, order: "b", extra: [
" due:", ` date: "${localDay(2)}"`, " plan:", ` start: "${localDay(0)}"`, ` end: "${localDay(4)}"`] }),
card("card-c", "Card C", { placements: { [bugs]: "qa" }, order: "c" }),
card("card-d", "Shared card", { placements: { [roadmap]: "todo", [bugs]: "todo" }, order: "d" }),
card("card-e", "Loose card", { order: "e" }),
]);
}
// This function runs in the page. Keep it self-contained. The files stay in localStorage, so a reload keeps them.
function pmCommands(test) {
const KEY = "runestone.smoke.pm-files";
let saved = null;
try { saved = JSON.parse(localStorage.getItem(KEY)); } catch { saved = null; }
const workspace = test.workspace({ root: "C:\\pm-smoke", files: new Map(saved ?? Object.entries(test.state.files)) });
test.files = workspace.files;
const keep = () => localStorage.setItem(KEY, JSON.stringify([...workspace.files]));
const kept = handler => args => { const result = handler(args); keep(); return result; };
return {
...workspace,
workspace_read: args => {
if (!workspace.files.has(args.rel) && args.missingOk) return null;
return workspace.workspace_read(args);
},
workspace_write: kept(workspace.workspace_write),
workspace_delete: kept(workspace.workspace_delete),
workspace_create: kept(({ rel, kind, contents }) => {
if (workspace.files.has(rel)) throw new Error("Destination exists");
if (kind === "file") workspace.files.set(rel, contents ?? "");
else workspace.folders.add(rel);
return null;
}),
plugins_snapshot: () => ({ root: "C:/plugins", plugins: [] }),
spelling_menu_install: () => null,
"plugin:window|is_maximized": () => false,
};
}
/** Mock the host with the files of `pmFiles()`, load the app, and wait for the file tree. */
export async function loadWorkspace(page, files = pmFiles()) {
await mockTauri(page, { state: { files }, commands: pmCommands });
await page.goto(smokeUrl);
await page.locator('[data-tree-rel="note.md"]').waitFor();
}
/** The Project Management ribbon button. */
export const ribbon = page => page.locator(".plugin-ribbon").getByRole("button", { name: "Project Management", exact: true });
/** The visible Project Management view. */
export const pane = page => page.locator(".plugin-editor-pane:visible .rs-pm");
/** A Kanban column by its accessible name. */
export const column = (page, name) => pane(page).locator(`section.pm-column[aria-label="${name}"]`);
/** Open All tasks with the ribbon button, then open a board through the board scope menu when `name` is given. */
export async function openBoard(page, name) {
if (!await pane(page).count()) {
await ribbon(page).click();
await pane(page).locator(".pm-board").waitFor();
}
if (!name) return;
await pane(page).locator(".pm-scope").click();
await page.getByRole("menuitemradio", { name, exact: true }).click();
await page.getByRole("tab", { name, exact: true }).waitFor();
await pane(page).locator(".pm-scope-label", { hasText: new RegExp(`^${name}$`) }).waitFor();
await pane(page).locator(".pm-column").first().waitFor();
}
/** Use the dark or the light mode of the default theme. */
export async function setTheme(page, mode) {
await page.evaluate(async value => {
const { saveAppearance } = await import("/src/lib/theme/appearance.ts");
saveAppearance({ theme: "default", mode: value });
}, mode);
await page.waitForFunction(value => document.documentElement.dataset.theme === value, mode);
}
/** The text of a workspace file, or undefined. */
export const fileText = (page, path) => page.evaluate(rel => window.__TEST__.files.get(rel), path);
/** Wait until a workspace file matches `pattern`. */
export const waitForFile = (page, path, pattern) =>
page.waitForFunction(([rel, source, flags]) => new RegExp(source, flags).test(window.__TEST__.files.get(rel) ?? ""), [path, pattern.source, pattern.flags]);
/** The saved boards of the catalog. */
export const savedBoards = async page => JSON.parse(await fileText(page, catalogPath)).boards;
/** The element that has focus, as its accessible name or text. */
export const focusedName = page => page.evaluate(() => document.activeElement?.getAttribute("aria-label") ?? document.activeElement?.textContent?.trim());
+165
View File
@@ -0,0 +1,165 @@
// Project Management board state: list capacity and its warning (UI-033), compact list collapse (UI-036), the separate
// collapse state of All tasks, new cards from the list composer, a page reload that keeps the state, the fixed default
// board of the workspace (UI-038), and the first board of a workspace without boards.
// Ports list-limits.spec.ts, list-collapse-create.spec.ts, kanban-cards.spec.ts, board-view-state.spec.ts,
// october-cards.spec.ts (default board and onboarding), and host-board-state.smoke.mjs of RuneStone_Project_Management.
import assert from "node:assert/strict";
import path from "node:path";
import { openPage, outputDir, runSmoke } from "../_harness/index.mjs";
import { bugs, catalogPath, column, fileText, loadWorkspace, openBoard, pane, pmFiles, ribbon, roadmap, savedBoards, setTheme, waitForFile } from "../_harness/pmFixture.mjs";
const listOf = async (page, id, listId) => (await savedBoards(page)).find(item => item.value.id === id).value.lists.find(list => list.id === listId);
const width = async locator => (await locator.boundingBox()).width;
await runSmoke("features/pmBoard", async ({ browser, page }) => {
const output = await outputDir("features/pmBoard");
await loadWorkspace(page);
const catalog = await fileText(page, catalogPath);
// All tasks keeps its collapsed lists in the view state of the tab. The board files stay unchanged.
await openBoard(page);
const allTodo = column(page, "To do");
await allTodo.getByRole("button", { name: "Collapse To do", exact: true }).click();
await allTodo.getByRole("button", { name: "Expand To do", exact: true }).waitFor();
assert.equal(await focusedLabel(page), "Expand To do", "Focus stays on the collapse control");
assert(await width(allTodo) < 60, "A collapsed list is a narrow strip");
assert.equal(await allTodo.locator(".pm-card").count(), 0, "A collapsed list hides its cards");
assert.equal(await allTodo.locator(".pm-count").innerText(), "4", "The strip keeps the card count");
await page.waitForFunction(() => JSON.parse(localStorage.getItem("runestone.pm.viewStates") ?? "{}").planning?.collapsedLists?.includes("list:to do"));
assert.equal(await fileText(page, catalogPath), catalog, "A collapse in All tasks does not write the boards");
// UI-033: All tasks has no list actions and no capacity of a merged list.
assert.equal(await pane(page).locator(".pm-list-actions, .pm-list-limit").count(), 0, "All tasks has no list actions and no list limits");
// A board list starts expanded: the board has its own collapse state.
await openBoard(page, "Roadmap");
const todo = column(page, "To do");
assert.equal(await todo.locator(".pm-card").count(), 3);
// UI-033: a limit below the maximum shows the plain indicator.
const review = column(page, "Review");
assert.equal(await review.locator(".pm-count").innerText(), "0/2");
assert.equal(await review.locator(".pm-list-limit").count(), 1);
assert.equal(await review.locator(".pm-list-limit-reached").count(), 0);
// Set a limit through the list menu. At the maximum, the list shows the warning.
await todo.getByRole("button", { name: "List actions for To do", exact: true }).click();
await page.getByRole("menu", { name: "List actions", exact: true }).getByRole("menuitem", { name: "Set list limit", exact: true }).click();
const limitForm = page.getByRole("dialog", { name: "Set list limit", exact: true });
await limitForm.getByLabel("Maximum cards", { exact: true }).fill("3");
await limitForm.getByRole("button", { name: "Save limit", exact: true }).click();
await limitForm.waitFor({ state: "detached" });
await waitForFile(page, catalogPath, /"maxCards": 3/);
assert.equal(await todo.locator(".pm-count").innerText(), "3/3");
const warning = todo.locator(".pm-list-limit-reached");
assert.match(await warning.getAttribute("aria-label"), /^Active cards in To do: 3\. The maximum is 3\. The list is at the limit\.$/);
// The limit warns but does not block: the composer adds a fourth card.
await todo.getByRole("button", { name: "Add a card", exact: true }).click();
const composer = todo.getByRole("textbox", { name: "Card title", exact: true });
await composer.fill("Composer card");
await composer.press("Enter");
await todo.getByRole("button", { name: "Composer card", exact: true }).waitFor();
await page.waitForFunction(() => [...window.__TEST__.files.values()].some(text => /title: Composer card/.test(text)));
await page.waitForFunction(() => document.querySelector('.plugin-editor-pane .pm-column[aria-label="To do"] .pm-count')?.textContent === "4/3");
assert.match(await warning.getAttribute("aria-label"), /The list is over the limit\.$/);
for (const theme of ["dark", "light"]) {
await setTheme(page, theme);
await warning.focus();
await page.getByRole("tooltip").filter({ hasText: /over the limit/ }).waitFor();
await page.screenshot({ path: path.join(output, `limit-warning-${theme}.png`) });
}
// UI-036: a keyboard collapse saves the board file, keeps the count, and keeps focus on the control.
await todo.getByRole("button", { name: "Collapse To do", exact: true }).focus();
await page.keyboard.press("Enter");
await todo.getByRole("button", { name: "Expand To do", exact: true }).waitFor();
assert.equal(await focusedLabel(page), "Expand To do");
await waitForList(page, roadmap, "todo", list => list.collapsed === true);
assert(await width(todo) < 60);
assert.equal(await todo.locator(".pm-count").innerText(), "4/3", "The strip keeps the count and the limit");
assert.equal(await todo.locator(".pm-list-limit-reached").count(), 1, "The strip keeps the warning");
await column(page, "Done").getByRole("button", { name: "Collapse Done", exact: true }).click();
await waitForList(page, roadmap, "done", list => list.collapsed === true);
for (const theme of ["dark", "light"]) {
await setTheme(page, theme);
await page.screenshot({ path: path.join(output, `collapsed-board-${theme}.png`) });
}
// A reload keeps the board state, the limits, and the collapsed lists of All tasks.
await page.reload();
await page.locator('[data-tree-rel="note.md"]').waitFor();
await openBoard(page, "Roadmap");
await column(page, "To do").getByRole("button", { name: "Expand To do", exact: true }).waitFor();
assert.equal(await column(page, "To do").locator(".pm-count").innerText(), "4/3");
await column(page, "Done").getByRole("button", { name: "Expand Done", exact: true }).waitFor();
assert.equal(await column(page, "In progress").getByRole("button", { name: "Collapse In progress", exact: true }).count(), 1);
await column(page, "To do").getByRole("button", { name: "Expand To do", exact: true }).click();
await waitForList(page, roadmap, "todo", list => list.collapsed === false);
await column(page, "To do").getByRole("button", { name: "Composer card", exact: true }).waitFor();
// The limit indicator opens the limit form. An empty field removes the limit.
await column(page, "To do").locator(".pm-list-limit").click();
await limitForm.getByLabel("Maximum cards", { exact: true }).fill("");
await limitForm.getByRole("button", { name: "Save limit", exact: true }).click();
await waitForList(page, roadmap, "todo", list => list.maxCards === undefined);
assert.equal(await column(page, "To do").locator(".pm-list-limit").count(), 0);
assert.equal(await column(page, "To do").locator(".pm-count").innerText(), "4");
await pane(page).locator(".pm-scope").click();
await page.getByRole("menuitemradio", { name: "All tasks", exact: true }).click();
await column(page, "To do").getByRole("button", { name: "Expand To do", exact: true }).waitFor();
// UI-038: the settings save a default board. The ribbon button then opens it.
await pane(page).getByRole("button", { name: "More actions", exact: true }).click();
await page.getByRole("menuitem", { name: "Project Management settings", exact: true }).click();
const settings = page.getByRole("dialog", { name: "Project Management settings", exact: true });
const defaultBoard = settings.getByRole("button", { name: "Default board", exact: true });
await page.waitForFunction(() => document.querySelector('.pm-settings-popup [aria-label="Default board"]')?.disabled === false);
assert.equal(await defaultBoard.innerText(), "All tasks");
await defaultBoard.click();
await page.getByRole("menuitemradio", { name: "Bugs", exact: true }).click();
await waitForFile(page, catalogPath, new RegExp(`"defaultBoardId": "${bugs}"`));
await page.keyboard.press("Escape");
await settings.waitFor({ state: "detached" });
await ribbon(page).click();
await page.getByRole("tab", { name: "Bugs", exact: true, selected: true }).waitFor();
await pane(page).locator(".pm-card", { hasText: "Card C" }).waitFor();
// An unavailable default opens All tasks.
await page.evaluate(rel => {
const value = JSON.parse(window.__TEST__.files.get(rel));
window.__TEST__.files.set(rel, JSON.stringify({ ...value, defaultBoardId: "missing-board", defaultBoardPath: "pm-board:missing-board" }));
}, catalogPath);
await ribbon(page).click();
await page.getByRole("tab", { name: "Project Management", exact: true, selected: true }).waitFor();
await pane(page).locator(".pm-scope-label", { hasText: /^All tasks$/ }).waitFor();
console.log("PASS: list limits, collapse, reload, and the default board");
// UI-038: a workspace without boards shows a visible action that creates the first board.
const context = await browser.newContext({ viewport: { width: 1280, height: 860 } });
const empty = await openPage(context);
await loadWorkspace(empty, pmFiles({ boards: false }));
await openBoard(empty);
const welcome = empty.getByRole("region", { name: "Create your first board", exact: true });
await welcome.waitFor();
await welcome.getByRole("button", { name: "Create your first board", exact: true }).click();
await empty.getByRole("textbox", { name: "Board name", exact: true }).fill("First board");
await empty.getByRole("dialog", { name: "Create board", exact: true }).getByRole("button", { name: "Create board", exact: true }).click();
await empty.getByRole("tab", { name: "First board", exact: true, selected: true }).waitFor();
await waitForFile(empty, catalogPath, /"name": "First board"/);
await empty.screenshot({ path: path.join(output, "first-board-light.png") });
assert.deepEqual(empty.errors, [], "No page errors in the workspace without boards");
await context.close();
}, { timeout: 15000 });
function focusedLabel(page) {
return page.evaluate(() => document.activeElement?.getAttribute("aria-label"));
}
/** Wait until a list of a saved board matches `test`. */
async function waitForList(page, boardId, listId, test) {
for (let attempt = 0; attempt < 50; attempt++) {
if (test(await listOf(page, boardId, listId))) return;
await page.waitForTimeout(100);
}
throw new Error(`The list ${listId} of ${boardId} did not change`);
}
+135
View File
@@ -0,0 +1,135 @@
// Project Management cards: open and edit a card, description drafts with Save, Cancel, and the unsaved marker (UI-037),
// a list choice that saves at once, the creation time, labels, priority, and delete with a confirmation, in both themes.
// Ports october-cards.spec.ts, description-indicator.spec.ts, card-details.spec.ts, labels.spec.ts, delete-card.spec.ts,
// and kanban-editing.spec.ts of RuneStone_Project_Management.
import assert from "node:assert/strict";
import path from "node:path";
import { outputDir, runSmoke } from "../_harness/index.mjs";
import { cardPath, column, deletedPath, draftPath, fileText, focusedName, loadWorkspace, openBoard, pane, setTheme, waitForFile } from "../_harness/pmFixture.mjs";
const draft = async (page, id) => JSON.parse(await fileText(page, draftPath(id)) ?? "null")?.body;
await runSmoke("features/pmCards", async ({ page }) => {
const output = await outputDir("features/pmCards");
await loadWorkspace(page);
await openBoard(page, "Roadmap");
const editor = page.locator("dialog.pm-card-editor[open]");
// The source field is hidden outside edit mode, so select it by its label attribute.
const description = editor.locator('textarea[aria-label="Details (Markdown)"]');
const unsaved = editor.locator(".pm-description-unsaved");
const descriptionAction = name => editor.locator(".pm-description-actions").getByRole("button", { name, exact: true });
const openCard = async title => {
await pane(page).locator(".pm-card-title", { hasText: new RegExp(`^${title}$`) }).click();
await editor.waitFor();
};
const closeCard = async () => {
await editor.getByRole("button", { name: "Close card", exact: true }).click();
await editor.waitFor({ state: "detached" });
};
// The details show the saved creation time.
await openCard("Card A");
const created = editor.locator(".pm-created-at");
assert.match(await created.innerText(), /^Created: (?!Unknown)/);
assert.equal(await created.getAttribute("title"), "2026-10-01T08:30:00.000Z");
assert.equal(await editor.getByRole("textbox", { name: "Title", exact: true }).inputValue(), "Card A");
// UI-037: a description edit stays a draft when the card closes. The saved description does not change.
await editor.getByRole("button", { name: "Edit", exact: true }).click();
await description.fill("Draft text");
await unsaved.waitFor();
assert.equal(await unsaved.innerText(), "Unsaved changes");
await closeCard();
await page.waitForFunction(rel => /"body":"Draft text"/.test(window.__TEST__.files.get(rel) ?? ""), draftPath("card-a"));
assert.match(await fileText(page, cardPath("card-a")), /\nBody of Card A\.\n$/, "Close keeps the saved description");
const marker = pane(page).locator('.pm-card[data-task-id="card-a"] .pm-card-unsaved');
await marker.waitFor();
assert.equal(await marker.innerText(), "Unsaved description");
// The card opens with the saved description and the marker. Edit shows the draft. Cancel restores the saved text.
await openCard("Card A");
await unsaved.waitFor();
assert.equal(await editor.getByRole("region", { name: "Description preview", exact: true }).innerText(), "Body of Card A.");
await editor.getByRole("button", { name: "Edit", exact: true }).click();
assert.equal(await description.inputValue(), "Draft text");
await descriptionAction("Cancel").click();
await unsaved.waitFor({ state: "hidden" });
assert.equal((await description.inputValue()).trim(), "Body of Card A.");
assert.equal(await draft(page, "card-a"), null, "Cancel removes the draft");
// Save commits the description at once. The creation time does not change.
await editor.getByRole("button", { name: "Edit", exact: true }).click();
await description.fill("Saved description");
await descriptionAction("Save").click();
await waitForFile(page, cardPath("card-a"), /\nSaved description\n?$/);
await unsaved.waitFor({ state: "hidden" });
assert.match(await fileText(page, cardPath("card-a")), /createdAt: "?2026-10-01T08:30:00.000Z"?/);
assert.equal(await draft(page, "card-a"), null);
await closeCard();
await marker.waitFor({ state: "hidden" });
// UI-037: a list choice in the details saves at once, before Save card.
await openCard("Shared card");
await editor.getByRole("button", { name: "List", exact: true }).click();
await page.getByRole("menu", { name: "List", exact: true }).getByRole("menuitemradio", { name: "Done", exact: true }).click();
await waitForFile(page, cardPath("card-d"), /listId: done/);
assert.match(await fileText(page, cardPath("card-d")), /status: done/, "The list status applies at once");
await closeCard();
await column(page, "Done").locator(".pm-card-title", { hasText: "Shared card" }).waitFor();
// Title, labels, and priority save with Save card.
await openCard("Card B");
await editor.getByRole("textbox", { name: "Title", exact: true }).fill("Card B edited");
const details = editor.getByRole("group", { name: "Card details", exact: true });
await details.getByRole("button", { name: "Labels", exact: true }).click();
const labels = page.getByRole("dialog", { name: "Choose labels", exact: true });
await labels.getByRole("button", { name: "Add label Bug", exact: true }).click();
await editor.getByRole("button", { name: "Remove label Bug", exact: true }).waitFor({ state: "attached" });
await page.keyboard.press("Escape");
await labels.waitFor({ state: "hidden" });
assert.equal(await editor.count(), 1, "Escape closes only the label choices");
const priority = details.getByRole("button", { name: "Priority", exact: true });
await priority.click();
await page.getByRole("menu", { name: "Choose priority", exact: true }).getByRole("menuitemradio", { name: "High priority", exact: true }).click();
await details.getByRole("button", { name: "High priority", exact: true }).waitFor();
for (const theme of ["dark", "light"]) {
await setTheme(page, theme);
await page.screenshot({ path: path.join(output, `card-details-${theme}.png`) });
}
await editor.getByRole("button", { name: "Save card", exact: true }).click();
await editor.waitFor({ state: "detached" });
await waitForFile(page, cardPath("card-b"), /title: Card B edited/);
const saved = await fileText(page, cardPath("card-b"));
assert.match(saved, /priority: high/);
assert.match(saved, /labels:\n\s+- bug/);
const edited = pane(page).locator('.pm-card[data-task-id="card-b"]');
assert.equal(await edited.locator(".pm-priority").innerText(), "High priority");
assert.equal(await edited.locator(".pm-label-badge").innerText(), "Bug");
assert.match(await fileText(page, cardPath("card-c")), /title: Card C/, "Other cards stay unchanged");
// Delete asks for a confirmation. Cancel keeps the card and returns focus to the card menu.
const actions = pane(page).getByRole("button", { name: "Actions for Card A", exact: true });
const confirm = page.getByRole("dialog", { name: "Delete card", exact: true });
await actions.click();
await page.getByRole("menu", { name: "Card actions", exact: true }).getByRole("menuitem", { name: "Delete card", exact: true }).click();
await confirm.getByRole("heading", { name: "Delete “Card A”?", exact: true }).waitFor();
assert.equal(await focusedName(page), "Cancel", "The safe choice has focus");
for (const theme of ["dark", "light"]) {
await setTheme(page, theme);
await page.screenshot({ path: path.join(output, `delete-card-${theme}.png`) });
}
await confirm.getByRole("button", { name: "Cancel", exact: true }).click();
await confirm.waitFor({ state: "detached" });
assert.equal(await focusedName(page), "Actions for Card A");
assert.equal(await fileText(page, deletedPath), undefined, "Cancel deletes nothing");
await actions.click();
await page.getByRole("menu", { name: "Card actions", exact: true }).getByRole("menuitem", { name: "Delete card", exact: true }).click();
await confirm.getByRole("button", { name: "Delete card", exact: true }).click();
await confirm.waitFor({ state: "detached" });
await waitForFile(page, deletedPath, /"card-a"/);
await pane(page).locator('.pm-card[data-task-id="card-a"]').waitFor({ state: "detached" });
assert.equal(await focusedName(page), "More actions", "Focus moves to the board menu after the card is gone");
assert.equal(await column(page, "To do").locator(".pm-card").count(), 1);
console.log("PASS: card details, description drafts, labels, priority, and delete");
}, { timeout: 15000 });
+70
View File
@@ -0,0 +1,70 @@
// Project Management drag and drop: a card to another list, a card to a new place in its list, and a list to a new
// place on the board. Each drop saves the files. All tasks has no drag and drop (UI-033).
// Ports card-placement.spec.ts, card-transfer.spec.ts (drag part), lists.spec.ts, and kanban-cards.spec.ts
// of RuneStone_Project_Management.
import assert from "node:assert/strict";
import path from "node:path";
import { outputDir, runSmoke } from "../_harness/index.mjs";
import { cardPath, column, fileText, loadWorkspace, openBoard, pane, roadmap, savedBoards, setTheme, waitForFile } from "../_harness/pmFixture.mjs";
const titles = locator => locator.locator(".pm-card-title").allInnerTexts();
const columnIds = page => pane(page).locator("section.pm-column").evaluateAll(nodes => nodes.map(node => node.dataset.listId));
await runSmoke("features/pmDrag", async ({ page }) => {
const output = await outputDir("features/pmDrag");
await loadWorkspace(page);
await openBoard(page, "Roadmap");
/** Drag `source` to a point of `target` with the mouse, and take a screenshot before the drop. */
async function drag(source, target, { x = 0.5, y = 0.5, shot }) {
const from = await source.boundingBox(), to = await target.boundingBox();
await page.mouse.move(from.x + from.width / 2, from.y + Math.min(12, from.height / 2));
await page.mouse.down();
await page.mouse.move(from.x + from.width / 2 + 20, from.y + 20, { steps: 4 });
await page.mouse.move(to.x + to.width * x, to.y + to.height * y, { steps: 8 });
if (shot) {
await pane(page).locator(".pm-drag-preview").waitFor();
await page.screenshot({ path: path.join(output, shot) });
}
await page.mouse.up();
}
// A card goes to another list. The list status applies, and only that card file changes.
await setTheme(page, "dark");
const cardC = await fileText(page, cardPath("card-c"));
await drag(pane(page).locator('.pm-card[data-task-id="card-a"]'), column(page, "In progress"), { y: 0.3, shot: "card-drag-dark.png" });
await waitForFile(page, cardPath("card-a"), /listId: doing/);
assert.match(await fileText(page, cardPath("card-a")), /status: doing/);
assert.deepEqual(await titles(column(page, "In progress")), ["Card A"]);
assert.deepEqual(await titles(column(page, "To do")), ["Card B", "Shared card"]);
assert.equal(await fileText(page, cardPath("card-c")), cardC, "Other cards stay unchanged");
assert.equal(await pane(page).locator(".pm-drag-preview, .pm-drop-target").count(), 0, "The drop removes the drag preview");
// A card goes above another card of the same list.
await drag(pane(page).locator('.pm-card[data-task-id="card-d"]'), pane(page).locator('.pm-card[data-task-id="card-b"]'), { y: 0.2 });
await page.waitForFunction(() => [...document.querySelectorAll('.plugin-editor-pane .pm-column[aria-label="To do"] .pm-card-title')].map(node => node.textContent).join() === "Shared card,Card B");
const order = async id => /\n {6}order: "([^"]+)"/.exec(await fileText(page, cardPath(id)))[1];
assert(await order("card-d") < await order("card-b"), "The saved order puts Shared card first");
// A list goes to a new place: the grip of Done goes to the left half of To do.
await setTheme(page, "light");
const grip = column(page, "Done").getByRole("button", { name: "Move list Done", exact: true });
await drag(grip, column(page, "To do"), { x: 0.2, y: 0.2, shot: "list-drag-light.png" });
await page.waitForFunction(() => [...document.querySelectorAll(".plugin-editor-pane .pm-column")].map(node => node.dataset.listId).join() === "done,todo,doing,review");
assert.deepEqual((await savedBoards(page)).find(item => item.value.id === roadmap).value.lists.map(list => list.id), ["done", "todo", "doing", "review"]);
assert.deepEqual(await columnIds(page), ["done", "todo", "doing", "review"]);
await page.screenshot({ path: path.join(output, "after-drops-light.png") });
// UI-033: All tasks has no drag and drop. Its cards and lists cannot move.
await pane(page).locator(".pm-scope").click();
await page.getByRole("menuitemradio", { name: "All tasks", exact: true }).click();
await pane(page).locator(".pm-scope-label", { hasText: /^All tasks$/ }).waitFor();
await pane(page).locator(".pm-card").first().waitFor();
assert.deepEqual([...new Set(await pane(page).locator(".pm-card").evaluateAll(nodes => nodes.map(node => node.draggable)))], [false]);
assert.equal(await pane(page).locator(".pm-list-grip").count(), 0);
const before = await fileText(page, cardPath("card-b"));
await drag(pane(page).locator('.pm-card[data-task-id="card-b"]'), column(page, "Done"), {});
await page.waitForTimeout(300);
assert.equal(await fileText(page, cardPath("card-b")), before, "A drag in All tasks changes nothing");
console.log("PASS: card and list drag and drop, and no drag in All tasks");
}, { timeout: 15000 });
+88
View File
@@ -0,0 +1,88 @@
// Project Management in French: a language change in the settings shows an open board again in the new language and
// closes its open menu. The controls, menus, card details, and All tasks show French text from the catalog
// (src/lib/i18n/messages.ts). Board names, list names, and card titles stay as the user typed them.
// A change back to English shows English again. New in RuneStone: the plugin had no translations.
import assert from "node:assert/strict";
import path from "node:path";
import { outputDir, runSmoke } from "../_harness/index.mjs";
import { column, loadWorkspace, openBoard, pane, setTheme } from "../_harness/pmFixture.mjs";
await runSmoke("features/pmLanguage", async ({ page }) => {
const output = await outputDir("features/pmLanguage");
await loadWorkspace(page);
await openBoard(page, "Roadmap");
const catalog = await page.evaluate(async () => (await import("/src/lib/i18n/messages.ts")).catalogs.fr);
/** The French text of a catalog key, with its values. */
const fr = (key, values = {}) => {
assert(Object.hasOwn(catalog, key), `The catalog has "${key}"`);
return catalog[key].replace(/\{(\w+)\}/g, (_, name) => values[name]);
};
const button = name => pane(page).getByRole("button", { name, exact: true });
const setLanguage = async language => {
await page.evaluate(value => window.__TEST__.writeSettings("language", value), language);
await page.waitForFunction(value => document.documentElement.lang === value, language);
};
// An open menu closes when the language changes. The board shows again in French.
await button("List actions for To do").click();
await page.getByRole("menu", { name: "List actions", exact: true }).waitFor();
await setLanguage("fr");
await page.locator(".rs-menu").waitFor({ state: "detached" });
await button(fr("More actions")).waitFor();
assert.equal(fr("More actions"), "Plus d’actions");
assert.equal(fr("Calendar"), "Calendrier");
const views = pane(page).getByRole("navigation", { name: fr("Project Management views"), exact: true });
assert.deepEqual(await views.getByRole("button").evaluateAll(nodes => nodes.map(node => node.getAttribute("aria-label"))), [fr("Kanban"), fr("Gantt"), fr("Calendar")]);
for (const name of [fr("Search tasks"), fr("Manage labels"), fr("Add a list"), fr("Board scope: {name}", { name: "Roadmap" }),
fr("List actions for {name}", { name: "To do" }), fr("Collapse {name}", { name: "To do" }), fr("Actions for {name}", { name: "Card A" })]) {
assert.equal(await button(name).count() > 0, true, `The board has the control "${name}"`);
}
assert.equal(await column(page, "To do").getByRole("button", { name: fr("Add a card"), exact: true }).count(), 1);
assert.equal(await button("More actions").count(), 0, "No English control name stays");
// The text that the user typed stays unchanged.
assert.equal(await pane(page).locator(".pm-scope-label").innerText(), "Roadmap");
await page.getByRole("tab", { name: "Roadmap", exact: true }).waitFor();
assert.deepEqual(await column(page, "To do").locator(".pm-card-title").allInnerTexts(), ["Card A", "Card B", "Shared card"]);
assert.deepEqual(await pane(page).locator(".pm-column-heading h2").allInnerTexts(), ["To do", "In progress", "Done", "Review"]);
// The shared menus show French items.
await button(fr("List actions for {name}", { name: "To do" })).focus();
await page.keyboard.press("Enter");
const listMenu = page.getByRole("menu", { name: fr("List actions"), exact: true });
await listMenu.waitFor();
assert.deepEqual((await listMenu.getByRole("menuitem").allInnerTexts()).slice(0, 2), [fr("Edit list"), fr("Set list limit")]);
for (const theme of ["dark", "light"]) {
await setTheme(page, theme);
await page.screenshot({ path: path.join(output, `board-menu-fr-${theme}.png`) });
}
await page.keyboard.press("Escape");
await listMenu.waitFor({ state: "detached" });
// The card details are in French. The card title stays.
await pane(page).locator(".pm-card-title", { hasText: /^Card A$/ }).click();
const editor = page.locator("dialog.pm-card-editor[open]");
await editor.waitFor();
assert.equal(await editor.getByRole("textbox", { name: fr("Title"), exact: true }).inputValue(), "Card A");
assert.ok((await editor.locator(".pm-created-at").innerText()).startsWith(fr("Created: {date}", { date: "" })));
await editor.getByRole("button", { name: fr("Save card"), exact: true }).waitFor();
await page.screenshot({ path: path.join(output, "card-fr-light.png") });
await editor.getByRole("button", { name: fr("Close card"), exact: true }).click();
await editor.waitFor({ state: "detached" });
// All tasks: the catalog name of a group without a board translates. Board names stay.
await pane(page).locator(".pm-scope").click();
await page.getByRole("menu", { name: fr("Board scope"), exact: true }).getByRole("menuitemradio", { name: fr("All tasks"), exact: true }).click();
await pane(page).locator(".pm-scope-label", { hasText: fr("All tasks") }).waitFor();
await page.getByRole("tab", { name: "Project Management", exact: true }).waitFor();
assert.deepEqual(await column(page, "To do").locator(".pm-board-group-heading").allInnerTexts(), ["Bugs · Roadmap", "Roadmap", fr("No active board")]);
await page.screenshot({ path: path.join(output, "all-tasks-fr-light.png") });
// A change back to English shows the open view in English at once.
await setLanguage("en");
await button("More actions").waitFor();
assert.equal(await pane(page).locator(".pm-scope-label").innerText(), "All tasks");
assert.deepEqual(await column(page, "To do").locator(".pm-board-group-heading").allInnerTexts(), ["Bugs · Roadmap", "Roadmap", "No active board"]);
assert.equal(await button(fr("More actions")).count(), 0);
console.log("PASS: French controls, menus, and card details, with the typed names unchanged");
}, { timeout: 15000 });
+127
View File
@@ -0,0 +1,127 @@
// Project Management menus: the list actions, the card actions with the Move to list submenu, the board scope, and
// More actions. All use the shared host menu. Each opens with the keyboard, in the dark and the light theme, at a wide
// and a narrow width. The arrow keys move the focus, Enter runs an item, and Escape closes the menu and returns focus.
// Ports menu-audit.spec.ts, shared-menu.spec.ts, board-menu-api.spec.ts, and relations-menu.spec.ts (keyboard part)
// of RuneStone_Project_Management.
import assert from "node:assert/strict";
import path from "node:path";
import { outputDir, runSmoke, settle } from "../_harness/index.mjs";
import { cardPath, column, focusedName, loadWorkspace, openBoard, pane, roadmap, savedBoards, setTheme, waitForFile } from "../_harness/pmFixture.mjs";
await runSmoke("features/pmMenus", async ({ page }) => {
const output = await outputDir("features/pmMenus");
await loadWorkspace(page);
await openBoard(page, "Roadmap");
const listTrigger = column(page, "To do").getByRole("button", { name: "List actions for To do", exact: true });
const cardTrigger = pane(page).getByRole("button", { name: "Actions for Card A", exact: true });
const scope = pane(page).getByRole("button", { name: "Board scope: Roadmap", exact: true });
const moreTrigger = pane(page).getByRole("button", { name: "More actions", exact: true });
const menu = name => page.getByRole("menu", { name, exact: true });
const items = async name => menu(name).locator(":scope > button").evaluateAll(rows => rows.map(row => `${row.textContent.trim()}${row.disabled ? " (disabled)" : ""}`));
/** Open a menu with `key` on its focused trigger, and return the menu after its checks. */
async function open(trigger, key, name) {
await trigger.focus();
await page.keyboard.press(key);
const panel = menu(name);
await panel.waitFor();
assert.equal(await panel.evaluate(node => node.classList.contains("rs-menu")), true, `${name} uses the shared menu`);
const box = await panel.boundingBox(), viewport = page.viewportSize();
assert(box.x >= 0 && box.y >= 0 && box.x + box.width <= viewport.width + 1 && box.y + box.height <= viewport.height + 1, `${name} stays inside the window`);
return panel;
}
/** Press Escape, and make sure that the menu closes and the trigger has focus again. */
async function dismiss(name, trigger) {
await page.keyboard.press("Escape");
await menu(name).waitFor({ state: "detached" });
assert.equal(await focusedName(page), trigger, `Escape returns focus to ${trigger}`);
}
for (const theme of ["dark", "light"]) {
await setTheme(page, theme);
for (const width of [1440, 760]) {
await page.setViewportSize({ width, height: width === 1440 ? 1000 : 700 });
// A window resize closes an open menu. Let the resize event pass first.
await settle(page);
const shot = name => page.screenshot({ path: path.join(output, `${name}-${theme}-${width}.png`) });
// List actions: Enter opens the menu on the first item. The arrow keys skip a disabled item.
await column(page, "To do").scrollIntoViewIfNeeded();
await open(listTrigger, "Enter", "List actions");
assert.deepEqual(await items("List actions"), ["Edit list", "Set list limit", "Move left (disabled)", "Move right", "Archive all cards", "Delete list"]);
assert.equal(await focusedName(page), "Edit list");
await page.keyboard.press("ArrowDown");
assert.equal(await focusedName(page), "Set list limit");
await page.keyboard.press("ArrowDown");
assert.equal(await focusedName(page), "Move right", "ArrowDown skips the disabled item");
await shot("list-actions");
await dismiss("List actions", "List actions for To do");
// Card actions: ArrowDown on the card menu button opens the menu. ArrowRight opens the list submenu.
await open(cardTrigger, "ArrowDown", "Card actions");
assert.deepEqual(await items("Card actions"), ["Edit card", "Move to list", "Move to board", "Move up (disabled)", "Move down", "Remove from board", "Archive", "Delete card"]);
assert.equal(await focusedName(page), "Edit card");
await page.keyboard.press("ArrowDown");
assert.equal(await focusedName(page), "Move to list");
await page.keyboard.press("ArrowRight");
const submenu = menu("Move to list");
await submenu.waitFor();
assert.equal(await submenu.getByRole("menuitemradio", { name: "To do", exact: true }).getAttribute("aria-checked"), "true");
assert.equal(await focusedName(page), "Unlisted");
await shot("card-actions");
await page.keyboard.press("ArrowLeft");
assert.equal(await focusedName(page), "Move to list", "ArrowLeft returns to the parent item");
await dismiss("Card actions", "Actions for Card A");
// Board scope: the boards are in name order, and the focus starts on the checked board.
await open(scope, "ArrowDown", "Board scope");
assert.deepEqual(await menu("Board scope").getByRole("menuitemradio").allInnerTexts(), ["All tasks", "Bugs", "Roadmap"]);
assert.equal(await focusedName(page), "Roadmap");
await page.keyboard.press("ArrowUp");
assert.equal(await focusedName(page), "Bugs");
await shot("board-scope");
await dismiss("Board scope", "Board scope: Roadmap");
// More actions: the board commands.
await open(moreTrigger, "Enter", "More actions");
assert.deepEqual(await items("More actions"), ["New board", "Archive board", "Delete board", "Rename board", "New card", "Add existing note", "Show archived", "Refresh", "Customize background", "Project Management settings"]);
assert.equal(await focusedName(page), "New board");
await page.keyboard.press("End");
assert.equal(await focusedName(page), "Project Management settings");
await shot("more-actions");
await dismiss("More actions", "More actions");
}
}
await page.setViewportSize({ width: 1440, height: 1000 });
await settle(page);
// Enter runs the focused item. Move right changes the list order.
await open(listTrigger, "Enter", "List actions");
await page.keyboard.press("ArrowDown");
await page.keyboard.press("ArrowDown");
await page.keyboard.press("Enter");
await menu("List actions").waitFor({ state: "detached" });
await page.waitForFunction(() => [...document.querySelectorAll(".plugin-editor-pane .pm-column")].map(node => node.dataset.listId).join() === "doing,todo,done,review");
assert.deepEqual((await savedBoards(page)).find(item => item.value.id === roadmap).value.lists.map(list => list.id), ["doing", "todo", "done", "review"]);
// Enter on a submenu item moves the card to that list.
await open(cardTrigger, "ArrowDown", "Card actions");
await page.keyboard.press("ArrowDown");
await page.keyboard.press("ArrowRight");
await menu("Move to list").waitFor();
// The submenu follows the new list order: Unlisted, In progress, To do, Done, Review.
await page.keyboard.press("ArrowDown");
assert.equal(await focusedName(page), "In progress");
await page.keyboard.press("Enter");
await waitForFile(page, cardPath("card-a"), /listId: doing/);
await column(page, "In progress").locator(".pm-card-title", { hasText: "Card A" }).waitFor();
// Enter on a board opens it in the same tab.
await open(scope, "ArrowDown", "Board scope");
await page.keyboard.press("ArrowUp");
await page.keyboard.press("Enter");
await page.getByRole("tab", { name: "Bugs", exact: true, selected: true }).waitFor();
await pane(page).getByRole("button", { name: "Board scope: Bugs", exact: true }).waitFor();
assert.equal(await page.getByRole("tab", { name: "Roadmap", exact: true }).count(), 0);
console.log("PASS: list, card, board scope, and board menus with the keyboard in both themes");
}, { timeout: 15000 });
+92
View File
@@ -0,0 +1,92 @@
// Project Management views: All tasks with merged list columns and board dividers (UI-034, UI-035), then Gantt,
// Calendar (month, week, and day), and Kanban, in both themes. Each view keeps its own view state.
// Ports all-tasks.spec.ts, board-scope-alignment.spec.ts, board-view-state.spec.ts, and the Gantt and Calendar parts of
// workflow.spec.ts of RuneStone_Project_Management.
import assert from "node:assert/strict";
import path from "node:path";
import { outputDir, runSmoke } from "../_harness/index.mjs";
import { card, column, loadWorkspace, openBoard, pane, pmFiles, roadmap, setTheme } from "../_harness/pmFixture.mjs";
await runSmoke("features/pmViews", async ({ page }) => {
const output = await outputDir("features/pmViews");
// One more card on the Review list of Roadmap, so that the merged review column has two boards.
await loadWorkspace(page, Object.fromEntries([...Object.entries(pmFiles()), card("card-f", "Review card", { placements: { [roadmap]: "review" }, order: "f" })]));
await openBoard(page);
const view = name => pane(page).getByRole("navigation", { name: "Project Management views", exact: true }).getByRole("button", { name, exact: true });
const shots = async name => {
for (const theme of ["dark", "light"]) {
await setTheme(page, theme);
await page.screenshot({ path: path.join(output, `${name}-${theme}.png`) });
}
};
// UI-034: equal list names share one column. Case and outer spaces do not matter ("Review" and "review").
await pane(page).locator(".pm-card").first().waitFor();
assert.equal(await view("Kanban").getAttribute("aria-pressed"), "true");
const labels = await pane(page).locator("section.pm-column").evaluateAll(nodes => nodes.map(node => node.getAttribute("aria-label")));
assert.deepEqual(labels.map(label => label.toLowerCase()), ["to do", "in progress", "done", "review"]);
// UI-035: each column groups its cards under board names. A shared card shows once, under the names of its boards.
const todo = column(page, "To do");
const headings = locator => locator.locator(".pm-board-group-heading").allInnerTexts();
assert.deepEqual(await headings(todo), ["Bugs · Roadmap", "Roadmap", "No active board"]);
assert.equal(await todo.locator(".pm-card-title", { hasText: /^Shared card$/ }).count(), 1, "A shared card shows once");
assert.deepEqual(await todo.getByRole("region", { name: "Roadmap", exact: true }).locator(".pm-card-title").allInnerTexts(), ["Card A", "Card B"]);
assert.deepEqual(await todo.getByRole("region", { name: "No active board", exact: true }).locator(".pm-card-title").allInnerTexts(), ["Loose card"]);
const review = pane(page).locator('section.pm-column[data-list-id="list:review"]');
assert.deepEqual(await headings(review), ["Bugs", "Roadmap"]);
// A merged column has no board limit. The board keeps its limit (checked below).
assert.equal(await review.locator(".pm-list-limit").count(), 0);
assert.equal(await review.locator(".pm-count").innerText(), "2");
assert.equal(await pane(page).locator(".pm-board-group-heading").evaluateAll(nodes => nodes.every(node => getComputedStyle(node).opacity === "1")), true, "Board names are opaque");
await shots("all-tasks");
// Gantt: a row for each card, a bar for the planned dates, and a deadline marker.
await view("Gantt").click();
assert.equal(await view("Gantt").getAttribute("aria-pressed"), "true");
const timeline = pane(page).getByRole("table", { name: "Task timeline", exact: true });
await timeline.waitFor();
assert.equal(await timeline.locator(".pm-gantt-row").count(), 7, "A heading row and six cards");
const bar = timeline.locator(".pm-gantt-bar", { hasText: "Card B" });
assert.match(await bar.getAttribute("title"), /^Card B: .+ to .+$/);
assert.equal(await timeline.locator(".pm-deadline").count(), 1);
assert.match(await timeline.locator(".pm-deadline").getAttribute("aria-label"), /^Card B, deadline /);
assert.equal(await timeline.getByRole("button", { name: /^Card A/ }).locator("small").innerText(), "Unscheduled");
await pane(page).getByRole("button", { name: "Next", exact: true }).click();
await pane(page).getByRole("button", { name: "Today", exact: true }).click();
await timeline.locator(".pm-gantt-bar").waitFor();
await shots("gantt");
// Calendar: the month shows the deadline. Week and Day show the hours.
await view("Calendar").click();
const period = name => pane(page).locator(".pm-date-nav").getByRole("button", { name, exact: true });
assert.equal(await period("Month").getAttribute("aria-pressed"), "true");
await pane(page).locator(".pm-month").waitFor();
assert.equal(await pane(page).locator(".pm-day-heading").count(), 7);
assert.equal(await pane(page).locator(".pm-month-day").count(), 42);
await pane(page).getByRole("button", { name: "◆ Due: Card B", exact: true }).waitFor();
await shots("calendar-month");
await period("Week").click();
assert.equal(await pane(page).locator(".pm-hour-day").count(), 7);
assert.equal(await period("Week").getAttribute("aria-pressed"), "true");
await shots("calendar-week");
await period("Day").click();
assert.equal(await pane(page).locator(".pm-hour-day").count(), 1);
assert.equal(await pane(page).locator(".pm-hour-day .pm-hour-slot").count(), 24);
await page.waitForFunction(() => {
const state = JSON.parse(localStorage.getItem("runestone.pm.viewStates") ?? "{}").planning;
return state?.view === "calendar" && state?.period === "day";
});
// Kanban again. A board in the same tab has its own view state and shows its limit.
await view("Kanban").click();
await pane(page).locator(".pm-board").waitFor();
await openBoard(page, "Roadmap");
assert.equal(await view("Kanban").getAttribute("aria-pressed"), "true", "A board starts in Kanban");
assert.equal(await column(page, "Review").locator(".pm-count").innerText(), "1/2");
assert.equal(await column(page, "Review").locator(".pm-list-limit").count(), 1);
await view("Calendar").click();
await pane(page).locator(".pm-month").waitFor();
await shots("board-calendar");
console.log("PASS: All tasks columns and dividers, Gantt, Calendar, and Kanban");
}, { timeout: 15000 });
+4 -4
View File
@@ -116,8 +116,8 @@ await runSmoke('tree/renameUndo', async ({ browser }) => {
await page.keyboard.press('Escape'); await page.keyboard.press('Escape');
await page.evaluate(async () => { await page.evaluate(async () => {
const external = await import(performance.getEntriesByType('resource').find(entry => new URL(entry.name).pathname === '/src/lib/plugins/external.ts').name); const external = await import(performance.getEntriesByType('resource').find(entry => new URL(entry.name).pathname === '/src/lib/plugins/external.ts').name);
external.pluginNavigation.set([{ owner: 'pm-test', id: 'pm', title: 'Project Management', icon: 'kanban', placement: 'editor', toolbar: true }, { owner: 'git-test', id: 'source', title: 'Source control', icon: 'git', placement: 'sidebar', toolbar: true }]); external.pluginNavigation.set([{ owner: 'pm-test', id: 'pm', title: 'Board fixture', icon: 'kanban', placement: 'editor', toolbar: true }, { owner: 'git-test', id: 'source', title: 'Source control', icon: 'git', placement: 'sidebar', toolbar: true }]);
external.pluginTools.set([{ owner: 'pm-test', id: 'pm', title: 'Project Management', kind: 'view', surface: 'open' }, { owner: 'git-test', id: 'graph', title: 'Graph view', kind: 'command', surface: 'open', icon: 'git' }]); external.pluginTools.set([{ owner: 'pm-test', id: 'pm', title: 'Board fixture', kind: 'view', surface: 'open' }, { owner: 'git-test', id: 'graph', title: 'Graph view', kind: 'command', surface: 'open', icon: 'git' }]);
external.pluginTools.update(items => [...items, { owner: 'runestone.browser', id: 'new-tab', title: 'New browser tab', kind: 'command', surface: 'open' }]); external.pluginTools.update(items => [...items, { owner: 'runestone.browser', id: 'new-tab', title: 'New browser tab', kind: 'command', surface: 'open' }]);
const registry = await import(performance.getEntriesByType('resource').find(entry => new URL(entry.name).pathname === '/src/lib/plugins/registry.ts').name); const registry = await import(performance.getEntriesByType('resource').find(entry => new URL(entry.name).pathname === '/src/lib/plugins/registry.ts').name);
registry.pluginHost.get('browser').newTab = async () => { window.__TEST__.browserOpened = true; }; registry.pluginHost.get('browser').newTab = async () => { window.__TEST__.browserOpened = true; };
@@ -125,11 +125,11 @@ await runSmoke('tree/renameUndo', async ({ browser }) => {
// The app tools are in the left ribbon. Plugin view shortcuts stay out of it in this test (src/lib/layout/PluginRibbon.svelte). // The app tools are in the left ribbon. Plugin view shortcuts stay out of it in this test (src/lib/layout/PluginRibbon.svelte).
await page.locator('.plugin-ribbon').getByRole('button', { name: 'New browser tab', exact: true }).click(); await page.locator('.plugin-ribbon').getByRole('button', { name: 'New browser tab', exact: true }).click();
assert.equal(await page.evaluate(() => window.__TEST__.browserOpened), true); assert.equal(await page.evaluate(() => window.__TEST__.browserOpened), true);
assert.equal(await page.locator('.plugin-ribbon .ribbon-tools').getByRole('button', { name: 'Project Management', exact: true }).count(), 0); assert.equal(await page.locator('.plugin-ribbon .ribbon-tools').getByRole('button', { name: 'Board fixture', exact: true }).count(), 0);
assert.equal(await page.locator('.header-left').getByRole('button', { name: 'Source control', exact: true }).count(), 1); assert.equal(await page.locator('.header-left').getByRole('button', { name: 'Source control', exact: true }).count(), 1);
assert.equal(await page.locator('.plugin-ribbon .ribbon-tools').getByRole('button', { name: 'Source control', exact: true }).count(), 0); assert.equal(await page.locator('.plugin-ribbon .ribbon-tools').getByRole('button', { name: 'Source control', exact: true }).count(), 0);
await page.getByRole('button', { name: 'Plug-in views', exact: true }).click(); await page.getByRole('button', { name: 'Plug-in views', exact: true }).click();
assert.equal(await page.getByRole('menuitem', { name: /Project Management/ }).count(), 1); assert.equal(await page.getByRole('menuitem', { name: /Board fixture/ }).count(), 1);
assert.equal(await page.getByRole('menuitem', { name: /New browser tab/ }).count(), 0); assert.equal(await page.getByRole('menuitem', { name: /New browser tab/ }).count(), 0);
await page.getByRole('menuitem', { name: /Graph view/ }).waitFor(); await page.keyboard.press('Escape'); await page.getByRole('menuitem', { name: /Graph view/ }).waitFor(); await page.keyboard.press('Escape');
for (const mode of ['light', 'dark']) { for (const mode of ['light', 'dark']) {