33 Commits
Author SHA1 Message Date
yyc12345 0672735fe0 feat(packaging): pack macos builds as a dmg disk image 2026-10-10 09:53:54 +08:00
yyc12345 62c62956d3 chore(ci): upload artifacts unzipped via upload-artifact v7 2026-10-10 09:20:50 +08:00
yyc12345 97b44a4b85 chore(ci): fix github action workflow
- use macos-latest instead of macos-15
2026-10-09 22:56:20 +08:00
yyc12345 309f37eead doc: remove developer docs 2026-10-06 09:51:29 +08:00
yyc12345 6b5a59cd87 refactor(i18n): take language labels from culture native names 2026-10-05 15:42:53 +08:00
yyc12345 506fb4b2f1 feat(i18n): add japanese (ja) localization 2026-10-05 15:32:57 +08:00
yyc12345 b7a6373e17 chore: bump version to 0.3.0 2026-10-05 15:11:11 +08:00
yyc12345 2220fcf48b chore(macos): change macos package id 2026-10-05 14:09:10 +08:00
yyc12345 b0024f3aa4 chore(assets): regenerate the app icons from a new svg 2026-10-05 14:08:22 +08:00
yyc12345 aba62a58c2 feat(packaging): build a windows installer with inno setup 2026-10-05 13:55:05 +08:00
yyc12345 61d3a0c03c fix(ui): use the Semi TextArea class for multiline editor inputs 2026-10-05 13:33:19 +08:00
yyc12345 c2b744e742 feat(ui): give dialog buttons distinct primary and danger levels 2026-10-05 13:20:49 +08:00
yyc12345 9c47ce6b38 refactor(ui): replace opacity dimming with Semi secondary text classes 2026-10-05 12:27:58 +08:00
yyc12345 704b0ff3cf feat(ui): cap the card content preview at 200 chars and 10 lines 2026-10-05 12:13:12 +08:00
yyc12345 a9e97d9b35 feat(ui): show the tag count beside the add-tag button 2026-10-05 12:09:52 +08:00
yyc12345 da2a73d70f docs: rewrite USAGE in the thematic style and expand README 2026-10-05 11:26:09 +08:00
yyc12345 68e4ace92b ci: build only the osx-arm64 macOS target 2026-10-04 22:15:23 +08:00
yyc12345 e9f39a3a53 chore: bump version to 0.2.0 2026-10-04 16:25:27 +08:00
yyc12345 60619e0290 feat(ui): apply flow direction to modals, default confirmations to Cancel and guard code-behind resources 2026-10-04 16:18:08 +08:00
yyc12345 e3265e3c89 fix(launch): reject option-like and missing paths, resolve them absolute and drop the folder-missing page 2026-10-04 16:17:05 +08:00
yyc12345 157f597eed fix(export): sanitize the suggested file name and harden Markdown escaping 2026-10-04 16:16:01 +08:00
yyc12345 1140cd500b fix(config): never let app.json I/O stop startup and reject numeric enum values 2026-10-04 16:15:01 +08:00
yyc12345 7f277d1630 feat(ui): show an open-failed page and release a workspace that fails to build 2026-10-04 16:14:30 +08:00
yyc12345 647232c447 fix(storage): initialize a workspace under the lock and refuse a missing database 2026-10-04 16:11:51 +08:00
yyc12345 78e5faa3c4 feat(search): tighten the grammar and use Unicode case folding 2026-10-04 16:10:14 +08:00
yyc12345 97f79db3f1 feat(packaging): add macOS bundle metadata, release packaging and application icon 2026-10-04 16:08:06 +08:00
yyc12345 90a7531a27 chore(deps): migrate to net10.0 and update Avalonia, Semi.Avalonia and Microsoft.Data.Sqlite 2026-10-04 16:07:26 +08:00
yyc12345 8b7e50a955 style: expand one-line summaries and run dotnet format solution-wide 2026-10-04 10:22:02 +08:00
yyc12345 9ea551b600 docs: annotate safe delete and truncate operations with SAFETY comments 2026-10-04 10:11:48 +08:00
yyc12345 8a7c6fe8d6 refactor: keep the workspace lock file empty 2026-10-04 09:58:09 +08:00
yyc12345 d8a4dd6190 docs: add usage, acceptance checklist and build workflow 2026-10-04 09:52:09 +08:00
yyc12345 0fdd94d109 feat: add tag manager, search filtering and export 2026-10-04 09:43:25 +08:00
yyc12345 830f1153fd feat: add board interface with cards, columns and dialogs 2026-10-03 21:18:54 +08:00
163 changed files with 5247 additions and 6352 deletions

No files matched your search

+1 -1
View File
@@ -18,7 +18,7 @@ indent_size = 4
tab_width = 4 tab_width = 4
# New line preferences # New line preferences
insert_final_newline = false insert_final_newline = true
#### .NET Coding Conventions #### #### .NET Coding Conventions ####
[*.{cs,vb}] [*.{cs,vb}]
+9 -7
View File
@@ -1,6 +1,10 @@
# Manual-only release build (PLAN §7.2): no push or pull_request trigger. # Manual-only release build (PLAN §7.2): no push or pull_request trigger.
# Each RID job runs build -> test -> publish/pack -> upload; a failing step # Each RID job runs build -> test -> publish/pack -> upload; a failing step
# skips the rest of that job, so a RID whose tests fail produces no artifact. # skips the rest of that job, so a RID whose tests fail produces no artifact.
# win-x64 packs an Inno Setup installer; linux-x64 a tar.gz; osx-arm64 a
# drag-to-Applications dmg.
# Artifacts are uploaded unzipped (upload-artifact archive: false): each RID's
# dist/ holds exactly one file, and its name becomes the artifact name.
# No GitHub Release is created. # No GitHub Release is created.
name: Build name: Build
@@ -27,10 +31,8 @@ jobs:
os: windows-latest os: windows-latest
- rid: linux-x64 - rid: linux-x64
os: ubuntu-latest os: ubuntu-latest
- rid: osx-x64
os: macos-15-intel
- rid: osx-arm64 - rid: osx-arm64
os: macos-15 os: macos-latest
defaults: defaults:
run: run:
shell: bash shell: bash
@@ -55,15 +57,15 @@ jobs:
--self-contained -o publish/${{ matrix.rid }} --self-contained -o publish/${{ matrix.rid }}
- name: Pack - name: Pack
id: pack
run: | run: |
version="$(dotnet msbuild YKanBan/YKanBan.csproj -getProperty:Version)" version="$(dotnet msbuild YKanBan/YKanBan.csproj -getProperty:Version)"
bash packaging/package.sh ${{ matrix.rid }} publish/${{ matrix.rid }} dist "$version" bash packaging/package.sh ${{ matrix.rid }} publish/${{ matrix.rid }} dist "$version"
echo "name=YKanBan-$version-${{ matrix.rid }}" >> "$GITHUB_OUTPUT"
- name: Upload artifact - name: Upload artifact
uses: actions/upload-artifact@v4 uses: actions/upload-artifact@v7
with: with:
name: ${{ steps.pack.outputs.name }} # archive: false uploads the single matched file as-is (no zip
# wrapper); the file name doubles as the artifact name.
path: dist/* path: dist/*
archive: false
if-no-files-found: error if-no-files-found: error
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 yyc12345
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+13 -16
View File
@@ -1,31 +1,28 @@
# YKanBan # YKanBan
My personal used local/offline kanban. A personal, local/offline kanban board. Cross-platform desktop app built with Avalonia UI and MVVM. Each workspace stores its data in a `.ykanban` folder at the project root, Git-style; start it with `ykanban <path>`.
- Cross-platform desktop app (Windows / Linux / macOS) built with Avalonia. - One board per workspace, with columns, cards and colored tags.
- Git-like storage: the board lives in a `.ykanban` folder inside the project - Strict search expressions, for example `tag:bug OR title:login`.
folder it manages; start it with `ykanban <path>`. - Markdown export of the whole board, and a tag manager.
- One board per workspace with columns, cards and colored tags; strict search - Multi-language interface; light, dark or system theme.
expressions (`tag:bug OR title:login`); Markdown export.
- English and Simplified Chinese interface; light, dark or system theme.
See **[USAGE.md](USAGE.md)** for installing, starting YKanBan, backups and See [USAGE.md](USAGE.md) for installing, starting YKanBan, workspaces and backups, the search syntax and the settings file.
Git, and the full search syntax.
## Building ## Building
Requires the .NET 10 SDK. Requires the .NET 10 SDK.
```sh ```
dotnet build dotnet build YKanBan.slnx
dotnet test dotnet test YKanBan.slnx
dotnet run --project YKanBan -- <path> dotnet run --project YKanBan -- <path>
``` ```
Release archives for win-x64, linux-x64, osx-x64 and osx-arm64 are produced Packages are pinned in `YKanBan/YKanBan.csproj`.
by the manually triggered workflow in `.github/workflows/build.yml`;
`packaging/package.sh` packs one published RID. Release archives for win-x64, linux-x64 and osx-arm64 are produced by the manually triggered workflow in `.github/workflows/build.yml`; `packaging/package.sh` packs one published RID.
## License ## License
MIT MIT — see [LICENSE](LICENSE).
+59 -111
View File
@@ -1,30 +1,20 @@
# YKanBan usage # YKanBan Usage
YKanBan is a local, offline kanban board. Like Git, it keeps its data in a YKanBan is a local, offline kanban board. Like Git, it keeps its data in a `.ykanban` folder inside the project folder it manages (the **workspace**). Each YKanBan window manages exactly one workspace; several windows can run at the same time on different workspaces.
`.ykanban` folder inside the project folder it manages (the **workspace**).
Each YKanBan window manages exactly one workspace; several windows can run at
the same time on different workspaces.
- [Installing](#installing)
- [Starting YKanBan](#starting-ykanban)
- [macOS](#macos)
- [Workspaces, Git and backups](#workspaces-git-and-backups)
- [Search syntax](#search-syntax)
- [Settings file](#settings-file)
## Installing ## Installing
Each release build is a self-contained archive; no .NET runtime is needed. Each release build is self-contained; no .NET runtime is needed.
| Platform | Archive | Executable | | Platform | Package | Executable |
|---|---|---| |---|---|---|
| Windows x64 | `YKanBan-<version>-win-x64.zip` | `YKanBan.exe` | | Windows x64 | `YKanBan-<version>-win-x64-setup.exe` | `YKanBan.exe` |
| Linux x64 | `YKanBan-<version>-linux-x64.tar.gz` | `YKanBan` | | Linux x64 | `YKanBan-<version>-linux-x64.tar.gz` | `YKanBan` |
| macOS Intel | `YKanBan-<version>-osx-x64.tar.gz` | `YKanBan.app` (see [macOS](#macos)) | | macOS Apple silicon | `YKanBan-<version>-osx-arm64.dmg` | `YKanBan.app` (see [macOS](#macos)) |
| macOS Apple silicon | `YKanBan-<version>-osx-arm64.tar.gz` | `YKanBan.app` (see [macOS](#macos)) |
Extract the archive anywhere. To type `ykanban <path>` as shown below, put the Only Apple silicon macOS is a release target; there is no Intel Mac build.
executable on your `PATH` under that name, for example:
On Windows, run the installer. On Linux, extract the archive anywhere. On macOS, open the disk image and drag `YKanBan.app` into `Applications` (or any other folder). To type `ykanban <path>` as shown below, put the executable on your `PATH` under that name, for example:
```sh ```sh
# Linux # Linux
@@ -33,8 +23,7 @@ ln -s /opt/YKanBan-<version>-linux-x64/YKanBan ~/.local/bin/ykanban
ln -s /Applications/YKanBan.app/Contents/MacOS/YKanBan /usr/local/bin/ykanban ln -s /Applications/YKanBan.app/Contents/MacOS/YKanBan /usr/local/bin/ykanban
``` ```
On Windows, add the extracted folder to `PATH`; `ykanban` then finds On Windows, add the installed folder to `PATH` (the default is `C:\Program Files\YKanBan`); `ykanban` then finds `YKanBan.exe` because Windows ignores case.
`YKanBan.exe` because Windows ignores case.
## Starting YKanBan ## Starting YKanBan
@@ -44,84 +33,60 @@ The only way to start YKanBan is with the workspace path:
ykanban <path> ykanban <path>
``` ```
- Exactly one argument is accepted. A relative path is resolved against the - Exactly one argument is accepted. A relative path is resolved against the current working directory, so `ykanban .` opens the current folder (but see [macOS](#macos) when starting through `open`).
current working directory, so `ykanban .` opens the current folder. - YKanBan looks for `.ykanban` **only in `<path>` itself**; it does not search parent folders the way Git does.
- YKanBan looks for `.ykanban` **only in `<path>` itself**; it does not search - There are no command-line options. An argument starting with `-` is never treated as a path; to open a folder whose name starts with `-`, write it as `./-name`.
parent folders the way Git does.
- There are no command-line options. An argument starting with `-` is never
treated as a path; to open a folder whose name starts with `-`, write it as
`./-name`.
When the board cannot be shown, the whole window shows one of these pages The path must exist and be a folder. When the board cannot be shown, the whole window shows one of these pages instead:
instead:
| Page | When | | Page | When |
|---|---| |---|---|
| Invalid arguments | No argument, more than one argument, an empty argument, or an argument starting with `-` (including `--help`). Shows the usage line. | | Invalid arguments | No argument, more than one argument, an empty or whitespace-only argument, an argument starting with `-` (including `--help`), a path the operating system cannot represent (for example one containing a NUL character), or a path that does not exist or is not a folder. Shows the usage line. |
| Folder not found | `<path>` does not exist or is not a folder. | | No workspace here | `<path>` exists but has no `.ykanban`. The **Initialize workspace** button creates one, with the columns To Do / In Progress / Done and the preset tags (both named in the current interface language). |
| No workspace here | `<path>` exists but has no `.ykanban`. The **Initialize workspace** button creates one, with the columns To Do / In Progress / Done (named in the current interface language). | | Workspace locked | Another YKanBan window already has this workspace open. Close that window first. Also shown when another window takes the lock while you initialize. |
| Workspace locked | Another YKanBan window already has this workspace open. Close that window first. | | Cannot open workspace | `.ykanban` exists but `ykanban.db` in it is missing (restore it from a backup, or delete `.ykanban` and initialize again; YKanBan never silently creates an empty board), the database was created by a newer YKanBan, is damaged or cannot be opened, or a file-system or permission error occurred (also when initializing fails for a reason other than the lock). The English error details can be selected and copied. |
| Cannot open workspace | The database was created by a newer YKanBan, is damaged or cannot be opened, or a file-system or permission error occurred (also when initializing fails). The English error details can be selected and copied. |
The window title is `<workspace name> - YKanBan` while a workspace is open and The window title is `<workspace name> - YKanBan` while a workspace is open and just `YKanBan` on these pages.
just `YKanBan` on these pages.
## macOS ## macOS
The app is not notarized. After extracting, remove the download quarantine The app is not notarized. After dragging it out of the disk image, remove the download quarantine once, or macOS refuses to open it:
once, or macOS refuses to open it:
```sh ```sh
xattr -dr com.apple.quarantine YKanBan.app xattr -dr com.apple.quarantine YKanBan.app
``` ```
Double-clicking `YKanBan.app` starts it without a path, so it only shows the Double-clicking `YKanBan.app` starts it without a path, so it only shows the **Invalid arguments** page. Start it from a terminal instead, either through Launch Services or by running the executable inside the bundle:
**Invalid arguments** page. Start it from a terminal instead, either through
Launch Services or by running the executable inside the bundle:
```sh ```sh
open -a YKanBan --args /path/to/project open -n -a YKanBan --args /path/to/project
/Applications/YKanBan.app/Contents/MacOS/YKanBan /path/to/project /Applications/YKanBan.app/Contents/MacOS/YKanBan /path/to/project
``` ```
`open -a YKanBan` finds the app once it is in `/Applications` (or another - Keep `-n`: without it, `open` only brings an already running YKanBan to the front and drops the path, instead of starting another window.
folder Launch Services knows about). - Give `open` an **absolute** path. An app started by `open` runs in `/`, so `open -n -a YKanBan --args .` opens `/`, not the current folder. Running the executable inside the bundle resolves relative paths normally.
- `open -a YKanBan` finds the app once it is in `/Applications` (or another folder Launch Services knows about).
## Workspaces, Git and backups ## Workspaces, Git and Backups
- **Do not commit `.ykanban` to Git.** Add it to your global ignore file once, - **Do not commit `.ykanban` to Git.** Add it to your global ignore file once, so no repository picks it up. If `git config --global core.excludesFile` prints a file, add the line `.ykanban/` to that file; otherwise create one:
so no repository picks it up. If `git config --global core.excludesFile`
prints a file, add the line `.ykanban/` to that file; otherwise create one:
```sh ```sh
echo ".ykanban/" >> ~/.gitignore_global echo ".ykanban/" >> ~/.gitignore_global
git config --global core.excludesFile ~/.gitignore_global git config --global core.excludesFile ~/.gitignore_global
``` ```
- **Back up or move all three database files together**: `ykanban.db`, - **Back up or move all three database files together**: `ykanban.db`, `ykanban.db-wal` and `ykanban.db-shm` in `.ykanban/`. Recent changes may still be in the `-wal` file; copying only `ykanban.db` can lose them. The simplest safe backup is to close YKanBan and copy the whole `.ykanban` folder.
`ykanban.db-wal` and `ykanban.db-shm` in `.ykanban/`. Recent changes may - **Network shares (SMB, NFS, …) are not supported.** The database and the workspace lock rely on local file-system features that do not work reliably over a network. YKanBan does not detect this; keep workspaces on a local disk.
still be in the `-wal` file; copying only `ykanban.db` can lose them. The - `.ykanban/ykanban.lock` is held while a window has the workspace open and is released automatically when YKanBan exits or crashes. The file itself is kept empty; only the exclusive OS handle it carries has meaning.
simplest safe backup is to close YKanBan and copy the whole `.ykanban`
folder.
- **Network shares (SMB, NFS, …) are not supported.** The database and the
workspace lock rely on local file-system features that do not work reliably
over a network. YKanBan does not detect this; keep workspaces on a local
disk.
- `.ykanban/ykanban.lock` is held while a window has the workspace open and is
released automatically when YKanBan exits or crashes.
## Search syntax ## Search Syntax
Type an expression in the search box on the **Board** tab and click Type an expression in the search box on the **Board** tab and click **Search** (or press Enter). Searching only happens then; there is no search while typing. The **×** button clears the box and shows every card again.
**Search** (or press Enter). Searching only happens then; there is no search
while typing. The **×** button clears the box and shows every card again.
- Columns are always shown, even when none of their cards match. - Columns are always shown, even when none of their cards match.
- An empty or blank expression shows every card. - An empty or blank expression shows every card.
- After any change (adding, editing, moving or deleting cards, columns or - An active search keeps the result set it produced until you search again: after adding, editing, moving or deleting cards the board shows the same matching cards as before, minus any that were deleted. Adding or editing a card does not change whether it is currently shown; press **Search** again to refresh the result.
tags), the board re-runs the **last expression that searched successfully**,
not whatever is in the box at that moment. Cards that stop matching
disappear; new cards that do not match are not shown.
### Examples ### Examples
@@ -153,23 +118,18 @@ value := word | phrase -- tag / title / content / column
| '#'? digit+ -- id: a positive decimal integer | '#'? digit+ -- id: a positive decimal integer
word := one or more characters, except whitespace and ( ) " : \ ; word := one or more characters, except whitespace and ( ) " : \ ;
not equal to AND or OR not equal to AND or OR
phrase := '"' any text '"' -- escapes: \" and \\ phrase := '"' one or more characters '"' -- escapes: \" and \\
``` ```
### Operators ### Operators
- `AND` and `OR` are operators **only in uppercase**. `and` and `or` are - `AND` and `OR` are operators **only in uppercase**. `and` and `or` are ordinary words.
ordinary words.
- Writing words next to each other means `AND`: `a b` is `a AND b`. - Writing words next to each other means `AND`: `a b` is `a AND b`.
- `AND` binds tighter than `OR`: `a OR b c` is `a OR (b AND c)`. Use - `AND` binds tighter than `OR`: `a OR b c` is `a OR (b AND c)`. Use parentheses to group differently: `(a OR b) c`.
parentheses to group differently: `(a OR b) c`. - To search for the literal text `AND` or `OR`, quote it: `"AND"`, `tag:"OR"`.
- To search for the literal text `AND` or `OR`, quote it: `"AND"`, - The search keywords (`AND`, `OR`, `tag`, `title`, `content`, `id`, `column`) are always English, whatever the interface language. Qualifier keys are lowercase only: `Tag:bug` is an unknown qualifier.
`tag:"OR"`.
- The search keywords (`AND`, `OR`, `tag`, `title`, `content`, `id`,
`column`) are always English, whatever the interface language. Qualifier
keys are lowercase only: `Tag:bug` is an unknown qualifier.
### What each atom matches ### What Each Atom Matches
| Atom | Matches when | | Atom | Matches when |
|---|---| |---|---|
@@ -180,35 +140,25 @@ phrase := '"' any text '"' -- escapes: \" and \\
| `column:` value | the card is in a column whose title **equals** the text | | `column:` value | the card is in a column whose title **equals** the text |
| `id:` value | the card number equals the value | | `id:` value | the card number equals the value |
- A qualifier value can be a word (`tag:bug`) or a phrase - A qualifier value can be a word (`tag:bug`) or a phrase (`tag:"needs review"`). Use a phrase for values containing spaces, `(`, `)`, `:` or `\`, and for the values `AND` / `OR`.
(`tag:"needs review"`). Use a phrase for values containing spaces, `(`, - `id:` takes an unquoted positive integer, optionally prefixed with `#`: `id:61`, `id:#61`.
`)`, `:` or `\`, and for the values `AND` / `OR`.
- `id:` takes an unquoted positive integer, optionally prefixed with `#`:
`id:61`, `id:#61`.
### Quoting and escapes ### Quoting and Escapes
- A phrase is text in double quotes. Inside it, `\"` stands for a quote and - A phrase is text in double quotes. Inside it, `\"` stands for a quote and `\\` for a backslash; any other backslash is an error.
`\\` for a backslash; any other backslash is an error. - Outside quotes, `\` is not allowed at all, and `:` always starts a qualifier. Quote any text containing them: `"C:\\temp"`, `"a:b"`.
- Outside quotes, `\` is not allowed at all, and `:` always starts a - A phrase cannot be empty, and must be separated from neighbouring words and phrases by a space or a parenthesis: write `a "b"`, not `a"b"`.
qualifier. Quote any text containing them: `"C:\\temp"`, `"a:b"`. - A qualifier's phrase value follows the `:` directly: `tag:"needs review"`, not `tag: "needs review"`.
### Case ### Case
All matching ignores case, for letters of every language: `tag:BUG` finds All matching ignores case, for letters of every language: `tag:BUG` finds `bug`, and `ÄRGER` finds `ärger`. Text is otherwise compared literally: `%`, `_` and `*` have no special meaning.
`bug`, and `ÄRGER` finds `ärger`. Text is otherwise compared literally: `%`,
`_` and `*` have no special meaning.
Tag names and column titles must be unique ignoring case for the letters A–Z Tag names and column titles must each be unique, but the uniqueness check is case-sensitive: `Bug` and `bug` are different names and can both exist. Because matching folds case, a query such as `tag:bug` then matches both.
only. Two tags such as `Ä` and `ä` can therefore both exist, and `tag:ä`
matches both.
### Invalid expressions ### Invalid Expressions
An invalid expression does not search. A dialog shows "The query expression is An invalid expression does not search. A dialog shows "The query expression is invalid. Details: …" followed by the parser's message (always in English). After closing it, the box keeps your text for correcting and the board keeps the previous result.
invalid. Details: …" followed by the parser's message (always in English).
After closing it, the box keeps your text for correcting and the board keeps
the previous result.
These are invalid: These are invalid:
@@ -220,27 +170,25 @@ These are invalid:
| A qualifier without a value | `tag:` | | A qualifier without a value | `tag:` |
| `AND` / `OR` as an unquoted qualifier value | `tag:AND` (write `tag:"AND"`) | | `AND` / `OR` as an unquoted qualifier value | `tag:AND` (write `tag:"AND"`) |
| An unterminated phrase | `"dark mode` | | An unterminated phrase | `"dark mode` |
| An empty phrase | `""`, `tag:""` |
| A phrase touching other text | `a"b"`, `"a"b`, `"a""b"` |
| A space between a qualifier and its phrase value | `tag: "needs review"` |
| An invalid escape in a phrase | `tag:"a\x"` | | An invalid escape in a phrase | `tag:"a\x"` |
| A backslash outside a phrase | `C:\temp` | | A backslash outside a phrase | `C:\temp` |
| An unknown qualifier key | `label:bug`, `Tag:bug`, `http://x` | | An unknown qualifier key | `label:bug`, `Tag:bug`, `http://x` |
| An unquoted value containing `:` | `title:a:b` | | An unquoted value containing `:` | `title:a:b` |
| An `id:` value that is not an unquoted positive integer | `id:abc`, `id:0`, `id:"61"` | | An `id:` value that is not an unquoted positive integer | `id:abc`, `id:0`, `id:"61"` |
## Settings file ## Settings File
Settings (language, theme, card sort order, column width and the confirmation Settings (language, theme, card sort order, column width and the confirmation switches) are stored in `app.json`:
switches) are stored in `app.json`:
| Platform | Location | | Platform | Location |
|---|---| |---|---|
| Windows | `%APPDATA%\YKanBan\app.json` | | Windows | `%APPDATA%\YKanBan\app.json` |
| Linux, macOS | `~/.config/YKanBan/app.json` (`$XDG_CONFIG_HOME/YKanBan/app.json` when that is set) | | Linux, macOS | `~/.config/YKanBan/app.json` (`$XDG_CONFIG_HOME/YKanBan/app.json` when that is set) |
- The file is written when YKanBan exits, and only if a setting was changed in - The file is written when YKanBan exits. With several instances running, the last one to exit overwrites the file with its own settings.
that session. With several windows open, the last one closed after changing - A language change takes effect after restarting YKanBan; a theme change applies as soon as the settings dialog is accepted.
a setting wins. - A missing file is normal on first run and yields the defaults. If the file exists but cannot be read (an I/O or permission error), the defaults are used.
- A language change takes effect after restarting YKanBan; a theme change - If the file cannot be parsed, it is saved as `app.json.bak` and the defaults are used. This also covers an invalid enum value: an unknown theme, sort or width string, or a numeric enum value, makes the whole file fall back to defaults. A section that is simply missing falls back to its own defaults.
applies immediately.
- If the file cannot be parsed, it is saved as `app.json.bak` and the defaults
are used. A single invalid value falls back to its default; the other
values are kept.
@@ -10,8 +10,7 @@ namespace YKanBan.Tests.Conventions;
/// must be written as <c>YKanBan.Resources</c> (or through a using alias). /// must be written as <c>YKanBan.Resources</c> (or through a using alias).
/// </summary> /// </summary>
[TestClass] [TestClass]
public partial class CodeBehindConventionTests public partial class CodeBehindConventionTests {
{
/// <summary>A <c>Resources.</c> member access not preceded by a qualifier or identifier character.</summary> /// <summary>A <c>Resources.</c> member access not preceded by a qualifier or identifier character.</summary>
[GeneratedRegex(@"(?<![\w.])Resources\.")] [GeneratedRegex(@"(?<![\w.])Resources\.")]
private static partial Regex BareResourcesAccess(); private static partial Regex BareResourcesAccess();
@@ -21,11 +20,9 @@ public partial class CodeBehindConventionTests
/// </summary> /// </summary>
/// <param name="thisFile">Filled in by the compiler.</param> /// <param name="thisFile">Filled in by the compiler.</param>
/// <returns>The YKanBan project folder.</returns> /// <returns>The YKanBan project folder.</returns>
private static string ApplicationSourceFolder([CallerFilePath] string thisFile = "") private static string ApplicationSourceFolder([CallerFilePath] string thisFile = "") {
{
DirectoryInfo? directory = new FileInfo(thisFile).Directory; DirectoryInfo? directory = new FileInfo(thisFile).Directory;
while (directory is not null && !File.Exists(Path.Combine(directory.FullName, "YKanBan", "YKanBan.csproj"))) while (directory is not null && !File.Exists(Path.Combine(directory.FullName, "YKanBan", "YKanBan.csproj"))) {
{
directory = directory.Parent; directory = directory.Parent;
} }
@@ -34,8 +31,7 @@ public partial class CodeBehindConventionTests
} }
[TestMethod] [TestMethod]
public void CodeBehindNeverUsesBareResourcesClassName() public void CodeBehindNeverUsesBareResourcesClassName() {
{
string root = ApplicationSourceFolder(); string root = ApplicationSourceFolder();
string[] files = Directory.GetFiles(root, "*.axaml.cs", SearchOption.AllDirectories) string[] files = Directory.GetFiles(root, "*.axaml.cs", SearchOption.AllDirectories)
.Where(path => !path.Split(Path.DirectorySeparatorChar).Any(part => part is "obj" or "bin")) .Where(path => !path.Split(Path.DirectorySeparatorChar).Any(part => part is "obj" or "bin"))
@@ -43,13 +39,10 @@ public partial class CodeBehindConventionTests
Assert.IsTrue(files.Length > 0, "No code-behind files found."); Assert.IsTrue(files.Length > 0, "No code-behind files found.");
var offenders = new List<string>(); var offenders = new List<string>();
foreach (string file in files) foreach (string file in files) {
{
string[] lines = File.ReadAllLines(file); string[] lines = File.ReadAllLines(file);
for (int index = 0; index < lines.Length; index++) for (int index = 0; index < lines.Length; index++) {
{ if (BareResourcesAccess().IsMatch(lines[index])) {
if (BareResourcesAccess().IsMatch(lines[index]))
{
offenders.Add($"{Path.GetRelativePath(root, file)}:{index + 1}: {lines[index].Trim()}"); offenders.Add($"{Path.GetRelativePath(root, file)}:{index + 1}: {lines[index].Trim()}");
} }
} }
+50 -120
View File
@@ -1,5 +1,6 @@
using System.Globalization; using System.Globalization;
using System.Text; using System.Text;
using YKanBan.Export; using YKanBan.Export;
using YKanBan.Models; using YKanBan.Models;
@@ -14,8 +15,7 @@ namespace YKanBan.Tests.Export;
/// </summary> /// </summary>
[TestClass] [TestClass]
[DoNotParallelize] [DoNotParallelize]
public class MarkdownExporterTests public class MarkdownExporterTests {
{
private static readonly DateTimeOffset ExportedAt = new(2026, 9, 30, 14, 25, 37, TimeSpan.Zero); private static readonly DateTimeOffset ExportedAt = new(2026, 9, 30, 14, 25, 37, TimeSpan.Zero);
/// <summary> /// <summary>
@@ -46,8 +46,7 @@ public class MarkdownExporterTests
/// Builds the board fixture: one working column with two cards, one empty column and two tags. /// Builds the board fixture: one working column with two cards, one empty column and two tags.
/// </summary> /// </summary>
/// <returns>The columns, cards and tag/usage tuples.</returns> /// <returns>The columns, cards and tag/usage tuples.</returns>
private static (IReadOnlyList<ColumnModel> Columns, IReadOnlyList<CardModel> Cards, IReadOnlyList<(TagModel, long)> Tags) CreateBoard() private static (IReadOnlyList<ColumnModel> Columns, IReadOnlyList<CardModel> Cards, IReadOnlyList<(TagModel, long)> Tags) CreateBoard() {
{
long created = UnixTimeOf(2026, 9, 1, 10, 0); long created = UnixTimeOf(2026, 9, 1, 10, 0);
long updated = UnixTimeOf(2026, 9, 28, 18, 30); long updated = UnixTimeOf(2026, 9, 28, 18, 30);
@@ -71,8 +70,7 @@ public class MarkdownExporterTests
/// Renders the fixture board with the exporter under the current culture. /// Renders the fixture board with the exporter under the current culture.
/// </summary> /// </summary>
/// <returns>The produced Markdown document.</returns> /// <returns>The produced Markdown document.</returns>
private static string ExportBoard() private static string ExportBoard() {
{
(IReadOnlyList<ColumnModel> columns, IReadOnlyList<CardModel> cards, IReadOnlyList<(TagModel, long)> tags) = CreateBoard(); (IReadOnlyList<ColumnModel> columns, IReadOnlyList<CardModel> cards, IReadOnlyList<(TagModel, long)> tags) = CreateBoard();
return MarkdownExporter.Export("MyRepo", columns, cards, tags, ExportedAt); return MarkdownExporter.Export("MyRepo", columns, cards, tags, ExportedAt);
} }
@@ -82,8 +80,7 @@ public class MarkdownExporterTests
/// </summary> /// </summary>
/// <param name="culture">The UI culture.</param> /// <param name="culture">The UI culture.</param>
/// <returns>The expected Markdown document.</returns> /// <returns>The expected Markdown document.</returns>
private static string BuildExpected(CultureInfo culture) private static string BuildExpected(CultureInfo culture) {
{
string created = Local(2026, 9, 1, 10, 0).ToString(Resources.Export_TimePattern, culture); string created = Local(2026, 9, 1, 10, 0).ToString(Resources.Export_TimePattern, culture);
string updated = Local(2026, 9, 28, 18, 30).ToString(Resources.Export_TimePattern, culture); string updated = Local(2026, 9, 28, 18, 30).ToString(Resources.Export_TimePattern, culture);
@@ -133,38 +130,30 @@ public class MarkdownExporterTests
/// Asserts that the exporter output matches the resource-built expected document. /// Asserts that the exporter output matches the resource-built expected document.
/// </summary> /// </summary>
/// <param name="culture">The UI culture to test.</param> /// <param name="culture">The UI culture to test.</param>
private static void AssertOutputMatches(CultureInfo culture) private static void AssertOutputMatches(CultureInfo culture) {
{
CultureInfo? original = Resources.Culture; CultureInfo? original = Resources.Culture;
try try {
{
Resources.Culture = culture; Resources.Culture = culture;
Assert.AreEqual(Normalize(BuildExpected(culture)), Normalize(ExportBoard())); Assert.AreEqual(Normalize(BuildExpected(culture)), Normalize(ExportBoard()));
} } finally {
finally
{
Resources.Culture = original; Resources.Culture = original;
} }
} }
[TestMethod] [TestMethod]
public void EnglishOutputMatchesTemplate() public void EnglishOutputMatchesTemplate() {
{
AssertOutputMatches(new CultureInfo("en")); AssertOutputMatches(new CultureInfo("en"));
} }
[TestMethod] [TestMethod]
public void ChineseOutputMatchesTemplate() public void ChineseOutputMatchesTemplate() {
{
AssertOutputMatches(new CultureInfo("zh-Hans")); AssertOutputMatches(new CultureInfo("zh-Hans"));
} }
[TestMethod] [TestMethod]
public void FileNameFollowsLanguage() public void FileNameFollowsLanguage() {
{
CultureInfo? original = Resources.Culture; CultureInfo? original = Resources.Culture;
try try {
{
Resources.Culture = new CultureInfo("en"); Resources.Culture = new CultureInfo("en");
Assert.AreEqual( Assert.AreEqual(
string.Format(Resources.Culture, Resources.Export_FileNamePattern, "MyRepo", ExportedAt), string.Format(Resources.Culture, Resources.Export_FileNamePattern, "MyRepo", ExportedAt),
@@ -174,19 +163,15 @@ public class MarkdownExporterTests
Assert.AreEqual( Assert.AreEqual(
string.Format(Resources.Culture, Resources.Export_FileNamePattern, "MyRepo", ExportedAt), string.Format(Resources.Culture, Resources.Export_FileNamePattern, "MyRepo", ExportedAt),
MarkdownExporter.BuildFileName("MyRepo", ExportedAt)); MarkdownExporter.BuildFileName("MyRepo", ExportedAt));
} } finally {
finally
{
Resources.Culture = original; Resources.Culture = original;
} }
} }
[TestMethod] [TestMethod]
public void TagTableCellsEscapePipesAndLineBreaks() public void TagTableCellsEscapePipesAndLineBreaks() {
{
CultureInfo? original = Resources.Culture; CultureInfo? original = Resources.Culture;
try try {
{
Resources.Culture = new CultureInfo("en"); Resources.Culture = new CultureInfo("en");
var tag = new TagModel(1, "a|b", RgbColor.Parse("#112233"), "first\nsecond"); var tag = new TagModel(1, "a|b", RgbColor.Parse("#112233"), "first\nsecond");
string markdown = MarkdownExporter.Export( string markdown = MarkdownExporter.Export(
@@ -197,27 +182,36 @@ public class MarkdownExporterTests
ExportedAt); ExportedAt);
StringAssert.Contains(markdown, "| a\\|b | #112233 | first<br>second | 0 |"); StringAssert.Contains(markdown, "| a\\|b | #112233 | first<br>second | 0 |");
} } finally {
finally
{
Resources.Culture = original; Resources.Culture = original;
} }
} }
[TestMethod] [TestMethod]
[DataRow("plain", "`plain`")] public void TagTableCellsEscapeBackslashes() {
[DataRow("a`b", "``a`b``")]
[DataRow("a``b`c", "```a``b`c```")]
[DataRow("`x", "`` `x ``")]
[DataRow("x`", "`` x` ``")]
[DataRow("`", "`` ` ``")]
public void TagNamesUseLongEnoughBacktickFence(string name, string expected)
{
CultureInfo? original = Resources.Culture; CultureInfo? original = Resources.Culture;
try try {
{
Resources.Culture = new CultureInfo("en"); Resources.Culture = new CultureInfo("en");
var tag = new TagModel(1, name, RgbColor.Parse("#112233"), string.Empty); var tag = new TagModel(1, "a\\b", RgbColor.Parse("#112233"), "c\\|d");
string markdown = MarkdownExporter.Export(
"W",
[new ColumnModel(1, "C", string.Empty, 1, 1)],
[],
[(tag, 0L)],
ExportedAt);
StringAssert.Contains(markdown, "| a\\\\b | #112233 | c\\\\\\|d | 0 |");
} finally {
Resources.Culture = original;
}
}
[TestMethod]
public void TagNameWithBacktickUsesLongerFence() {
CultureInfo? original = Resources.Culture;
try {
Resources.Culture = new CultureInfo("en");
var tag = new TagModel(1, "a`b", RgbColor.Parse("#112233"), string.Empty);
string markdown = MarkdownExporter.Export( string markdown = MarkdownExporter.Export(
"W", "W",
[new ColumnModel(1, "C", string.Empty, 1, 1)], [new ColumnModel(1, "C", string.Empty, 1, 1)],
@@ -225,91 +219,27 @@ public class MarkdownExporterTests
[(tag, 1L)], [(tag, 1L)],
ExportedAt); ExportedAt);
StringAssert.Contains(markdown, string.Format(Resources.Culture, Resources.Export_TagsLine, expected) + Environment.NewLine); StringAssert.Contains(markdown, "``a`b``");
} } finally {
finally
{
Resources.Culture = original; Resources.Culture = original;
} }
} }
[TestMethod] [TestMethod]
public void CardBodyAndColumnDescriptionAreVerbatim() public void FileNameDropsInvalidCharactersAndFallsBackToAppName() {
{
CultureInfo? original = Resources.Culture; CultureInfo? original = Resources.Culture;
try try {
{
Resources.Culture = new CultureInfo("en"); Resources.Culture = new CultureInfo("en");
string markdown = Normalize(MarkdownExporter.Export(
"W",
[new ColumnModel(1, "C", "line one\n# not a heading | pipe", 1, 1)],
[new CardModel(1, 1, "T", "body\n\n## raw | `md`", 1, 1, [])],
[],
ExportedAt));
StringAssert.Contains(markdown, "\nline one\n# not a heading | pipe\n"); // A drive root workspace name "D:\" must not leak ':' or '\' into the file name.
StringAssert.Contains(markdown, "\nbody\n\n## raw | `md`\n"); string name = MarkdownExporter.BuildFileName("D:\\", ExportedAt);
} Assert.IsFalse(name.Contains(':'));
finally Assert.IsFalse(name.Contains('\\'));
{
Resources.Culture = original;
}
}
[TestMethod] // A name made only of invalid characters falls back to the application name.
public void ColumnsAndCardsAreExportedInIdOrder() string fallback = MarkdownExporter.BuildFileName("///", ExportedAt);
{ StringAssert.StartsWith(fallback, Resources.App_Name);
CultureInfo? original = Resources.Culture; } finally {
try
{
Resources.Culture = new CultureInfo("en");
string markdown = MarkdownExporter.Export(
"W",
[new ColumnModel(2, "Second", string.Empty, 1, 1), new ColumnModel(1, "First", string.Empty, 1, 1)],
[
new CardModel(9, 1, "Nine", string.Empty, 1, 1, []),
new CardModel(3, 2, "Three", string.Empty, 1, 1, []),
new CardModel(4, 1, "Four", string.Empty, 1, 1, []),
],
[],
ExportedAt);
int first = markdown.IndexOf(string.Format(Resources.Culture, Resources.Export_ColumnHeading, "First", 2), StringComparison.Ordinal);
int second = markdown.IndexOf(string.Format(Resources.Culture, Resources.Export_ColumnHeading, "Second", 1), StringComparison.Ordinal);
int four = markdown.IndexOf("### #4 Four", StringComparison.Ordinal);
int nine = markdown.IndexOf("### #9 Nine", StringComparison.Ordinal);
int three = markdown.IndexOf("### #3 Three", StringComparison.Ordinal);
Assert.IsTrue(first >= 0 && first < four && four < nine && nine < second && second < three, markdown);
}
finally
{
Resources.Culture = original;
}
}
[TestMethod]
[DataRow("en", "2026-09-30 14:25:37", "2026-09-01 10:00:05")]
[DataRow("zh-Hans", "2026年9月30日 14:25", "2026年9月1日 10:00")]
public void TimestampsUseThePlannedPerLanguageFormat(string language, string exportedAt, string cardTime)
{
CultureInfo? original = Resources.Culture;
try
{
Resources.Culture = new CultureInfo(language);
long cardSeconds = new DateTimeOffset(new DateTime(2026, 9, 1, 10, 0, 5)).ToUnixTimeSeconds();
var exportMoment = new DateTimeOffset(new DateTime(2026, 9, 30, 14, 25, 37));
string markdown = MarkdownExporter.Export(
"W",
[new ColumnModel(1, "C", string.Empty, 1, 1)],
[new CardModel(1, 1, "T", string.Empty, cardSeconds, cardSeconds, [])],
[],
exportMoment);
StringAssert.Contains(markdown, string.Format(Resources.Culture, Resources.Export_ExportedAtLine, exportedAt));
StringAssert.Contains(markdown, string.Format(Resources.Culture, Resources.Export_CreatedModifiedLine, cardTime, cardTime));
}
finally
{
Resources.Culture = original; Resources.Culture = original;
} }
} }
+49 -40
View File
@@ -1,76 +1,85 @@
using YKanBan.Launching; using YKanBan.Launching;
using YKanBan.Tests.TestUtilities;
namespace YKanBan.Tests.Launching; namespace YKanBan.Tests.Launching;
/// <summary> /// <summary>
/// Tests for the <c>ykanban &lt;path&gt;</c> command-line contract across its /// Tests for the <c>ykanban &lt;path&gt;</c> command-line contract: exactly one
/// three branches: no argument, one valid path, and invalid input. /// existing folder, resolved to an absolute path; everything else is rejected.
/// </summary> /// </summary>
[TestClass] [TestClass]
public class LaunchArgumentsTests public class LaunchArgumentsTests {
{
[TestMethod] [TestMethod]
public void NoArgumentsIsRejected() public void NoArgumentsIsRejected() {
{
Assert.IsFalse(LaunchArguments.TryParse([], out string? path)); Assert.IsFalse(LaunchArguments.TryParse([], out string? path));
Assert.IsNull(path); Assert.IsNull(path);
} }
[TestMethod] [TestMethod]
public void BlankArgumentIsRejected() public void BlankArgumentIsRejected() {
{
Assert.IsFalse(LaunchArguments.TryParse([" "], out string? path)); Assert.IsFalse(LaunchArguments.TryParse([" "], out string? path));
Assert.IsNull(path); Assert.IsNull(path);
} }
[TestMethod] [TestMethod]
public void MoreThanOneArgumentIsRejected() public void MoreThanOneArgumentIsRejected() {
{
Assert.IsFalse(LaunchArguments.TryParse(["a", "b"], out string? path)); Assert.IsFalse(LaunchArguments.TryParse(["a", "b"], out string? path));
Assert.IsNull(path); Assert.IsNull(path);
} }
[TestMethod] [TestMethod]
public void SingleAbsolutePathIsAccepted()
{
string absolute = Path.Combine(Path.GetTempPath(), "Repo", "MyProject");
bool parsed = LaunchArguments.TryParse([absolute], out string? path);
Assert.IsTrue(parsed);
Assert.AreEqual(absolute, path);
}
[TestMethod]
public void RelativePathResolvesAgainstCurrentDirectory()
{
Assert.IsTrue(LaunchArguments.TryParse(["MyProject"], out string? path));
Assert.AreEqual(Path.Combine(Environment.CurrentDirectory, "MyProject"), path);
Assert.IsTrue(LaunchArguments.TryParse(["."], out path));
Assert.AreEqual(Path.GetFullPath(Environment.CurrentDirectory), path);
}
[TestMethod]
[DataRow("-")]
[DataRow("-x")]
[DataRow("--help")] [DataRow("--help")]
[DataRow("--path=foo")] [DataRow("-x")]
public void OptionLikeArgumentIsRejected(string argument) public void OptionLikeArgumentIsRejected(string argument) {
{
Assert.IsFalse(LaunchArguments.TryParse([argument], out string? path)); Assert.IsFalse(LaunchArguments.TryParse([argument], out string? path));
Assert.IsNull(path); Assert.IsNull(path);
} }
[TestMethod] [TestMethod]
public void OptionAlongsidePathIsRejected() public void NonExistentFolderIsRejected() {
{ using var directory = new TempDirectory();
Assert.IsFalse(LaunchArguments.TryParse(["--help", "MyProject"], out string? path)); string missing = Path.Combine(directory.FullPath, "nope");
Assert.IsFalse(LaunchArguments.TryParse([missing], out string? path));
Assert.IsNull(path); Assert.IsNull(path);
} }
[TestMethod] [TestMethod]
public void MalformedPathIsRejected() public void FileInsteadOfFolderIsRejected() {
{ using var directory = new TempDirectory();
Assert.IsFalse(LaunchArguments.TryParse(["a\0b"], out string? path)); string file = Path.Combine(directory.FullPath, "file.txt");
File.WriteAllText(file, "x");
Assert.IsFalse(LaunchArguments.TryParse([file], out string? path));
Assert.IsNull(path);
}
[TestMethod]
public void ExistingFolderIsAcceptedAsAnAbsolutePath() {
using var directory = new TempDirectory();
bool parsed = LaunchArguments.TryParse([directory.FullPath], out string? path);
Assert.IsTrue(parsed);
Assert.AreEqual(Path.GetFullPath(directory.FullPath), path);
Assert.IsTrue(Path.IsPathRooted(path));
}
[TestMethod]
public void RelativePathIsResolvedToAbsolute() {
using var directory = new TempDirectory();
string relative = Path.GetRelativePath(Environment.CurrentDirectory, directory.FullPath);
bool parsed = LaunchArguments.TryParse([relative], out string? path);
Assert.IsTrue(parsed);
Assert.IsTrue(Path.IsPathRooted(path));
Assert.AreEqual(Path.GetFullPath(relative), path);
}
[TestMethod]
public void MalformedPathIsRejected() {
Assert.IsFalse(LaunchArguments.TryParse(["bad\0path"], out string? path));
Assert.IsNull(path); Assert.IsNull(path);
} }
} }
-46
View File
@@ -1,46 +0,0 @@
using YKanBan.Models;
using YKanBan.Storage.AppData;
namespace YKanBan.Tests.Models;
/// <summary>
/// Tests for the in-column card display order: each sort option plus the id
/// ascending tie-breaker.
/// </summary>
[TestClass]
public class CardOrderingTests
{
private static CardModel Card(long id, string title = "", long updatedAt = 0) =>
new(id, 1, title, string.Empty, 0, updatedAt, []);
private static long[] Ids(IEnumerable<CardModel> cards, CardSortOption option) =>
CardOrdering.Sort(cards, option).Select(card => card.Id).ToArray();
[TestMethod]
public void IdSortsAscending()
{
CollectionAssert.AreEqual(new[] { 1L, 2L, 3L }, Ids([Card(3), Card(1), Card(2)], CardSortOption.Id));
}
[TestMethod]
public void UpdatedAtSortsMostRecentFirstThenById()
{
CardModel[] cards = [Card(1, updatedAt: 10), Card(2, updatedAt: 30), Card(3, updatedAt: 10), Card(4, updatedAt: 20)];
CollectionAssert.AreEqual(new[] { 2L, 4L, 1L, 3L }, Ids(cards, CardSortOption.UpdatedAt));
}
[TestMethod]
public void TitleSortsByCodePointWithEmptyFirstThenById()
{
CardModel[] cards = [Card(1, "b"), Card(2, "B"), Card(3, ""), Card(4, "a"), Card(5, "b")];
CollectionAssert.AreEqual(new[] { 3L, 2L, 4L, 1L, 5L }, Ids(cards, CardSortOption.Title));
}
[TestMethod]
public void TitleSortsSupplementaryCharactersAfterBmpPrivateUse()
{
// U+1F600 is a surrogate pair in UTF-16, so ordinal comparison would put it before U+E000.
CardModel[] cards = [Card(1, "\U0001F600"), Card(2, "")];
CollectionAssert.AreEqual(new[] { 2L, 1L }, Ids(cards, CardSortOption.Title));
}
}
+9 -18
View File
@@ -7,11 +7,9 @@ namespace YKanBan.Tests.Models;
/// boundary in both directions. /// boundary in both directions.
/// </summary> /// </summary>
[TestClass] [TestClass]
public class RgbColorTests public class RgbColorTests {
{
[TestMethod] [TestMethod]
public void ParseSplitsComponents() public void ParseSplitsComponents() {
{
RgbColor color = RgbColor.Parse("#102030"); RgbColor color = RgbColor.Parse("#102030");
Assert.AreEqual((byte)0x10, color.R); Assert.AreEqual((byte)0x10, color.R);
Assert.AreEqual((byte)0x20, color.G); Assert.AreEqual((byte)0x20, color.G);
@@ -22,8 +20,7 @@ public class RgbColorTests
[DataRow("#a1B2c3")] [DataRow("#a1B2c3")]
[DataRow("#A1B2C3")] [DataRow("#A1B2C3")]
[DataRow("#a1b2c3")] [DataRow("#a1b2c3")]
public void ParseIsCaseInsensitive(string text) public void ParseIsCaseInsensitive(string text) {
{
Assert.AreEqual(new RgbColor(0xA1, 0xB2, 0xC3), RgbColor.Parse(text)); Assert.AreEqual(new RgbColor(0xA1, 0xB2, 0xC3), RgbColor.Parse(text));
} }
@@ -36,41 +33,35 @@ public class RgbColorTests
[DataRow("#12345g")] [DataRow("#12345g")]
[DataRow(" #112233")] [DataRow(" #112233")]
[DataRow("#112233 ")] [DataRow("#112233 ")]
public void ParseRejectsMalformedText(string text) public void ParseRejectsMalformedText(string text) {
{
Assert.ThrowsExactly<FormatException>(() => RgbColor.Parse(text)); Assert.ThrowsExactly<FormatException>(() => RgbColor.Parse(text));
} }
[TestMethod] [TestMethod]
public void TryParseRejectsNull() public void TryParseRejectsNull() {
{
Assert.IsFalse(RgbColor.TryParse(null, out RgbColor color)); Assert.IsFalse(RgbColor.TryParse(null, out RgbColor color));
Assert.AreEqual(default, color); Assert.AreEqual(default, color);
} }
[TestMethod] [TestMethod]
public void TryParseAcceptsValidText() public void TryParseAcceptsValidText() {
{
Assert.IsTrue(RgbColor.TryParse("#010203", out RgbColor color)); Assert.IsTrue(RgbColor.TryParse("#010203", out RgbColor color));
Assert.AreEqual(new RgbColor(1, 2, 3), color); Assert.AreEqual(new RgbColor(1, 2, 3), color);
} }
[TestMethod] [TestMethod]
public void ToStringUsesCanonicalLowercase() public void ToStringUsesCanonicalLowercase() {
{
Assert.AreEqual("#ff0a00", new RgbColor(0xFF, 0x0A, 0x00).ToString()); Assert.AreEqual("#ff0a00", new RgbColor(0xFF, 0x0A, 0x00).ToString());
} }
[TestMethod] [TestMethod]
public void TextRoundTrips() public void TextRoundTrips() {
{
var color = new RgbColor(0x12, 0xAB, 0xCD); var color = new RgbColor(0x12, 0xAB, 0xCD);
Assert.AreEqual(color, RgbColor.Parse(color.ToString())); Assert.AreEqual(color, RgbColor.Parse(color.ToString()));
} }
[TestMethod] [TestMethod]
public void EqualityComparesComponents() public void EqualityComparesComponents() {
{
Assert.AreEqual(new RgbColor(1, 2, 3), new RgbColor(1, 2, 3)); Assert.AreEqual(new RgbColor(1, 2, 3), new RgbColor(1, 2, 3));
Assert.AreNotEqual(new RgbColor(1, 2, 3), new RgbColor(1, 2, 4)); Assert.AreNotEqual(new RgbColor(1, 2, 3), new RgbColor(1, 2, 4));
} }
+2 -4
View File
@@ -7,15 +7,13 @@ namespace YKanBan.Tests;
/// application project and that the test runner can discover and execute tests. /// application project and that the test runner can discover and execute tests.
/// </summary> /// </summary>
[TestClass] [TestClass]
public class ProjectReferenceTests public class ProjectReferenceTests {
{
/// <summary> /// <summary>
/// Verifies that a type defined in the application assembly can be /// Verifies that a type defined in the application assembly can be
/// referenced from the test project. /// referenced from the test project.
/// </summary> /// </summary>
[TestMethod] [TestMethod]
public void ApplicationAssemblyIsReferenceable() public void ApplicationAssemblyIsReferenceable() {
{
Assert.IsNotNull(typeof(App)); Assert.IsNotNull(typeof(App));
} }
} }
+7 -14
View File
@@ -7,8 +7,7 @@ namespace YKanBan.Tests.Search;
/// records compare by reference for their Terms collections by design (see the /// records compare by reference for their Terms collections by design (see the
/// YYC MARK note in SearchNodes.cs), so tests provide equality explicitly. /// YYC MARK note in SearchNodes.cs), so tests provide equality explicitly.
/// </summary> /// </summary>
public sealed class SearchNodeComparer : IEqualityComparer<SearchNode> public sealed class SearchNodeComparer : IEqualityComparer<SearchNode> {
{
/// <summary> /// <summary>
/// Gets the shared comparer instance. /// Gets the shared comparer instance.
/// </summary> /// </summary>
@@ -20,19 +19,15 @@ public sealed class SearchNodeComparer : IEqualityComparer<SearchNode>
/// <param name="x">The first node.</param> /// <param name="x">The first node.</param>
/// <param name="y">The second node.</param> /// <param name="y">The second node.</param>
/// <returns><see langword="true"/> when the nodes are structurally equal.</returns> /// <returns><see langword="true"/> when the nodes are structurally equal.</returns>
public bool Equals(SearchNode? x, SearchNode? y) public bool Equals(SearchNode? x, SearchNode? y) {
{ if (ReferenceEquals(x, y)) {
if (ReferenceEquals(x, y))
{
return true; return true;
} }
if (x is null || y is null || x.GetType() != y.GetType()) if (x is null || y is null || x.GetType() != y.GetType()) {
{
return false; return false;
} }
return (x, y) switch return (x, y) switch {
{
(SearchNode.Or a, SearchNode.Or b) => SequencesEqual(a.Terms, b.Terms), (SearchNode.Or a, SearchNode.Or b) => SequencesEqual(a.Terms, b.Terms),
(SearchNode.And a, SearchNode.And b) => SequencesEqual(a.Terms, b.Terms), (SearchNode.And a, SearchNode.And b) => SequencesEqual(a.Terms, b.Terms),
(SearchNode.FreeText a, SearchNode.FreeText b) => a.Text == b.Text, (SearchNode.FreeText a, SearchNode.FreeText b) => a.Text == b.Text,
@@ -58,10 +53,8 @@ public sealed class SearchNodeComparer : IEqualityComparer<SearchNode>
/// <param name="x">The first sequence.</param> /// <param name="x">The first sequence.</param>
/// <param name="y">The second sequence.</param> /// <param name="y">The second sequence.</param>
/// <returns><see langword="true"/> when both sequences match element-wise.</returns> /// <returns><see langword="true"/> when both sequences match element-wise.</returns>
private static bool SequencesEqual(IReadOnlyList<SearchNode> x, IReadOnlyList<SearchNode> y) private static bool SequencesEqual(IReadOnlyList<SearchNode> x, IReadOnlyList<SearchNode> y) {
{ if (x.Count != y.Count) {
if (x.Count != y.Count)
{
return false; return false;
} }
return x.Zip(y).All(pair => Instance.Equals(pair.First, pair.Second)); return x.Zip(y).All(pair => Instance.Equals(pair.First, pair.Second));
+77 -90
View File
@@ -8,15 +8,13 @@ namespace YKanBan.Tests.Search;
/// <see cref="SearchSyntaxException"/>). /// <see cref="SearchSyntaxException"/>).
/// </summary> /// </summary>
[TestClass] [TestClass]
public class SearchQueryParserTests public class SearchQueryParserTests {
{
/// <summary> /// <summary>
/// Parses and asserts structural equality against the expected AST. /// Parses and asserts structural equality against the expected AST.
/// </summary> /// </summary>
/// <param name="expected">The expected AST.</param> /// <param name="expected">The expected AST.</param>
/// <param name="text">The search text.</param> /// <param name="text">The search text.</param>
private static void AssertParsesTo(SearchNode expected, string text) private static void AssertParsesTo(SearchNode expected, string text) {
{
SearchNode? parsed = SearchQueryParser.Parse(text); SearchNode? parsed = SearchQueryParser.Parse(text);
Assert.IsNotNull(parsed, $"Blank-looking input: '{text}'."); Assert.IsNotNull(parsed, $"Blank-looking input: '{text}'.");
Assert.AreEqual(expected, parsed, SearchNodeComparer.Instance); Assert.AreEqual(expected, parsed, SearchNodeComparer.Instance);
@@ -26,53 +24,46 @@ public class SearchQueryParserTests
/// Asserts that the input violates the grammar. /// Asserts that the input violates the grammar.
/// </summary> /// </summary>
/// <param name="text">The search text.</param> /// <param name="text">The search text.</param>
private static void AssertSyntaxError(string text) private static void AssertSyntaxError(string text) {
{
Assert.ThrowsExactly<SearchSyntaxException>(() => SearchQueryParser.Parse(text)); Assert.ThrowsExactly<SearchSyntaxException>(() => SearchQueryParser.Parse(text));
} }
#region Successful parses #region Successful parses
[TestMethod] [TestMethod]
public void BlankInputReturnsNull() public void BlankInputReturnsNull() {
{
Assert.IsNull(SearchQueryParser.Parse(string.Empty)); Assert.IsNull(SearchQueryParser.Parse(string.Empty));
Assert.IsNull(SearchQueryParser.Parse(" ")); Assert.IsNull(SearchQueryParser.Parse(" "));
} }
[TestMethod] [TestMethod]
public void SingleWordIsFreeText() public void SingleWordIsFreeText() {
{
AssertParsesTo(new SearchNode.FreeText("login"), "login"); AssertParsesTo(new SearchNode.FreeText("login"), "login");
} }
[TestMethod] [TestMethod]
public void AdjacentWordsAreImplicitAnd() public void AdjacentWordsAreImplicitAnd() {
{
AssertParsesTo( AssertParsesTo(
new SearchNode.And([new SearchNode.FreeText("fix"), new SearchNode.FreeText("login")]), new SearchNode.And([new SearchNode.FreeText("fix"), new SearchNode.FreeText("login")]),
"fix login"); "fix login");
} }
[TestMethod] [TestMethod]
public void ExplicitAndKeyword() public void ExplicitAndKeyword() {
{
AssertParsesTo( AssertParsesTo(
new SearchNode.And([new SearchNode.FreeText("a"), new SearchNode.FreeText("b")]), new SearchNode.And([new SearchNode.FreeText("a"), new SearchNode.FreeText("b")]),
"a AND b"); "a AND b");
} }
[TestMethod] [TestMethod]
public void OrKeyword() public void OrKeyword() {
{
AssertParsesTo( AssertParsesTo(
new SearchNode.Or([new SearchNode.FreeText("a"), new SearchNode.FreeText("b")]), new SearchNode.Or([new SearchNode.FreeText("a"), new SearchNode.FreeText("b")]),
"a OR b"); "a OR b");
} }
[TestMethod] [TestMethod]
public void ImplicitAndBindsTighterThanOr() public void ImplicitAndBindsTighterThanOr() {
{
AssertParsesTo( AssertParsesTo(
new SearchNode.Or([ new SearchNode.Or([
new SearchNode.And([new SearchNode.FreeText("a"), new SearchNode.FreeText("b")]), new SearchNode.And([new SearchNode.FreeText("a"), new SearchNode.FreeText("b")]),
@@ -81,8 +72,7 @@ public class SearchQueryParserTests
} }
[TestMethod] [TestMethod]
public void ParenthesesForceGrouping() public void ParenthesesForceGrouping() {
{
AssertParsesTo( AssertParsesTo(
new SearchNode.And([ new SearchNode.And([
new SearchNode.FreeText("a"), new SearchNode.FreeText("a"),
@@ -91,16 +81,14 @@ public class SearchQueryParserTests
} }
[TestMethod] [TestMethod]
public void NestedParenthesesCollapse() public void NestedParenthesesCollapse() {
{
AssertParsesTo( AssertParsesTo(
new SearchNode.Or([new SearchNode.FreeText("a"), new SearchNode.FreeText("b")]), new SearchNode.Or([new SearchNode.FreeText("a"), new SearchNode.FreeText("b")]),
"((a OR b))"); "((a OR b))");
} }
[TestMethod] [TestMethod]
public void LowercaseKeywordsArePlainWords() public void LowercaseKeywordsArePlainWords() {
{
AssertParsesTo( AssertParsesTo(
new SearchNode.And([ new SearchNode.And([
new SearchNode.FreeText("a"), new SearchNode.FreeText("a"),
@@ -111,14 +99,12 @@ public class SearchQueryParserTests
} }
[TestMethod] [TestMethod]
public void PhraseIsFreeText() public void PhraseIsFreeText() {
{
AssertParsesTo(new SearchNode.FreeText("hello world"), "\"hello world\""); AssertParsesTo(new SearchNode.FreeText("hello world"), "\"hello world\"");
} }
[TestMethod] [TestMethod]
public void QuotedOperatorKeywordIsFreeText() public void QuotedOperatorKeywordIsFreeText() {
{
// A quoted AND/OR is literal text, not an operator. // A quoted AND/OR is literal text, not an operator.
AssertParsesTo(new SearchNode.FreeText("AND"), "\"AND\""); AssertParsesTo(new SearchNode.FreeText("AND"), "\"AND\"");
AssertParsesTo( AssertParsesTo(
@@ -127,61 +113,52 @@ public class SearchQueryParserTests
} }
[TestMethod] [TestMethod]
public void PhraseSupportsEscapes() public void PhraseSupportsEscapes() {
{
// Escaped quote and escaped backslash. // Escaped quote and escaped backslash.
AssertParsesTo(new SearchNode.FreeText("a\"b"), "\"a\\\"b\""); AssertParsesTo(new SearchNode.FreeText("a\"b"), "\"a\\\"b\"");
AssertParsesTo(new SearchNode.FreeText("a\\b"), "\"a\\\\b\""); AssertParsesTo(new SearchNode.FreeText("a\\b"), "\"a\\\\b\"");
} }
[TestMethod] [TestMethod]
public void TagQualifier() public void TagQualifier() {
{
AssertParsesTo(new SearchNode.TagName("bug"), "tag:bug"); AssertParsesTo(new SearchNode.TagName("bug"), "tag:bug");
} }
[TestMethod] [TestMethod]
public void TagQualifierAcceptsPhraseValue() public void TagQualifierAcceptsPhraseValue() {
{
AssertParsesTo(new SearchNode.TagName("a b"), "tag:\"a b\""); AssertParsesTo(new SearchNode.TagName("a b"), "tag:\"a b\"");
} }
[TestMethod] [TestMethod]
public void QuotedQualifierValueMayContainColonsAndOperators() public void QuotedQualifierValueMayContainColonsAndOperators() {
{
AssertParsesTo(new SearchNode.TagName("a:b"), "tag:\"a:b\""); AssertParsesTo(new SearchNode.TagName("a:b"), "tag:\"a:b\"");
AssertParsesTo(new SearchNode.TagName("AND"), "tag:\"AND\""); AssertParsesTo(new SearchNode.TagName("AND"), "tag:\"AND\"");
} }
[TestMethod] [TestMethod]
public void TitleAndContentQualifiers() public void TitleAndContentQualifiers() {
{
AssertParsesTo(new SearchNode.FieldText(SearchField.Title, "foo"), "title:foo"); AssertParsesTo(new SearchNode.FieldText(SearchField.Title, "foo"), "title:foo");
AssertParsesTo(new SearchNode.FieldText(SearchField.Content, "foo"), "content:foo"); AssertParsesTo(new SearchNode.FieldText(SearchField.Content, "foo"), "content:foo");
} }
[TestMethod] [TestMethod]
public void ColumnQualifierAcceptsPhraseValue() public void ColumnQualifierAcceptsPhraseValue() {
{
AssertParsesTo(new SearchNode.ColumnTitle("To Do"), "column:\"To Do\""); AssertParsesTo(new SearchNode.ColumnTitle("To Do"), "column:\"To Do\"");
} }
[TestMethod] [TestMethod]
public void IdQualifierParsesNumber() public void IdQualifierParsesNumber() {
{
AssertParsesTo(new SearchNode.CardId(42), "id:42"); AssertParsesTo(new SearchNode.CardId(42), "id:42");
AssertParsesTo(new SearchNode.CardId(61), "id:#61"); AssertParsesTo(new SearchNode.CardId(61), "id:#61");
} }
[TestMethod] [TestMethod]
public void QuotedTextWithColonIsFreeText() public void QuotedTextWithColonIsFreeText() {
{
AssertParsesTo(new SearchNode.FreeText("http://x"), "\"http://x\""); AssertParsesTo(new SearchNode.FreeText("http://x"), "\"http://x\"");
} }
[TestMethod] [TestMethod]
public void WordMayContainHashAndPunctuation() public void WordMayContainHashAndPunctuation() {
{
AssertParsesTo(new SearchNode.FreeText("#61"), "#61"); AssertParsesTo(new SearchNode.FreeText("#61"), "#61");
AssertParsesTo(new SearchNode.FreeText("c#/.net"), "c#/.net"); AssertParsesTo(new SearchNode.FreeText("c#/.net"), "c#/.net");
} }
@@ -191,84 +168,103 @@ public class SearchQueryParserTests
#region Strict failures #region Strict failures
[TestMethod] [TestMethod]
public void UnterminatedPhraseIsAnError() public void UnterminatedPhraseIsAnError() {
{
AssertSyntaxError("\"abc def"); AssertSyntaxError("\"abc def");
} }
[TestMethod] [TestMethod]
public void TrailingUnterminatedPhraseIsAnError() public void TrailingUnterminatedPhraseIsAnError() {
{
AssertSyntaxError("a \"abc"); AssertSyntaxError("a \"abc");
} }
[TestMethod] [TestMethod]
public void InvalidEscapeInPhraseIsAnError() public void InvalidEscapeInPhraseIsAnError() {
{
// A bare backslash (not followed by a quote or another backslash) is invalid. // A bare backslash (not followed by a quote or another backslash) is invalid.
AssertSyntaxError("\"a\\b\""); AssertSyntaxError("\"a\\b\"");
} }
[TestMethod] [TestMethod]
public void InvalidEscapeInQualifierPhraseIsAnError() public void InvalidEscapeInQualifierPhraseIsAnError() {
{
AssertSyntaxError("tag:\"a\\x\""); AssertSyntaxError("tag:\"a\\x\"");
} }
[TestMethod] [TestMethod]
public void UnbalancedOpenParenIsAnError() public void UnbalancedOpenParenIsAnError() {
{
AssertSyntaxError("(a"); AssertSyntaxError("(a");
} }
[TestMethod] [TestMethod]
public void StrayCloseParenIsAnError() public void StrayCloseParenIsAnError() {
{
AssertSyntaxError("a)"); AssertSyntaxError("a)");
} }
[TestMethod] [TestMethod]
public void EmptyParensAreAnError() public void EmptyParensAreAnError() {
{
AssertSyntaxError("()"); AssertSyntaxError("()");
} }
[TestMethod] [TestMethod]
public void DanglingOrIsAnError() public void DanglingOrIsAnError() {
{
AssertSyntaxError("a OR"); AssertSyntaxError("a OR");
} }
[TestMethod] [TestMethod]
public void DanglingAndIsAnError() public void DanglingAndIsAnError() {
{
AssertSyntaxError("a AND"); AssertSyntaxError("a AND");
} }
[TestMethod] [TestMethod]
public void LeadingAndIsAnError() public void LeadingAndIsAnError() {
{
AssertSyntaxError("AND a"); AssertSyntaxError("AND a");
} }
[TestMethod] [TestMethod]
public void OperatorAtOperandPositionIsAnError() public void OperatorAtOperandPositionIsAnError() {
{
AssertSyntaxError("a AND OR b"); AssertSyntaxError("a AND OR b");
} }
[TestMethod] [TestMethod]
public void QualifierWithoutValueIsAnError() public void QualifierWithoutValueIsAnError() {
{
AssertSyntaxError("tag:"); AssertSyntaxError("tag:");
} }
[TestMethod] [TestMethod]
public void SpacedQualifierValueIsAnError() public void SpacedQualifierValueIsAnError() {
{
AssertSyntaxError("tag: bug"); AssertSyntaxError("tag: bug");
} }
[TestMethod]
[DataRow("tag: \"x\"")]
[DataRow("title: \"a b\"")]
public void SpacedQualifierPhraseValueIsAnError(string text) {
AssertSyntaxError(text);
}
[TestMethod]
[DataRow("a\"b\"")]
[DataRow("\"a\"b")]
[DataRow("\"a\"\"b\"")]
[DataRow("tag:\"x\"y")]
[DataRow("tag:\"x\"\"y\"")]
public void PhraseGluedToOtherTextIsAnError(string text) {
AssertSyntaxError(text);
}
[TestMethod]
[DataRow("\"\"")]
[DataRow("a \"\"")]
[DataRow("tag:\"\"")]
public void EmptyPhraseIsAnError(string text) {
AssertSyntaxError(text);
}
[TestMethod]
public void PhraseMayTouchParentheses() {
AssertParsesTo(
new SearchNode.And([new SearchNode.FreeText("a b"), new SearchNode.FreeText("c")]),
"(\"a b\")(c)");
}
[TestMethod] [TestMethod]
[DataRow("id:12x")] [DataRow("id:12x")]
[DataRow("id:abc")] [DataRow("id:abc")]
@@ -280,14 +276,12 @@ public class SearchQueryParserTests
[DataRow("id:1.5")] [DataRow("id:1.5")]
[DataRow("id:٣")] [DataRow("id:٣")]
[DataRow("id:99999999999999999999")] [DataRow("id:99999999999999999999")]
public void InvalidIdValueIsAnError(string text) public void InvalidIdValueIsAnError(string text) {
{
AssertSyntaxError(text); AssertSyntaxError(text);
} }
[TestMethod] [TestMethod]
public void QuotedIdValueIsAnError() public void QuotedIdValueIsAnError() {
{
AssertSyntaxError("id:\"61\""); AssertSyntaxError("id:\"61\"");
} }
@@ -295,14 +289,12 @@ public class SearchQueryParserTests
[DataRow("tag:AND")] [DataRow("tag:AND")]
[DataRow("tag:OR")] [DataRow("tag:OR")]
[DataRow("title:AND")] [DataRow("title:AND")]
public void BareOperatorAsQualifierValueIsAnError(string text) public void BareOperatorAsQualifierValueIsAnError(string text) {
{
AssertSyntaxError(text); AssertSyntaxError(text);
} }
[TestMethod] [TestMethod]
public void UnquotedQualifierValueWithColonIsAnError() public void UnquotedQualifierValueWithColonIsAnError() {
{
AssertSyntaxError("tag:a:b"); AssertSyntaxError("tag:a:b");
} }
@@ -310,8 +302,7 @@ public class SearchQueryParserTests
[DataRow(":foo")] [DataRow(":foo")]
[DataRow("http://x")] [DataRow("http://x")]
[DataRow("a:")] [DataRow("a:")]
public void ColonAfterNonKeyIsAnError(string text) public void ColonAfterNonKeyIsAnError(string text) {
{
AssertSyntaxError(text); AssertSyntaxError(text);
} }
@@ -319,27 +310,23 @@ public class SearchQueryParserTests
[DataRow("a\\b")] [DataRow("a\\b")]
[DataRow("\\")] [DataRow("\\")]
[DataRow("tag:a\\b")] [DataRow("tag:a\\b")]
public void BackslashInBareWordIsAnError(string text) public void BackslashInBareWordIsAnError(string text) {
{
AssertSyntaxError(text); AssertSyntaxError(text);
} }
[TestMethod] [TestMethod]
public void UnknownQualifierKeyIsAnError() public void UnknownQualifierKeyIsAnError() {
{
AssertSyntaxError("foo:bar"); AssertSyntaxError("foo:bar");
} }
[TestMethod] [TestMethod]
public void QualifierKeysAreCaseSensitive() public void QualifierKeysAreCaseSensitive() {
{
// "Tag" is a key-like prefix but not the known lowercase "tag", so it is unknown. // "Tag" is a key-like prefix but not the known lowercase "tag", so it is unknown.
AssertSyntaxError("Tag:x"); AssertSyntaxError("Tag:x");
} }
[TestMethod] [TestMethod]
public void SyntaxErrorCarriesDescriptiveMessage() public void SyntaxErrorCarriesDescriptiveMessage() {
{
SearchSyntaxException exception = Assert.ThrowsExactly<SearchSyntaxException>( SearchSyntaxException exception = Assert.ThrowsExactly<SearchSyntaxException>(
() => SearchQueryParser.Parse("a AND")); () => SearchQueryParser.Parse("a AND"));
Assert.IsFalse(string.IsNullOrEmpty(exception.Message)); Assert.IsFalse(string.IsNullOrEmpty(exception.Message));
+29 -51
View File
@@ -1,4 +1,5 @@
using Microsoft.Data.Sqlite; using Microsoft.Data.Sqlite;
using YKanBan.Search; using YKanBan.Search;
using YKanBan.Storage.Workspace; using YKanBan.Storage.Workspace;
using YKanBan.Tests.TestUtilities; using YKanBan.Tests.TestUtilities;
@@ -10,31 +11,29 @@ namespace YKanBan.Tests.Search;
/// workspace database. /// workspace database.
/// </summary> /// </summary>
[TestClass] [TestClass]
public class SearchSqlCompilerTests public class SearchSqlCompilerTests {
{
/// <summary> /// <summary>
/// Owns a workspace with a fixed card/tag fixture. /// Owns a workspace with a fixed card/tag fixture.
/// </summary> /// </summary>
private sealed class SearchFixture : IDisposable private sealed class SearchFixture : IDisposable {
{
public TempDirectory Directory { get; } = new(); public TempDirectory Directory { get; } = new();
public SqliteConnection Connection { get; } public SqliteConnection Connection { get; }
public SearchFixture() public SearchFixture() {
{
WorkspaceInitializer.Initialize(Directory.FullPath); WorkspaceInitializer.Initialize(Directory.FullPath);
using (SqliteConnection setup = SqliteTestHelper.OpenWorkspace(Directory.FullPath)) using (SqliteConnection setup = SqliteTestHelper.OpenWorkspace(Directory.FullPath)) {
{
// Columns: 1 "To Do", 2 "In Progress". // Columns: 1 "To Do", 2 "In Progress".
SqliteTestHelper.Exec(setup, "INSERT INTO columns (title, description, created_at, updated_at) VALUES ('To Do', '', 1, 1);"); SqliteTestHelper.Exec(setup, "INSERT INTO columns (title, description, created_at, updated_at) VALUES ('To Do', '', 1, 1);");
SqliteTestHelper.Exec(setup, "INSERT INTO columns (title, description, created_at, updated_at) VALUES ('In Progress', '', 1, 1);"); SqliteTestHelper.Exec(setup, "INSERT INTO columns (title, description, created_at, updated_at) VALUES ('In Progress', '', 1, 1);");
SqliteTestHelper.Exec(setup, "INSERT INTO columns (title, description, created_at, updated_at) VALUES ('Archive', '', 1, 1);");
// Cards: 1 titled, 2 title-or-content matches, 3 untitled, 4 wildcard chars. // Cards: 1 titled, 2 title-or-content matches, 3 untitled, 4 wildcard chars.
SqliteTestHelper.Exec(setup, "INSERT INTO cards (column_id, title, content, created_at, updated_at) VALUES (1, 'Fix login', 'Cannot sign in', 1, 1);"); SqliteTestHelper.Exec(setup, "INSERT INTO cards (column_id, title, content, created_at, updated_at) VALUES (1, 'Fix login', 'Cannot sign in', 1, 1);");
SqliteTestHelper.Exec(setup, "INSERT INTO cards (column_id, title, content, created_at, updated_at) VALUES (2, 'Green apple', 'the apple pie', 1, 1);"); SqliteTestHelper.Exec(setup, "INSERT INTO cards (column_id, title, content, created_at, updated_at) VALUES (2, 'Green apple', 'the apple pie', 1, 1);");
SqliteTestHelper.Exec(setup, "INSERT INTO cards (column_id, title, content, created_at, updated_at) VALUES (2, '', 'banana split', 1, 1);"); SqliteTestHelper.Exec(setup, "INSERT INTO cards (column_id, title, content, created_at, updated_at) VALUES (2, '', 'banana split', 1, 1);");
SqliteTestHelper.Exec(setup, "INSERT INTO cards (column_id, title, content, created_at, updated_at) VALUES (1, '100% done', 'a_b test', 1, 1);"); SqliteTestHelper.Exec(setup, "INSERT INTO cards (column_id, title, content, created_at, updated_at) VALUES (1, '100% done', 'a_b test', 1, 1);");
SqliteTestHelper.Exec(setup, "INSERT INTO cards (column_id, title, content, created_at, updated_at) VALUES (3, 'ÄÖÜ Straße', '', 1, 1);");
// Tags: mixed case names plus one containing spaces. // Tags: mixed case names plus one containing spaces.
SqliteTestHelper.Exec(setup, "INSERT INTO tags (name, color, description) VALUES ('Bug', '#ff0000', '');"); SqliteTestHelper.Exec(setup, "INSERT INTO tags (name, color, description) VALUES ('Bug', '#ff0000', '');");
@@ -54,38 +53,33 @@ public class SearchSqlCompilerTests
/// </summary> /// </summary>
/// <param name="queryText">The search text.</param> /// <param name="queryText">The search text.</param>
/// <returns>The matching card ids in id order.</returns> /// <returns>The matching card ids in id order.</returns>
public List<long> Search(string queryText) public List<long> Search(string queryText) {
{
SearchNode? query = SearchQueryParser.Parse(queryText); SearchNode? query = SearchQueryParser.Parse(queryText);
Assert.IsNotNull(query, "Blank fixture queries are not expected here."); Assert.IsNotNull(query, "Blank fixture queries are not expected here.");
CompiledSearch compiled = SearchSqlCompiler.Compile(query); CompiledSearch compiled = SearchSqlCompiler.Compile(query);
using var command = Connection.CreateCommand(); using var command = Connection.CreateCommand();
command.CommandText = $"SELECT c.id FROM cards c WHERE {compiled.Predicate} ORDER BY c.id ASC;"; command.CommandText = $"SELECT c.id FROM cards c WHERE {compiled.Predicate} ORDER BY c.id ASC;";
foreach ((string name, object value) in compiled.Parameters) foreach ((string name, object value) in compiled.Parameters) {
{
command.Parameters.AddWithValue(name, value); command.Parameters.AddWithValue(name, value);
} }
using var reader = command.ExecuteReader(); using var reader = command.ExecuteReader();
var ids = new List<long>(); var ids = new List<long>();
while (reader.Read()) while (reader.Read()) {
{
ids.Add(reader.GetInt64(0)); ids.Add(reader.GetInt64(0));
} }
return ids; return ids;
} }
public void Dispose() public void Dispose() {
{
Connection.Dispose(); Connection.Dispose();
Directory.Dispose(); Directory.Dispose();
} }
} }
[TestMethod] [TestMethod]
public void FreeTextMatchesTitleOrContentCaseInsensitively() public void FreeTextMatchesTitleOrContentCaseInsensitively() {
{
using var fixture = new SearchFixture(); using var fixture = new SearchFixture();
CollectionAssert.AreEqual(new[] { 2L }, fixture.Search("apple")); CollectionAssert.AreEqual(new[] { 2L }, fixture.Search("apple"));
CollectionAssert.AreEqual(new[] { 1L }, fixture.Search("login")); CollectionAssert.AreEqual(new[] { 1L }, fixture.Search("login"));
@@ -94,8 +88,7 @@ public class SearchSqlCompilerTests
} }
[TestMethod] [TestMethod]
public void FieldQualifiersScopeToTheirField() public void FieldQualifiersScopeToTheirField() {
{
using var fixture = new SearchFixture(); using var fixture = new SearchFixture();
CollectionAssert.AreEqual(new[] { 2L }, fixture.Search("title:apple")); CollectionAssert.AreEqual(new[] { 2L }, fixture.Search("title:apple"));
CollectionAssert.AreEqual(new[] { 3L }, fixture.Search("content:banana")); CollectionAssert.AreEqual(new[] { 3L }, fixture.Search("content:banana"));
@@ -103,8 +96,7 @@ public class SearchSqlCompilerTests
} }
[TestMethod] [TestMethod]
public void TagQualifierMatchesExactlyAndCaseInsensitively() public void TagQualifierMatchesExactlyAndCaseInsensitively() {
{
using var fixture = new SearchFixture(); using var fixture = new SearchFixture();
CollectionAssert.AreEqual(new[] { 1L }, fixture.Search("tag:bug")); CollectionAssert.AreEqual(new[] { 1L }, fixture.Search("tag:bug"));
CollectionAssert.AreEqual(new[] { 2L, 3L }, fixture.Search("tag:ui")); CollectionAssert.AreEqual(new[] { 2L, 3L }, fixture.Search("tag:ui"));
@@ -116,8 +108,7 @@ public class SearchSqlCompilerTests
} }
[TestMethod] [TestMethod]
public void ColumnQualifierMatchesColumnTitleExactly() public void ColumnQualifierMatchesColumnTitleExactly() {
{
using var fixture = new SearchFixture(); using var fixture = new SearchFixture();
CollectionAssert.AreEqual(new[] { 1L, 4L }, fixture.Search("column:\"to do\"")); CollectionAssert.AreEqual(new[] { 1L, 4L }, fixture.Search("column:\"to do\""));
CollectionAssert.AreEqual(new[] { 2L, 3L }, fixture.Search("column:\"in progress\"")); CollectionAssert.AreEqual(new[] { 2L, 3L }, fixture.Search("column:\"in progress\""));
@@ -128,16 +119,14 @@ public class SearchSqlCompilerTests
} }
[TestMethod] [TestMethod]
public void IdQualifierMatchesExactly() public void IdQualifierMatchesExactly() {
{
using var fixture = new SearchFixture(); using var fixture = new SearchFixture();
CollectionAssert.AreEqual(new[] { 3L }, fixture.Search("id:3")); CollectionAssert.AreEqual(new[] { 3L }, fixture.Search("id:3"));
Assert.AreEqual(0, fixture.Search("id:99").Count); Assert.AreEqual(0, fixture.Search("id:99").Count);
} }
[TestMethod] [TestMethod]
public void AndOrCombination() public void AndOrCombination() {
{
using var fixture = new SearchFixture(); using var fixture = new SearchFixture();
CollectionAssert.AreEqual(new[] { 2L, 3L }, fixture.Search("apple OR banana")); CollectionAssert.AreEqual(new[] { 2L, 3L }, fixture.Search("apple OR banana"));
CollectionAssert.AreEqual(new[] { 2L }, fixture.Search("apple AND id:2")); CollectionAssert.AreEqual(new[] { 2L }, fixture.Search("apple AND id:2"));
@@ -145,8 +134,7 @@ public class SearchSqlCompilerTests
} }
[TestMethod] [TestMethod]
public void ParenthesizedGrouping() public void ParenthesizedGrouping() {
{
using var fixture = new SearchFixture(); using var fixture = new SearchFixture();
// (apple OR banana) hits cards 2,3; intersected with column "In Progress" (2,3). // (apple OR banana) hits cards 2,3; intersected with column "In Progress" (2,3).
@@ -157,37 +145,27 @@ public class SearchSqlCompilerTests
} }
[TestMethod] [TestMethod]
public void LikeWildcardsInUserTextMatchLiterally() public void PercentAndUnderscoreInUserTextMatchLiterally() {
{
using var fixture = new SearchFixture(); using var fixture = new SearchFixture();
CollectionAssert.AreEqual(new[] { 4L }, fixture.Search("100%")); CollectionAssert.AreEqual(new[] { 4L }, fixture.Search("100%"));
CollectionAssert.AreEqual(new[] { 4L }, fixture.Search("a_b")); CollectionAssert.AreEqual(new[] { 4L }, fixture.Search("a_b"));
} }
[TestMethod] [TestMethod]
public void CompiledPredicateUsesNamedParameters() public void UnicodeCaseFoldingMatchesNonAscii() {
{ using var fixture = new SearchFixture();
// SQLite's LIKE would only fold ASCII; the ykb_fold function folds these too.
CollectionAssert.AreEqual(new[] { 5L }, fixture.Search("äöü"));
CollectionAssert.AreEqual(new[] { 5L }, fixture.Search("straße"));
}
[TestMethod]
public void CompiledPredicateUsesNamedParameters() {
CompiledSearch compiled = SearchSqlCompiler.Compile(new SearchNode.FreeText("x")); CompiledSearch compiled = SearchSqlCompiler.Compile(new SearchNode.FreeText("x"));
// One folded parameter shared by the title and content tests.
StringAssert.Contains(compiled.Predicate, "$p0"); StringAssert.Contains(compiled.Predicate, "$p0");
Assert.AreEqual(1, compiled.Parameters.Count); Assert.AreEqual(1, compiled.Parameters.Count);
Assert.AreEqual("x", compiled.Parameters[0].Value); Assert.AreEqual("x", compiled.Parameters[0].Value);
} }
[TestMethod]
public void MatchingFoldsNonAsciiCase()
{
using var fixture = new SearchFixture();
SqliteTestHelper.Exec(fixture.Connection, "INSERT INTO columns (title, description, created_at, updated_at) VALUES ('Érable', '', 1, 1);");
SqliteTestHelper.Exec(fixture.Connection, "INSERT INTO cards (column_id, title, content, created_at, updated_at) VALUES (3, 'Ärger', 'Straße ΣΟΦΙΑ', 1, 1);");
SqliteTestHelper.Exec(fixture.Connection, "INSERT INTO tags (name, color, description) VALUES ('Äpfel', '#123456', '');");
SqliteTestHelper.Exec(fixture.Connection, "INSERT INTO card_tags (card_id, tag_id) VALUES (5, 4);");
CollectionAssert.AreEqual(new[] { 5L }, fixture.Search("ärger"));
CollectionAssert.AreEqual(new[] { 5L }, fixture.Search("title:ÄRGER"));
CollectionAssert.AreEqual(new[] { 5L }, fixture.Search("content:σοφια"));
CollectionAssert.AreEqual(new[] { 5L }, fixture.Search("tag:äpfel"));
CollectionAssert.AreEqual(new[] { 5L }, fixture.Search("column:érable"));
}
} }
@@ -8,11 +8,9 @@ namespace YKanBan.Tests.Storage.AppData;
/// degradation on a missing or corrupt file. /// degradation on a missing or corrupt file.
/// </summary> /// </summary>
[TestClass] [TestClass]
public class AppConfigStoreTests public class AppConfigStoreTests {
{
[TestMethod] [TestMethod]
public void LoadMissingFileReturnsDefaults() public void LoadMissingFileReturnsDefaults() {
{
using var directory = new TempDirectory(); using var directory = new TempDirectory();
var store = new AppConfigStore(Path.Combine(directory.FullPath, "app.json")); var store = new AppConfigStore(Path.Combine(directory.FullPath, "app.json"));
@@ -21,9 +19,10 @@ public class AppConfigStoreTests
Assert.AreEqual(AppConfig.CurrentFormatVersion, config.Version); Assert.AreEqual(AppConfig.CurrentFormatVersion, config.Version);
Assert.AreEqual(AppConfig.DefaultLanguage, config.Language); Assert.AreEqual(AppConfig.DefaultLanguage, config.Language);
Assert.AreEqual(ThemeOption.FollowSystem, config.Theme); Assert.AreEqual(ThemeOption.FollowSystem, config.Theme);
Assert.AreEqual(CardSortOption.Id, config.Sort.Card); Assert.AreEqual(SortOption.IdAscending, config.Display.CardSort);
Assert.AreEqual(ColumnWidthPreset.Standard, config.ColumnWidth.Preset); Assert.AreEqual(SortOption.IdAscending, config.Display.ColumnSort);
Assert.AreEqual(320, config.ColumnWidth.CustomPixels); Assert.AreEqual(ColumnWidthPreset.Standard, config.Display.ColumnWidth.Preset);
Assert.AreEqual(320, config.Display.ColumnWidth.CustomPixels);
Assert.IsTrue(config.Confirmations.DeleteCard); Assert.IsTrue(config.Confirmations.DeleteCard);
Assert.IsTrue(config.Confirmations.DeleteColumn); Assert.IsTrue(config.Confirmations.DeleteColumn);
Assert.IsTrue(config.Confirmations.DeleteTag); Assert.IsTrue(config.Confirmations.DeleteTag);
@@ -31,8 +30,7 @@ public class AppConfigStoreTests
} }
[TestMethod] [TestMethod]
public void LoadCorruptFileBacksUpAndReturnsDefaults() public void LoadCorruptFileBacksUpAndReturnsDefaults() {
{
using var directory = new TempDirectory(); using var directory = new TempDirectory();
string path = Path.Combine(directory.FullPath, "app.json"); string path = Path.Combine(directory.FullPath, "app.json");
File.WriteAllText(path, "{ this is not valid json"); File.WriteAllText(path, "{ this is not valid json");
@@ -46,8 +44,7 @@ public class AppConfigStoreTests
} }
[TestMethod] [TestMethod]
public void LoadJsonNullReturnsDefaults() public void LoadJsonNullReturnsDefaults() {
{
using var directory = new TempDirectory(); using var directory = new TempDirectory();
string path = Path.Combine(directory.FullPath, "app.json"); string path = Path.Combine(directory.FullPath, "app.json");
File.WriteAllText(path, "null"); File.WriteAllText(path, "null");
@@ -57,8 +54,40 @@ public class AppConfigStoreTests
} }
[TestMethod] [TestMethod]
public void LoadReadsKebabCaseKeysAndEnumValues() public void LoadNumericEnumValueIsRejectedAndBackedUp() {
{ using var directory = new TempDirectory();
string path = Path.Combine(directory.FullPath, "app.json");
// Integer enum values are not accepted; the file is treated like corrupt.
File.WriteAllText(path, """{ "theme": 1 }""");
var store = new AppConfigStore(path);
AppConfig config = store.Load();
Assert.AreEqual(ThemeOption.FollowSystem, config.Theme);
Assert.IsTrue(File.Exists(path + ".bak"));
}
[TestMethod]
public void LoadUnreadableFileReturnsDefaults() {
// File sharing is only reliably enforced on Windows, so this branch is exercised there.
if (!OperatingSystem.IsWindows()) {
return;
}
using var directory = new TempDirectory();
string path = Path.Combine(directory.FullPath, "app.json");
File.WriteAllText(path, """{ "version": 1 }""");
// Hold the file exclusively so the store's read fails with an I/O error.
using FileStream hold = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.None);
var store = new AppConfigStore(path);
Assert.AreEqual(AppConfig.CurrentFormatVersion, store.Load().Version);
}
[TestMethod]
public void LoadReadsKebabCaseKeysAndEnumValues() {
using var directory = new TempDirectory(); using var directory = new TempDirectory();
string path = Path.Combine(directory.FullPath, "app.json"); string path = Path.Combine(directory.FullPath, "app.json");
File.WriteAllText(path, $$""" File.WriteAllText(path, $$"""
@@ -66,8 +95,11 @@ public class AppConfigStoreTests
"version": {{AppConfig.CurrentFormatVersion}}, "version": {{AppConfig.CurrentFormatVersion}},
"language": "zh-Hans", "language": "zh-Hans",
"theme": "dark", "theme": "dark",
"sort": { "card": "title" }, "display": {
"column-width": { "preset": "custom", "custom-pixels": 400 }, "column-width": { "preset": "custom", "custom-pixels": 400 },
"card-sort": "title-asc",
"column-sort": "id-desc"
},
"confirmations": { "confirmations": {
"delete-card": false, "delete-card": false,
"delete-column": false, "delete-column": false,
@@ -82,9 +114,10 @@ public class AppConfigStoreTests
Assert.AreEqual("zh-Hans", config.Language); Assert.AreEqual("zh-Hans", config.Language);
Assert.AreEqual(ThemeOption.Dark, config.Theme); Assert.AreEqual(ThemeOption.Dark, config.Theme);
Assert.AreEqual(CardSortOption.Title, config.Sort.Card); Assert.AreEqual(SortOption.TitleAscending, config.Display.CardSort);
Assert.AreEqual(ColumnWidthPreset.Custom, config.ColumnWidth.Preset); Assert.AreEqual(SortOption.IdDescending, config.Display.ColumnSort);
Assert.AreEqual(400, config.ColumnWidth.CustomPixels); Assert.AreEqual(ColumnWidthPreset.Custom, config.Display.ColumnWidth.Preset);
Assert.AreEqual(400, config.Display.ColumnWidth.CustomPixels);
Assert.IsFalse(config.Confirmations.DeleteCard); Assert.IsFalse(config.Confirmations.DeleteCard);
Assert.IsFalse(config.Confirmations.DeleteColumn); Assert.IsFalse(config.Confirmations.DeleteColumn);
Assert.IsFalse(config.Confirmations.DeleteTag); Assert.IsFalse(config.Confirmations.DeleteTag);
@@ -92,8 +125,7 @@ public class AppConfigStoreTests
} }
[TestMethod] [TestMethod]
public void LoadMissingSectionsFillsDefaults() public void LoadMissingSectionsFillsDefaults() {
{
using var directory = new TempDirectory(); using var directory = new TempDirectory();
string path = Path.Combine(directory.FullPath, "app.json"); string path = Path.Combine(directory.FullPath, "app.json");
File.WriteAllText(path, $$"""{ "version": {{AppConfig.CurrentFormatVersion}} }"""); File.WriteAllText(path, $$"""{ "version": {{AppConfig.CurrentFormatVersion}} }""");
@@ -101,24 +133,25 @@ public class AppConfigStoreTests
AppConfig config = store.Load(); AppConfig config = store.Load();
Assert.IsNotNull(config.Sort); Assert.IsNotNull(config.Display);
Assert.IsNotNull(config.ColumnWidth); Assert.IsNotNull(config.Display.ColumnWidth);
Assert.IsNotNull(config.Confirmations); Assert.IsNotNull(config.Confirmations);
Assert.AreEqual(ColumnWidthPreset.Standard, config.ColumnWidth.Preset); Assert.AreEqual(ColumnWidthPreset.Standard, config.Display.ColumnWidth.Preset);
} }
[TestMethod] [TestMethod]
public void SaveWritesKebabCaseKeysAndEnumValues() public void SaveWritesKebabCaseKeysAndEnumValues() {
{
using var directory = new TempDirectory(); using var directory = new TempDirectory();
string path = Path.Combine(directory.FullPath, "app.json"); string path = Path.Combine(directory.FullPath, "app.json");
var store = new AppConfigStore(path); var store = new AppConfigStore(path);
var config = new AppConfig var config = new AppConfig {
{
Theme = ThemeOption.FollowSystem, Theme = ThemeOption.FollowSystem,
Sort = new SortSettings { Card = CardSortOption.UpdatedAt }, Display = new DisplaySettings {
CardSort = SortOption.UpdatedDescending,
ColumnSort = SortOption.CreatedAscending,
ColumnWidth = new ColumnWidthSettings { Preset = ColumnWidthPreset.Custom, CustomPixels = 500 }, ColumnWidth = new ColumnWidthSettings { Preset = ColumnWidthPreset.Custom, CustomPixels = 500 },
},
Confirmations = new ConfirmationSettings { DeleteColumn = false }, Confirmations = new ConfirmationSettings { DeleteColumn = false },
}; };
store.Save(config); store.Save(config);
@@ -126,27 +159,31 @@ public class AppConfigStoreTests
string json = File.ReadAllText(path); string json = File.ReadAllText(path);
StringAssert.Contains(json, "\"delete-column\""); StringAssert.Contains(json, "\"delete-column\"");
StringAssert.Contains(json, "\"discard-edit\""); StringAssert.Contains(json, "\"discard-edit\"");
StringAssert.Contains(json, "\"card-sort\"");
StringAssert.Contains(json, "\"column-sort\"");
StringAssert.Contains(json, "\"custom-pixels\""); StringAssert.Contains(json, "\"custom-pixels\"");
StringAssert.Contains(json, "\"follow-system\""); StringAssert.Contains(json, "\"follow-system\"");
StringAssert.Contains(json, "\"updated-at\""); StringAssert.Contains(json, "\"updated-desc\"");
StringAssert.Contains(json, "\"created-asc\"");
// No member-name CamelCase must leak into the file. // No member-name CamelCase must leak into the file.
Assert.IsFalse(json.Contains("deleteColumn", StringComparison.Ordinal)); Assert.IsFalse(json.Contains("deleteColumn", StringComparison.Ordinal));
Assert.IsFalse(json.Contains("CustomPixels", StringComparison.Ordinal)); Assert.IsFalse(json.Contains("CustomPixels", StringComparison.Ordinal));
} }
[TestMethod] [TestMethod]
public void SaveThenLoadRoundTrips() public void SaveThenLoadRoundTrips() {
{
using var directory = new TempDirectory(); using var directory = new TempDirectory();
string path = Path.Combine(directory.FullPath, "app.json"); string path = Path.Combine(directory.FullPath, "app.json");
var store = new AppConfigStore(path); var store = new AppConfigStore(path);
var config = new AppConfig var config = new AppConfig {
{
Language = "zh-Hans", Language = "zh-Hans",
Theme = ThemeOption.Light, Theme = ThemeOption.Light,
Sort = new SortSettings { Card = CardSortOption.Title }, Display = new DisplaySettings {
CardSort = SortOption.CreatedDescending,
ColumnSort = SortOption.TitleAscending,
ColumnWidth = new ColumnWidthSettings { Preset = ColumnWidthPreset.Wide }, ColumnWidth = new ColumnWidthSettings { Preset = ColumnWidthPreset.Wide },
},
Confirmations = new ConfirmationSettings { DiscardEdit = false }, Confirmations = new ConfirmationSettings { DiscardEdit = false },
}; };
store.Save(config); store.Save(config);
@@ -154,152 +191,9 @@ public class AppConfigStoreTests
AppConfig reloaded = store.Load(); AppConfig reloaded = store.Load();
Assert.AreEqual(config.Language, reloaded.Language); Assert.AreEqual(config.Language, reloaded.Language);
Assert.AreEqual(config.Theme, reloaded.Theme); Assert.AreEqual(config.Theme, reloaded.Theme);
Assert.AreEqual(config.Sort.Card, reloaded.Sort.Card); Assert.AreEqual(config.Display.CardSort, reloaded.Display.CardSort);
Assert.AreEqual(config.ColumnWidth.Preset, reloaded.ColumnWidth.Preset); Assert.AreEqual(config.Display.ColumnSort, reloaded.Display.ColumnSort);
Assert.AreEqual(config.Display.ColumnWidth.Preset, reloaded.Display.ColumnWidth.Preset);
Assert.AreEqual(config.Confirmations.DiscardEdit, reloaded.Confirmations.DiscardEdit); Assert.AreEqual(config.Confirmations.DiscardEdit, reloaded.Confirmations.DiscardEdit);
} }
[TestMethod]
public void LoadNonObjectRootBacksUpAndReturnsDefaults()
{
using var directory = new TempDirectory();
string path = Path.Combine(directory.FullPath, "app.json");
File.WriteAllText(path, "[1, 2]");
var store = new AppConfigStore(path);
Assert.AreEqual(AppConfig.DefaultLanguage, store.Load().Language);
Assert.AreEqual("[1, 2]", File.ReadAllText(path + ".bak"));
}
[TestMethod]
[DataRow("\"theme\": \"sepia\"")]
[DataRow("\"theme\": 1")]
[DataRow("\"theme\": {}")]
[DataRow("\"language\": \"fr\"")]
[DataRow("\"language\": \"zh-hans\"")]
[DataRow("\"language\": 5")]
[DataRow("\"sort\": { \"card\": \"created-at\" }")]
[DataRow("\"sort\": 7")]
[DataRow("\"column-width\": { \"preset\": \"huge\", \"custom-pixels\": 159 }")]
[DataRow("\"column-width\": { \"custom-pixels\": 721 }")]
[DataRow("\"column-width\": { \"custom-pixels\": \"wide\" }")]
[DataRow("\"confirmations\": { \"delete-card\": \"nope\" }")]
[DataRow("\"version\": \"one\"")]
public void InvalidFieldFallsBackAloneWithoutBackup(string invalidMember)
{
using var directory = new TempDirectory();
string path = Path.Combine(directory.FullPath, "app.json");
// The valid fields are non-defaults, so any whole-file fallback would show.
File.WriteAllText(path, $$"""
{
"theme": "dark",
"confirmations": { "discard-edit": false },
{{invalidMember}}
}
""");
var store = new AppConfigStore(path);
AppConfig config = store.Load();
Assert.IsFalse(File.Exists(path + ".bak"));
AppConfig defaults = new();
Assert.AreEqual(invalidMember.Contains("theme") ? defaults.Theme : ThemeOption.Dark, config.Theme);
if (!invalidMember.Contains("confirmations"))
{
Assert.IsFalse(config.Confirmations.DiscardEdit);
}
Assert.AreEqual(defaults.Language, config.Language);
Assert.AreEqual(defaults.Sort.Card, config.Sort.Card);
Assert.AreEqual(defaults.ColumnWidth.Preset, config.ColumnWidth.Preset);
Assert.AreEqual(defaults.ColumnWidth.CustomPixels, config.ColumnWidth.CustomPixels);
Assert.AreEqual(defaults.Confirmations.DeleteCard, config.Confirmations.DeleteCard);
Assert.AreEqual(defaults.Version, config.Version);
}
[TestMethod]
public void InvalidNestedFieldKeepsItsSiblings()
{
using var directory = new TempDirectory();
string path = Path.Combine(directory.FullPath, "app.json");
File.WriteAllText(path, """{ "column-width": { "preset": "bogus", "custom-pixels": 500 } }""");
AppConfig config = new AppConfigStore(path).Load();
Assert.AreEqual(ColumnWidthPreset.Standard, config.ColumnWidth.Preset);
Assert.AreEqual(500, config.ColumnWidth.CustomPixels);
}
[TestMethod]
public void ColumnWidthBoundsAreInclusive()
{
using var directory = new TempDirectory();
string path = Path.Combine(directory.FullPath, "app.json");
File.WriteAllText(path, """{ "column-width": { "custom-pixels": 160 } }""");
Assert.AreEqual(160, new AppConfigStore(path).Load().ColumnWidth.CustomPixels);
File.WriteAllText(path, """{ "column-width": { "custom-pixels": 720 } }""");
Assert.AreEqual(720, new AppConfigStore(path).Load().ColumnWidth.CustomPixels);
}
[TestMethod]
public void UnchangedConfigurationIsNotWritten()
{
using var directory = new TempDirectory();
string path = Path.Combine(directory.FullPath, "app.json");
var store = new AppConfigStore(path);
AppConfig config = store.Load();
Assert.IsFalse(store.SaveIfChanged(config));
Assert.IsFalse(File.Exists(path));
}
[TestMethod]
public void FieldFallbackAloneDoesNotRewriteTheFile()
{
using var directory = new TempDirectory();
string path = Path.Combine(directory.FullPath, "app.json");
const string original = """{ "theme": "sepia" }""";
File.WriteAllText(path, original);
var store = new AppConfigStore(path);
AppConfig config = store.Load();
Assert.IsFalse(store.SaveIfChanged(config));
Assert.AreEqual(original, File.ReadAllText(path));
}
[TestMethod]
public void ChangedConfigurationIsWrittenOnce()
{
using var directory = new TempDirectory();
string path = Path.Combine(directory.FullPath, "app.json");
var store = new AppConfigStore(path);
AppConfig config = store.Load();
config.Sort.Card = CardSortOption.UpdatedAt;
Assert.IsTrue(store.SaveIfChanged(config));
Assert.AreEqual(CardSortOption.UpdatedAt, new AppConfigStore(path).Load().Sort.Card);
// Saved state is the new baseline.
Assert.IsFalse(store.SaveIfChanged(config));
}
[TestMethod]
public void ChangeRevertedWithinSessionIsNotWritten()
{
using var directory = new TempDirectory();
string path = Path.Combine(directory.FullPath, "app.json");
var store = new AppConfigStore(path);
AppConfig config = store.Load();
config.Theme = ThemeOption.Dark;
config.Theme = ThemeOption.FollowSystem;
Assert.IsFalse(store.SaveIfChanged(config));
Assert.IsFalse(File.Exists(path));
}
} }
+9 -16
View File
@@ -1,4 +1,5 @@
using Microsoft.Data.Sqlite; using Microsoft.Data.Sqlite;
using YKanBan.Storage; using YKanBan.Storage;
using YKanBan.Storage.Workspace; using YKanBan.Storage.Workspace;
using YKanBan.Tests.TestUtilities; using YKanBan.Tests.TestUtilities;
@@ -10,11 +11,9 @@ namespace YKanBan.Tests.Storage;
/// user_version-driven migration runner. /// user_version-driven migration runner.
/// </summary> /// </summary>
[TestClass] [TestClass]
public class SqliteDatabaseTests public class SqliteDatabaseTests {
{
[TestMethod] [TestMethod]
public void OpenAppliesMandatoryPragmas() public void OpenAppliesMandatoryPragmas() {
{
using var directory = new TempDirectory(); using var directory = new TempDirectory();
string databasePath = Path.Combine(directory.FullPath, "pragmas.db"); string databasePath = Path.Combine(directory.FullPath, "pragmas.db");
@@ -25,8 +24,7 @@ public class SqliteDatabaseTests
} }
[TestMethod] [TestMethod]
public void OpenSetsUserVersionToLatestMigration() public void OpenSetsUserVersionToLatestMigration() {
{
using var directory = new TempDirectory(); using var directory = new TempDirectory();
string databasePath = Path.Combine(directory.FullPath, "version.db"); string databasePath = Path.Combine(directory.FullPath, "version.db");
@@ -35,13 +33,11 @@ public class SqliteDatabaseTests
} }
[TestMethod] [TestMethod]
public void ReopenKeepsWalJournalMode() public void ReopenKeepsWalJournalMode() {
{
using var directory = new TempDirectory(); using var directory = new TempDirectory();
string databasePath = Path.Combine(directory.FullPath, "wal.db"); string databasePath = Path.Combine(directory.FullPath, "wal.db");
using (SqliteConnection connection = SqliteDatabase.Open(databasePath, WorkspaceSchema.Migrations)) using (SqliteConnection connection = SqliteDatabase.Open(databasePath, WorkspaceSchema.Migrations)) {
{
} }
// WAL mode is stored in the database header, so a fresh connection keeps it. // WAL mode is stored in the database header, so a fresh connection keeps it.
@@ -50,14 +46,12 @@ public class SqliteDatabaseTests
} }
[TestMethod] [TestMethod]
public void OpenRejectsNewerStoredSchemaVersion() public void OpenRejectsNewerStoredSchemaVersion() {
{
using var directory = new TempDirectory(); using var directory = new TempDirectory();
string databasePath = Path.Combine(directory.FullPath, "newer.db"); string databasePath = Path.Combine(directory.FullPath, "newer.db");
long newerVersion = WorkspaceSchema.CurrentVersion + 1; long newerVersion = WorkspaceSchema.CurrentVersion + 1;
using (SqliteConnection connection = SqliteDatabase.Open(databasePath, WorkspaceSchema.Migrations)) using (SqliteConnection connection = SqliteDatabase.Open(databasePath, WorkspaceSchema.Migrations)) {
{
SqliteTestHelper.Exec(connection, $"PRAGMA user_version={newerVersion};"); SqliteTestHelper.Exec(connection, $"PRAGMA user_version={newerVersion};");
} }
@@ -68,8 +62,7 @@ public class SqliteDatabaseTests
} }
[TestMethod] [TestMethod]
public void OpenRejectsNonContiguousMigrationList() public void OpenRejectsNonContiguousMigrationList() {
{
using var directory = new TempDirectory(); using var directory = new TempDirectory();
string databasePath = Path.Combine(directory.FullPath, "gap.db"); string databasePath = Path.Combine(directory.FullPath, "gap.db");
@@ -1,4 +1,5 @@
using Microsoft.Data.Sqlite; using Microsoft.Data.Sqlite;
using YKanBan.Storage; using YKanBan.Storage;
using YKanBan.Storage.Workspace; using YKanBan.Storage.Workspace;
using YKanBan.Tests.TestUtilities; using YKanBan.Tests.TestUtilities;
@@ -11,11 +12,9 @@ namespace YKanBan.Tests.Storage.Workspace;
/// content. /// content.
/// </summary> /// </summary>
[TestClass] [TestClass]
public class WorkspaceInitializerTests public class WorkspaceInitializerTests {
{
[TestMethod] [TestMethod]
public void IsWorkspaceReflectsInitializationState() public void IsWorkspaceReflectsInitializationState() {
{
using var directory = new TempDirectory(); using var directory = new TempDirectory();
Assert.IsFalse(WorkspaceInitializer.IsWorkspace(directory.FullPath)); Assert.IsFalse(WorkspaceInitializer.IsWorkspace(directory.FullPath));
@@ -24,8 +23,7 @@ public class WorkspaceInitializerTests
} }
[TestMethod] [TestMethod]
public void InitializeCreatesStructureAndMigratedEmptyDatabase() public void InitializeCreatesStructureAndMigratedEmptyDatabase() {
{
using var directory = new TempDirectory(); using var directory = new TempDirectory();
WorkspaceInitializer.Initialize(directory.FullPath); WorkspaceInitializer.Initialize(directory.FullPath);
@@ -43,8 +41,7 @@ public class WorkspaceInitializerTests
} }
[TestMethod] [TestMethod]
public void InitializeMissingFolderThrows() public void InitializeMissingFolderThrows() {
{
using var directory = new TempDirectory(); using var directory = new TempDirectory();
string missing = Path.Combine(directory.FullPath, "not-created"); string missing = Path.Combine(directory.FullPath, "not-created");
@@ -54,8 +51,7 @@ public class WorkspaceInitializerTests
} }
[TestMethod] [TestMethod]
public void InitializeTwiceThrows() public void InitializeTwiceThrows() {
{
using var directory = new TempDirectory(); using var directory = new TempDirectory();
WorkspaceInitializer.Initialize(directory.FullPath); WorkspaceInitializer.Initialize(directory.FullPath);
@@ -5,14 +5,12 @@ using YKanBan.Tests.TestUtilities;
namespace YKanBan.Tests.Storage.Workspace; namespace YKanBan.Tests.Storage.Workspace;
/// <summary> /// <summary>
/// Tests for exclusive lock acquisition, diagnostics and release. /// Tests for exclusive lock acquisition and release.
/// </summary> /// </summary>
[TestClass] [TestClass]
public class WorkspaceLockTests public class WorkspaceLockTests {
{
[TestMethod] [TestMethod]
public void AcquireThenDisposeThenAcquireAgainSucceeds() public void AcquireThenDisposeThenAcquireAgainSucceeds() {
{
using var directory = new TempDirectory(); using var directory = new TempDirectory();
WorkspaceInitializer.Initialize(directory.FullPath); WorkspaceInitializer.Initialize(directory.FullPath);
@@ -22,8 +20,7 @@ public class WorkspaceLockTests
} }
[TestMethod] [TestMethod]
public void SecondAcquireWhileHeldThrows() public void SecondAcquireWhileHeldThrows() {
{
using var directory = new TempDirectory(); using var directory = new TempDirectory();
WorkspaceInitializer.Initialize(directory.FullPath); WorkspaceInitializer.Initialize(directory.FullPath);
@@ -34,26 +31,21 @@ public class WorkspaceLockTests
} }
[TestMethod] [TestMethod]
public void AcquireWithoutYkanbanThrowsNotInitialized() public void AcquireWithoutYkanbanThrowsNotInitialized() {
{
using var directory = new TempDirectory(); using var directory = new TempDirectory();
Assert.ThrowsExactly<WorkspaceNotInitializedException>( Assert.ThrowsExactly<WorkspaceNotInitializedException>(
() => WorkspaceLock.Acquire(directory.FullPath)); () => WorkspaceLock.Acquire(directory.FullPath));
} }
[TestMethod] [TestMethod]
public void LockFileContainsHolderDiagnosticsAfterRelease() public void LockFileIsEmptyAfterRelease() {
{
using var directory = new TempDirectory(); using var directory = new TempDirectory();
WorkspaceInitializer.Initialize(directory.FullPath); WorkspaceInitializer.Initialize(directory.FullPath);
using (WorkspaceLock.Acquire(directory.FullPath)) using (WorkspaceLock.Acquire(directory.FullPath)) {
{
} }
// The file survives release and carries PID / machine name / time for humans. // The lock file survives release but carries no content; only the OS handle matters.
string content = File.ReadAllText(WorkspacePaths.LockFile(directory.FullPath)); Assert.AreEqual(0L, new FileInfo(WorkspacePaths.LockFile(directory.FullPath)).Length);
StringAssert.Contains(content, "pid=");
StringAssert.Contains(content, $"machine={Environment.MachineName}");
} }
} }
@@ -1,98 +1,139 @@
using System.Globalization; using System.Globalization;
using Microsoft.Data.Sqlite; using Microsoft.Data.Sqlite;
using YKanBan.Storage.Workspace; using YKanBan.Storage.Workspace;
using YKanBan.Tests.TestUtilities; using YKanBan.Tests.TestUtilities;
namespace YKanBan.Tests.Storage.Workspace; namespace YKanBan.Tests.Storage.Workspace;
/// <summary> /// <summary>
/// Verifies that the preset column titles follow the UI language active when /// Verifies that the preset columns and tags follow the UI language active when
/// they are added and then live as ordinary data. These tests mutate the /// they are added and then live as ordinary data. These tests mutate the global
/// global <see cref="Resources.Culture"/>, so they are marked do-not-parallelize. /// <see cref="Resources.Culture"/>, so they are marked do-not-parallelize.
/// </summary> /// </summary>
[TestClass] [TestClass]
[DoNotParallelize] [DoNotParallelize]
public class WorkspacePresetTests public class WorkspacePresetTests {
{
[TestMethod] [TestMethod]
public void AddPresetColumnsStoresEnglishTitlesUnderEnglishCulture() public void AddPresetColumnsStoresEnglishTextUnderEnglishCulture() {
{
CultureInfo? original = Resources.Culture; CultureInfo? original = Resources.Culture;
try try {
{
Resources.Culture = new CultureInfo("en"); Resources.Culture = new CultureInfo("en");
string[] expected =
[
Resources.PresetColumn_Todo,
Resources.PresetColumn_InProgress,
Resources.PresetColumn_Done,
];
using var directory = new TempDirectory(); using var directory = new TempDirectory();
WorkspaceInitializer.Initialize(directory.FullPath); WorkspaceInitializer.Initialize(directory.FullPath);
WorkspacePreset.AddPresetColumns(directory.FullPath); WorkspacePreset.AddPresetColumns(directory.FullPath);
using SqliteConnection connection = SqliteTestHelper.OpenWorkspace(directory.FullPath); using SqliteConnection connection = SqliteTestHelper.OpenWorkspace(directory.FullPath);
CollectionAssert.AreEqual(expected, SqliteTestHelper.GetColumnTitles(connection)); CollectionAssert.AreEqual(
} new[]
finally
{ {
Resources.PresetColumn_Todo,
Resources.PresetColumn_InProgress,
Resources.PresetColumn_Done,
},
SqliteTestHelper.GetColumnTitles(connection));
CollectionAssert.AreEqual(
new[]
{
Resources.PresetColumn_Todo_Description,
Resources.PresetColumn_InProgress_Description,
Resources.PresetColumn_Done_Description,
},
SqliteTestHelper.GetColumnDescriptions(connection));
} finally {
Resources.Culture = original; Resources.Culture = original;
} }
} }
[TestMethod] [TestMethod]
public void AddPresetColumnsStoresChineseTitlesUnderChineseCulture() public void AddPresetColumnsStoresChineseTextUnderChineseCulture() {
{
CultureInfo? original = Resources.Culture; CultureInfo? original = Resources.Culture;
try try {
{
Resources.Culture = new CultureInfo("zh-Hans"); Resources.Culture = new CultureInfo("zh-Hans");
string[] expected =
[
Resources.PresetColumn_Todo,
Resources.PresetColumn_InProgress,
Resources.PresetColumn_Done,
];
using var directory = new TempDirectory(); using var directory = new TempDirectory();
WorkspaceInitializer.Initialize(directory.FullPath); WorkspaceInitializer.Initialize(directory.FullPath);
WorkspacePreset.AddPresetColumns(directory.FullPath); WorkspacePreset.AddPresetColumns(directory.FullPath);
using SqliteConnection connection = SqliteTestHelper.OpenWorkspace(directory.FullPath); using SqliteConnection connection = SqliteTestHelper.OpenWorkspace(directory.FullPath);
CollectionAssert.AreEqual(expected, SqliteTestHelper.GetColumnTitles(connection)); CollectionAssert.AreEqual(
} new[]
finally
{ {
Resources.PresetColumn_Todo,
Resources.PresetColumn_InProgress,
Resources.PresetColumn_Done,
},
SqliteTestHelper.GetColumnTitles(connection));
// Chinese resources must resolve to different text than English.
Assert.AreEqual("待办", Resources.PresetColumn_Todo);
Assert.AreEqual("已完成的任务。", Resources.PresetColumn_Done_Description);
} finally {
Resources.Culture = original; Resources.Culture = original;
} }
} }
[TestMethod] [TestMethod]
public void PresetTitlesAreDataAndIgnoreLaterCultureChanges() public void AddPresetTagsStoresEightTagsUnderEnglishCulture() {
{
CultureInfo? original = Resources.Culture; CultureInfo? original = Resources.Culture;
try try {
{ Resources.Culture = new CultureInfo("en");
using var directory = new TempDirectory();
WorkspaceInitializer.Initialize(directory.FullPath);
WorkspacePreset.AddPresetTags(directory.FullPath);
using SqliteConnection connection = SqliteTestHelper.OpenWorkspace(directory.FullPath);
List<(string Name, string Color, string Description)> tags = SqliteTestHelper.GetTags(connection);
Assert.AreEqual(8, tags.Count);
Assert.AreEqual(("bug", "#d73a4a", "Something isn't working"), tags[0]);
Assert.AreEqual(("documentation", "#0075ca", "Improvements or additions to documentation"), tags[1]);
Assert.AreEqual(("wontfix", "#ffffff", "This will not be worked on"), tags[7]);
} finally {
Resources.Culture = original;
}
}
[TestMethod]
public void AddPresetTagsStoresChineseNamesUnderChineseCulture() {
CultureInfo? original = Resources.Culture;
try {
Resources.Culture = new CultureInfo("zh-Hans");
using var directory = new TempDirectory();
WorkspaceInitializer.Initialize(directory.FullPath);
WorkspacePreset.AddPresetTags(directory.FullPath);
using SqliteConnection connection = SqliteTestHelper.OpenWorkspace(directory.FullPath);
List<(string Name, string Color, string Description)> tags = SqliteTestHelper.GetTags(connection);
Assert.AreEqual(8, tags.Count);
Assert.AreEqual("缺陷", tags[0].Name);
Assert.AreEqual("功能没有正常工作", tags[0].Description);
} finally {
Resources.Culture = original;
}
}
[TestMethod]
public void PresetContentIsDataAndIgnoresLaterCultureChanges() {
CultureInfo? original = Resources.Culture;
try {
Resources.Culture = new CultureInfo("en"); Resources.Culture = new CultureInfo("en");
string[] expected =
[
Resources.PresetColumn_Todo,
Resources.PresetColumn_InProgress,
Resources.PresetColumn_Done,
];
using var directory = new TempDirectory(); using var directory = new TempDirectory();
WorkspaceInitializer.Initialize(directory.FullPath); WorkspaceInitializer.Initialize(directory.FullPath);
WorkspacePreset.AddPresetColumns(directory.FullPath); WorkspacePreset.AddPresetColumns(directory.FullPath);
WorkspacePreset.AddPresetTags(directory.FullPath);
// Switching the language after adding the presets must not rewrite stored data. // Switching the language after adding the presets must not rewrite stored data.
Resources.Culture = new CultureInfo("zh-Hans"); Resources.Culture = new CultureInfo("zh-Hans");
using SqliteConnection connection = SqliteTestHelper.OpenWorkspace(directory.FullPath); using SqliteConnection connection = SqliteTestHelper.OpenWorkspace(directory.FullPath);
CollectionAssert.AreEqual(expected, SqliteTestHelper.GetColumnTitles(connection)); Assert.AreEqual("To Do", SqliteTestHelper.GetColumnTitles(connection)[0]);
} Assert.AreEqual("bug", SqliteTestHelper.GetTags(connection)[0].Name);
finally } finally {
{
Resources.Culture = original; Resources.Culture = original;
} }
} }
@@ -1,7 +1,7 @@
using Microsoft.Data.Sqlite; using Microsoft.Data.Sqlite;
using YKanBan.Models; using YKanBan.Models;
using YKanBan.Search; using YKanBan.Search;
using YKanBan.Storage;
using YKanBan.Storage.Workspace; using YKanBan.Storage.Workspace;
using YKanBan.Tests.TestUtilities; using YKanBan.Tests.TestUtilities;
@@ -12,16 +12,14 @@ namespace YKanBan.Tests.Storage.Workspace;
/// transaction atomicity and the timestamp refresh rules. /// transaction atomicity and the timestamp refresh rules.
/// </summary> /// </summary>
[TestClass] [TestClass]
public class WorkspaceRepositoryTests public class WorkspaceRepositoryTests {
{
/// <summary> /// <summary>
/// Owns a workspace with fixed-timestamp fixture data (one column, one /// Owns a workspace with fixed-timestamp fixture data (one column, one
/// card, two tags linked to the card) plus the repository under test. /// card, two tags linked to the card) plus the repository under test.
/// Fixture timestamps are small literal values so that any real write, /// Fixture timestamps are small literal values so that any real write,
/// which stamps the current Unix time, is observable. /// which stamps the current Unix time, is observable.
/// </summary> /// </summary>
private sealed class RepositoryFixture : IDisposable private sealed class RepositoryFixture : IDisposable {
{
public TempDirectory Directory { get; } = new(); public TempDirectory Directory { get; } = new();
public WorkspaceRepository Repository { get; } public WorkspaceRepository Repository { get; }
@@ -34,12 +32,10 @@ public class WorkspaceRepositoryTests
public long UiTagId { get; } = 2; public long UiTagId { get; } = 2;
public RepositoryFixture() public RepositoryFixture() {
{
WorkspaceInitializer.Initialize(Directory.FullPath); WorkspaceInitializer.Initialize(Directory.FullPath);
using (SqliteConnection connection = SqliteTestHelper.OpenWorkspace(Directory.FullPath)) using (SqliteConnection connection = SqliteTestHelper.OpenWorkspace(Directory.FullPath)) {
{
SqliteTestHelper.Exec(connection, "INSERT INTO columns (title, description, created_at, updated_at) VALUES ('Col', '', 100, 100);"); SqliteTestHelper.Exec(connection, "INSERT INTO columns (title, description, created_at, updated_at) VALUES ('Col', '', 100, 100);");
SqliteTestHelper.Exec(connection, "INSERT INTO cards (column_id, title, content, created_at, updated_at) VALUES (1, 'T', 'C', 100, 100);"); SqliteTestHelper.Exec(connection, "INSERT INTO cards (column_id, title, content, created_at, updated_at) VALUES (1, 'T', 'C', 100, 100);");
SqliteTestHelper.Exec(connection, "INSERT INTO tags (name, color, description) VALUES ('bug', '#ff0000', '');"); SqliteTestHelper.Exec(connection, "INSERT INTO tags (name, color, description) VALUES ('bug', '#ff0000', '');");
@@ -51,16 +47,14 @@ public class WorkspaceRepositoryTests
Repository = new WorkspaceRepository(Directory.FullPath); Repository = new WorkspaceRepository(Directory.FullPath);
} }
public void Dispose() public void Dispose() {
{
Repository.Dispose(); Repository.Dispose();
Directory.Dispose(); Directory.Dispose();
} }
} }
[TestMethod] [TestMethod]
public void GetColumnsReturnsTheSeededColumn() public void GetColumnsReturnsTheSeededColumn() {
{
using var fixture = new RepositoryFixture(); using var fixture = new RepositoryFixture();
ColumnModel column = fixture.Repository.GetColumn(fixture.ColumnId)!; ColumnModel column = fixture.Repository.GetColumn(fixture.ColumnId)!;
Assert.AreEqual("Col", column.Title); Assert.AreEqual("Col", column.Title);
@@ -68,8 +62,7 @@ public class WorkspaceRepositoryTests
} }
[TestMethod] [TestMethod]
public void AddColumnSetsEqualTimestamps() public void AddColumnSetsEqualTimestamps() {
{
using var fixture = new RepositoryFixture(); using var fixture = new RepositoryFixture();
ColumnModel column = fixture.Repository.AddColumn("New", "desc"); ColumnModel column = fixture.Repository.AddColumn("New", "desc");
Assert.IsTrue(column.CreatedAt > 0L); Assert.IsTrue(column.CreatedAt > 0L);
@@ -77,8 +70,7 @@ public class WorkspaceRepositoryTests
} }
[TestMethod] [TestMethod]
public void UpdateColumnWithoutChangeWritesNothing() public void UpdateColumnWithoutChangeWritesNothing() {
{
using var fixture = new RepositoryFixture(); using var fixture = new RepositoryFixture();
ColumnModel result = fixture.Repository.UpdateColumn(fixture.ColumnId, "Col", ""); ColumnModel result = fixture.Repository.UpdateColumn(fixture.ColumnId, "Col", "");
@@ -88,8 +80,7 @@ public class WorkspaceRepositoryTests
} }
[TestMethod] [TestMethod]
public void UpdateColumnChangeRefreshesTimestamp() public void UpdateColumnChangeRefreshesTimestamp() {
{
using var fixture = new RepositoryFixture(); using var fixture = new RepositoryFixture();
ColumnModel updated = fixture.Repository.UpdateColumn(fixture.ColumnId, "Col2", "desc"); ColumnModel updated = fixture.Repository.UpdateColumn(fixture.ColumnId, "Col2", "desc");
@@ -99,8 +90,7 @@ public class WorkspaceRepositoryTests
} }
[TestMethod] [TestMethod]
public void DeleteColumnCascadesToCardsAndTagLinks() public void DeleteColumnCascadesToCardsAndTagLinks() {
{
using var fixture = new RepositoryFixture(); using var fixture = new RepositoryFixture();
Assert.IsTrue(fixture.Repository.DeleteColumn(fixture.ColumnId)); Assert.IsTrue(fixture.Repository.DeleteColumn(fixture.ColumnId));
@@ -113,8 +103,7 @@ public class WorkspaceRepositoryTests
} }
[TestMethod] [TestMethod]
public void DeleteCardRemovesTagLinksButKeepsTags() public void DeleteCardRemovesTagLinksButKeepsTags() {
{
using var fixture = new RepositoryFixture(); using var fixture = new RepositoryFixture();
Assert.IsTrue(fixture.Repository.DeleteCard(fixture.CardId)); Assert.IsTrue(fixture.Repository.DeleteCard(fixture.CardId));
@@ -126,8 +115,7 @@ public class WorkspaceRepositoryTests
} }
[TestMethod] [TestMethod]
public void DeleteTagDetachesFromCardsButKeepsCards() public void DeleteTagDetachesFromCardsButKeepsCards() {
{
using var fixture = new RepositoryFixture(); using var fixture = new RepositoryFixture();
Assert.IsTrue(fixture.Repository.DeleteTag(fixture.BugTagId)); Assert.IsTrue(fixture.Repository.DeleteTag(fixture.BugTagId));
@@ -139,8 +127,7 @@ public class WorkspaceRepositoryTests
} }
[TestMethod] [TestMethod]
public void UpdateCardWithoutEffectiveChangeWritesNothing() public void UpdateCardWithoutEffectiveChangeWritesNothing() {
{
using var fixture = new RepositoryFixture(); using var fixture = new RepositoryFixture();
CardModel result = fixture.Repository.UpdateCard( CardModel result = fixture.Repository.UpdateCard(
@@ -150,8 +137,7 @@ public class WorkspaceRepositoryTests
} }
[TestMethod] [TestMethod]
public void UpdateCardTitleChangeRefreshesTimestamp() public void UpdateCardTitleChangeRefreshesTimestamp() {
{
using var fixture = new RepositoryFixture(); using var fixture = new RepositoryFixture();
CardModel updated = fixture.Repository.UpdateCard( CardModel updated = fixture.Repository.UpdateCard(
@@ -162,8 +148,7 @@ public class WorkspaceRepositoryTests
} }
[TestMethod] [TestMethod]
public void UpdateCardTagSetOnlyChangeStillRefreshesTimestamp() public void UpdateCardTagSetOnlyChangeStillRefreshesTimestamp() {
{
using var fixture = new RepositoryFixture(); using var fixture = new RepositoryFixture();
CardModel updated = fixture.Repository.UpdateCard(fixture.CardId, "T", "C", [fixture.BugTagId]); CardModel updated = fixture.Repository.UpdateCard(fixture.CardId, "T", "C", [fixture.BugTagId]);
@@ -173,8 +158,7 @@ public class WorkspaceRepositoryTests
} }
[TestMethod] [TestMethod]
public void UpdateCardWithUnknownTagRollsBackAtomically() public void UpdateCardWithUnknownTagRollsBackAtomically() {
{
using var fixture = new RepositoryFixture(); using var fixture = new RepositoryFixture();
// Tag 999 does not exist: the FK fires mid-transaction and the whole edit must roll back. // Tag 999 does not exist: the FK fires mid-transaction and the whole edit must roll back.
@@ -189,8 +173,7 @@ public class WorkspaceRepositoryTests
} }
[TestMethod] [TestMethod]
public void MoveCardUpdatesColumnWithoutRefreshingTimestamp() public void MoveCardUpdatesColumnWithoutRefreshingTimestamp() {
{
using var fixture = new RepositoryFixture(); using var fixture = new RepositoryFixture();
long target = fixture.Repository.AddColumn("Target", "").Id; long target = fixture.Repository.AddColumn("Target", "").Id;
@@ -203,8 +186,7 @@ public class WorkspaceRepositoryTests
} }
[TestMethod] [TestMethod]
public void MoveCardToCurrentColumnIsNoOp() public void MoveCardToCurrentColumnIsNoOp() {
{
using var fixture = new RepositoryFixture(); using var fixture = new RepositoryFixture();
Assert.IsFalse(fixture.Repository.MoveCard(fixture.CardId, fixture.ColumnId)); Assert.IsFalse(fixture.Repository.MoveCard(fixture.CardId, fixture.ColumnId));
@@ -213,8 +195,7 @@ public class WorkspaceRepositoryTests
} }
[TestMethod] [TestMethod]
public void AddCardCreatesWithEqualTimestampsAndLinkedTags() public void AddCardCreatesWithEqualTimestampsAndLinkedTags() {
{
using var fixture = new RepositoryFixture(); using var fixture = new RepositoryFixture();
CardModel card = fixture.Repository.AddCard(fixture.ColumnId, "N", "body", [fixture.UiTagId]); CardModel card = fixture.Repository.AddCard(fixture.ColumnId, "N", "body", [fixture.UiTagId]);
@@ -226,8 +207,7 @@ public class WorkspaceRepositoryTests
} }
[TestMethod] [TestMethod]
public void UpdateTagWithoutChangeWritesNothing() public void UpdateTagWithoutChangeWritesNothing() {
{
using var fixture = new RepositoryFixture(); using var fixture = new RepositoryFixture();
TagModel result = fixture.Repository.UpdateTag( TagModel result = fixture.Repository.UpdateTag(
@@ -238,8 +218,7 @@ public class WorkspaceRepositoryTests
} }
[TestMethod] [TestMethod]
public void UpdateTagChangeWrites() public void UpdateTagChangeWrites() {
{
using var fixture = new RepositoryFixture(); using var fixture = new RepositoryFixture();
TagModel updated = fixture.Repository.UpdateTag( TagModel updated = fixture.Repository.UpdateTag(
@@ -252,95 +231,24 @@ public class WorkspaceRepositoryTests
} }
[TestMethod] [TestMethod]
public void AddTagWithDuplicateNameIsRejected() public void AddTagWithDuplicateNameIsRejected() {
{
using var fixture = new RepositoryFixture(); using var fixture = new RepositoryFixture();
DuplicateNameException exception = Assert.ThrowsExactly<DuplicateNameException>(() => Assert.ThrowsExactly<SqliteException>(() =>
fixture.Repository.AddTag("BUG", RgbColor.Parse("#123456"), "")); fixture.Repository.AddTag("bug", RgbColor.Parse("#123456"), ""));
Assert.AreEqual(NamedEntity.Tag, exception.Entity);
Assert.AreEqual("BUG", exception.Name);
Assert.AreEqual(2, fixture.Repository.GetTags().Count);
} }
[TestMethod] [TestMethod]
public void AddTagWithEmptyNameIsRejected() public void GetCardIdsMatchingRunsTheCompiledSearch() {
{
using var fixture = new RepositoryFixture(); using var fixture = new RepositoryFixture();
NameRequiredException exception = Assert.ThrowsExactly<NameRequiredException>(() => CompiledSearch compiled = SearchSqlCompiler.Compile(new SearchNode.FreeText("T"));
fixture.Repository.AddTag("", RgbColor.Parse("#123456"), ""));
Assert.AreEqual(NamedEntity.Tag, exception.Entity); IReadOnlyCollection<long> ids = fixture.Repository.GetCardIdsMatching(compiled);
CollectionAssert.AreEquivalent(new[] { fixture.CardId }, ids.ToList());
} }
[TestMethod] [TestMethod]
public void UpdateTagToExistingNameIsRejectedAndKeepsTheRow() public void GetTagsWithUsageCountsAssignments() {
{
using var fixture = new RepositoryFixture();
Assert.ThrowsExactly<DuplicateNameException>(() =>
fixture.Repository.UpdateTag(fixture.UiTagId, "Bug", RgbColor.Parse("#00ff00"), ""));
Assert.AreEqual("ui", fixture.Repository.GetTags().Single(tag => tag.Id == fixture.UiTagId).Name);
}
[TestMethod]
public void AddColumnWithDuplicateTitleIsRejectedCaseInsensitively()
{
using var fixture = new RepositoryFixture();
DuplicateNameException exception = Assert.ThrowsExactly<DuplicateNameException>(() =>
fixture.Repository.AddColumn("COL", ""));
Assert.AreEqual(NamedEntity.Column, exception.Entity);
Assert.AreEqual(1, fixture.Repository.GetColumns().Count);
}
[TestMethod]
public void AddColumnWithEmptyTitleIsRejected()
{
using var fixture = new RepositoryFixture();
NameRequiredException exception = Assert.ThrowsExactly<NameRequiredException>(() =>
fixture.Repository.AddColumn("", "description"));
Assert.AreEqual(NamedEntity.Column, exception.Entity);
Assert.AreEqual(1, fixture.Repository.GetColumns().Count);
}
[TestMethod]
public void UpdateColumnConstraintViolationsAreTyped()
{
using var fixture = new RepositoryFixture();
ColumnModel other = fixture.Repository.AddColumn("Other", "");
Assert.ThrowsExactly<DuplicateNameException>(() => fixture.Repository.UpdateColumn(other.Id, "col", ""));
Assert.ThrowsExactly<NameRequiredException>(() => fixture.Repository.UpdateColumn(other.Id, "", ""));
Assert.AreEqual("Other", fixture.Repository.GetColumn(other.Id)!.Title);
}
[TestMethod]
public void GetCardsWithFilterReturnsMatchesWithAllOfTheirTags()
{
using var fixture = new RepositoryFixture();
fixture.Repository.AddCard(fixture.ColumnId, "Other", "", []);
// Filtering by one tag must still load both tags of the matching card.
CompiledSearch filter = SearchSqlCompiler.Compile(SearchQueryParser.Parse("tag:ui")!);
IReadOnlyList<CardModel> cards = fixture.Repository.GetCards(filter);
Assert.AreEqual(1, cards.Count);
Assert.AreEqual(fixture.CardId, cards[0].Id);
CollectionAssert.AreEqual(new[] { "bug", "ui" }, cards[0].Tags.Select(tag => tag.Name).ToArray());
Assert.AreEqual(2, fixture.Repository.GetCards(null).Count);
}
[TestMethod]
public void CountCardsCountsPerColumn()
{
using var fixture = new RepositoryFixture();
ColumnModel empty = fixture.Repository.AddColumn("Empty", "");
fixture.Repository.AddCard(fixture.ColumnId, "", "", []);
Assert.AreEqual(2L, fixture.Repository.CountCards(fixture.ColumnId));
Assert.AreEqual(0L, fixture.Repository.CountCards(empty.Id));
}
[TestMethod]
public void GetTagsWithUsageCountsAssignments()
{
using var fixture = new RepositoryFixture(); using var fixture = new RepositoryFixture();
IReadOnlyList<(TagModel Tag, long UsageCount)> before = fixture.Repository.GetTagsWithUsage(); IReadOnlyList<(TagModel Tag, long UsageCount)> before = fixture.Repository.GetTagsWithUsage();
@@ -1,4 +1,5 @@
using Microsoft.Data.Sqlite; using Microsoft.Data.Sqlite;
using YKanBan.Storage; using YKanBan.Storage;
using YKanBan.Storage.Workspace; using YKanBan.Storage.Workspace;
using YKanBan.Tests.TestUtilities; using YKanBan.Tests.TestUtilities;
@@ -10,19 +11,16 @@ namespace YKanBan.Tests.Storage.Workspace;
/// and that the cascading delete chains work as specified. /// and that the cascading delete chains work as specified.
/// </summary> /// </summary>
[TestClass] [TestClass]
public class WorkspaceSchemaTests public class WorkspaceSchemaTests {
{
/// <summary> /// <summary>
/// Owns a temp directory plus a fresh workspace-schema database for a single test. /// Owns a temp directory plus a fresh workspace-schema database for a single test.
/// </summary> /// </summary>
private sealed class FreshDatabase : IDisposable private sealed class FreshDatabase : IDisposable {
{
public TempDirectory Directory { get; } = new(); public TempDirectory Directory { get; } = new();
public SqliteConnection Connection { get; } public SqliteConnection Connection { get; }
public FreshDatabase() public FreshDatabase() {
{
Connection = SqliteDatabase.Open( Connection = SqliteDatabase.Open(
Path.Combine(Directory.FullPath, "ws.db"), WorkspaceSchema.Migrations); Path.Combine(Directory.FullPath, "ws.db"), WorkspaceSchema.Migrations);
} }
@@ -30,24 +28,21 @@ public class WorkspaceSchemaTests
/// <summary> /// <summary>
/// Closes the connection before removing the temporary directory. /// Closes the connection before removing the temporary directory.
/// </summary> /// </summary>
public void Dispose() public void Dispose() {
{
Connection.Dispose(); Connection.Dispose();
Directory.Dispose(); Directory.Dispose();
} }
} }
[TestMethod] [TestMethod]
public void EmptyColumnTitleIsRejected() public void EmptyColumnTitleIsRejected() {
{
using var db = new FreshDatabase(); using var db = new FreshDatabase();
Assert.ThrowsExactly<SqliteException>(() => Assert.ThrowsExactly<SqliteException>(() =>
SqliteTestHelper.Exec(db.Connection, "INSERT INTO columns (title, created_at, updated_at) VALUES ('', 1, 1);")); SqliteTestHelper.Exec(db.Connection, "INSERT INTO columns (title, created_at, updated_at) VALUES ('', 1, 1);"));
} }
[TestMethod] [TestMethod]
public void WhitespaceColumnTitleIsAccepted() public void WhitespaceColumnTitleIsAccepted() {
{
using var db = new FreshDatabase(); using var db = new FreshDatabase();
// No trimming: a single space is a non-empty title as far as the DDL is concerned. // No trimming: a single space is a non-empty title as far as the DDL is concerned.
int affected = SqliteTestHelper.Exec( int affected = SqliteTestHelper.Exec(
@@ -56,8 +51,7 @@ public class WorkspaceSchemaTests
} }
[TestMethod] [TestMethod]
public void DuplicateColumnTitleIsRejected() public void DuplicateColumnTitleIsRejected() {
{
using var db = new FreshDatabase(); using var db = new FreshDatabase();
SqliteTestHelper.Exec(db.Connection, "INSERT INTO columns (title, created_at, updated_at) VALUES ('Foo', 1, 1);"); SqliteTestHelper.Exec(db.Connection, "INSERT INTO columns (title, created_at, updated_at) VALUES ('Foo', 1, 1);");
Assert.ThrowsExactly<SqliteException>(() => Assert.ThrowsExactly<SqliteException>(() =>
@@ -65,97 +59,44 @@ public class WorkspaceSchemaTests
} }
[TestMethod] [TestMethod]
public void ColumnTitlesDifferingOnlyInAsciiCaseAreRejected() public void ColumnTitlesCompareCaseSensitively() {
{
using var db = new FreshDatabase(); using var db = new FreshDatabase();
// NOCASE uniqueness: 'Foo' and 'foo' cannot coexist. // BINARY collation: 'Foo' and 'foo' are distinct titles.
SqliteTestHelper.Exec(db.Connection, "INSERT INTO columns (title, created_at, updated_at) VALUES ('Foo', 1, 1);"); SqliteTestHelper.Exec(db.Connection, "INSERT INTO columns (title, created_at, updated_at) VALUES ('Foo', 1, 1);");
Assert.ThrowsExactly<SqliteException>(() => SqliteTestHelper.Exec(db.Connection, "INSERT INTO columns (title, created_at, updated_at) VALUES ('foo', 1, 1);");
SqliteTestHelper.Exec(db.Connection, "INSERT INTO columns (title, created_at, updated_at) VALUES ('foo', 1, 1);"));
}
[TestMethod]
public void ColumnTitlesDifferingOnlyInNonAsciiCaseAreAccepted()
{
using var db = new FreshDatabase();
// NOCASE folds ASCII only: 'Ä' and 'ä' remain distinct titles.
SqliteTestHelper.Exec(db.Connection, "INSERT INTO columns (title, created_at, updated_at) VALUES ('Ä', 1, 1);");
SqliteTestHelper.Exec(db.Connection, "INSERT INTO columns (title, created_at, updated_at) VALUES ('ä', 1, 1);");
Assert.AreEqual(2L, SqliteTestHelper.ScalarLong(db.Connection, "SELECT COUNT(*) FROM columns;")); Assert.AreEqual(2L, SqliteTestHelper.ScalarLong(db.Connection, "SELECT COUNT(*) FROM columns;"));
} }
[TestMethod] [TestMethod]
public void ColumnTitleCaseOnlyRenameOfSameRowIsAccepted() public void EmptyTagNameIsRejected() {
{
using var db = new FreshDatabase();
SqliteTestHelper.Exec(db.Connection, "INSERT INTO columns (title, created_at, updated_at) VALUES ('Foo', 1, 1);");
int affected = SqliteTestHelper.Exec(db.Connection, "UPDATE columns SET title = 'foo' WHERE id = 1;");
Assert.AreEqual(1, affected);
}
[TestMethod]
public void ColumnTitlesStillOrderByCodePoint()
{
using var db = new FreshDatabase();
// Uniqueness is NOCASE, but the column collation stays BINARY: 'B' (0x42) sorts before 'a' (0x61).
SqliteTestHelper.Exec(db.Connection, "INSERT INTO columns (title, created_at, updated_at) VALUES ('a', 1, 1);");
SqliteTestHelper.Exec(db.Connection, "INSERT INTO columns (title, created_at, updated_at) VALUES ('B', 1, 1);");
Assert.AreEqual("B", SqliteTestHelper.ScalarString(db.Connection, "SELECT title FROM columns ORDER BY title LIMIT 1;"));
}
[TestMethod]
public void EmptyTagNameIsRejected()
{
using var db = new FreshDatabase(); using var db = new FreshDatabase();
Assert.ThrowsExactly<SqliteException>(() => Assert.ThrowsExactly<SqliteException>(() =>
SqliteTestHelper.Exec(db.Connection, "INSERT INTO tags (name, color) VALUES ('', '#112233');")); SqliteTestHelper.Exec(db.Connection, "INSERT INTO tags (name, color) VALUES ('', '#112233');"));
} }
[TestMethod] [TestMethod]
public void TagNamesAcceptSpacesEmojiAndReservedWords() public void TagNamesAcceptSpacesEmojiAndReservedWords() {
{
using var db = new FreshDatabase(); using var db = new FreshDatabase();
// Tag names are fully open: no charset or length rules, no trimming. // Tag names are fully open: no charset or length rules, no trimming.
foreach (string name in new[] { " ", "a b", "🏷️", "AND", "tag:with:colons" }) foreach (string name in new[] { " ", "a b", "🏷️", "AND", "tag:with:colons" }) {
{
SqliteTestHelper.Exec(db.Connection, "INSERT INTO tags (name, color) VALUES ($n, '#112233');", ("$n", name)); SqliteTestHelper.Exec(db.Connection, "INSERT INTO tags (name, color) VALUES ($n, '#112233');", ("$n", name));
} }
Assert.AreEqual(5L, SqliteTestHelper.ScalarLong(db.Connection, "SELECT COUNT(*) FROM tags;")); Assert.AreEqual(5L, SqliteTestHelper.ScalarLong(db.Connection, "SELECT COUNT(*) FROM tags;"));
} }
[TestMethod] [TestMethod]
public void DuplicateTagNameIsRejected() public void DuplicateTagNameIsRejected() {
{
using var db = new FreshDatabase(); using var db = new FreshDatabase();
SqliteTestHelper.Exec(db.Connection, "INSERT INTO tags (name, color) VALUES ('bug', '#112233');"); SqliteTestHelper.Exec(db.Connection, "INSERT INTO tags (name, color) VALUES ('bug', '#112233');");
Assert.ThrowsExactly<SqliteException>(() => Assert.ThrowsExactly<SqliteException>(() =>
SqliteTestHelper.Exec(db.Connection, "INSERT INTO tags (name, color) VALUES ('bug', '#445566');")); SqliteTestHelper.Exec(db.Connection, "INSERT INTO tags (name, color) VALUES ('bug', '#445566');"));
} }
[TestMethod]
public void TagNamesDifferingOnlyInAsciiCaseAreRejected()
{
using var db = new FreshDatabase();
SqliteTestHelper.Exec(db.Connection, "INSERT INTO tags (name, color) VALUES ('bug', '#112233');");
Assert.ThrowsExactly<SqliteException>(() =>
SqliteTestHelper.Exec(db.Connection, "INSERT INTO tags (name, color) VALUES ('BUG', '#445566');"));
}
[TestMethod]
public void TagNamesDifferingOnlyInNonAsciiCaseAreAccepted()
{
using var db = new FreshDatabase();
SqliteTestHelper.Exec(db.Connection, "INSERT INTO tags (name, color) VALUES ('Ä', '#112233');");
SqliteTestHelper.Exec(db.Connection, "INSERT INTO tags (name, color) VALUES ('ä', '#445566');");
Assert.AreEqual(2L, SqliteTestHelper.ScalarLong(db.Connection, "SELECT COUNT(*) FROM tags;"));
}
[TestMethod] [TestMethod]
[DataRow("#000000")] [DataRow("#000000")]
[DataRow("#FFFFFF")] [DataRow("#FFFFFF")]
[DataRow("#a1B2c3")] [DataRow("#a1B2c3")]
public void ValidTagColorsAreAccepted(string color) public void ValidTagColorsAreAccepted(string color) {
{
using var db = new FreshDatabase(); using var db = new FreshDatabase();
int affected = SqliteTestHelper.Exec( int affected = SqliteTestHelper.Exec(
db.Connection, "INSERT INTO tags (name, color) VALUES ('x', $c);", ("$c", color)); db.Connection, "INSERT INTO tags (name, color) VALUES ('x', $c);", ("$c", color));
@@ -171,16 +112,14 @@ public class WorkspaceSchemaTests
[DataRow(" #112233")] [DataRow(" #112233")]
[DataRow("#112233 ")] [DataRow("#112233 ")]
[DataRow("")] [DataRow("")]
public void InvalidTagColorsAreRejected(string color) public void InvalidTagColorsAreRejected(string color) {
{
using var db = new FreshDatabase(); using var db = new FreshDatabase();
Assert.ThrowsExactly<SqliteException>(() => Assert.ThrowsExactly<SqliteException>(() =>
SqliteTestHelper.Exec(db.Connection, "INSERT INTO tags (name, color) VALUES ('x', $c);", ("$c", color))); SqliteTestHelper.Exec(db.Connection, "INSERT INTO tags (name, color) VALUES ('x', $c);", ("$c", color)));
} }
[TestMethod] [TestMethod]
public void CardRequiresExistingColumn() public void CardRequiresExistingColumn() {
{
using var db = new FreshDatabase(); using var db = new FreshDatabase();
// foreign_keys=ON makes the FK enforceable; this is the DDL contract behind the cascades. // foreign_keys=ON makes the FK enforceable; this is the DDL contract behind the cascades.
Assert.ThrowsExactly<SqliteException>(() => Assert.ThrowsExactly<SqliteException>(() =>
@@ -188,8 +127,7 @@ public class WorkspaceSchemaTests
} }
[TestMethod] [TestMethod]
public void CardDefaultsToEmptyTitleAndContent() public void CardDefaultsToEmptyTitleAndContent() {
{
using var db = new FreshDatabase(); using var db = new FreshDatabase();
SqliteTestHelper.Exec(db.Connection, "INSERT INTO columns (title, created_at, updated_at) VALUES ('c', 1, 1);"); SqliteTestHelper.Exec(db.Connection, "INSERT INTO columns (title, created_at, updated_at) VALUES ('c', 1, 1);");
SqliteTestHelper.Exec(db.Connection, "INSERT INTO cards (column_id, created_at, updated_at) VALUES (1, 1, 1);"); SqliteTestHelper.Exec(db.Connection, "INSERT INTO cards (column_id, created_at, updated_at) VALUES (1, 1, 1);");
@@ -200,8 +138,7 @@ public class WorkspaceSchemaTests
} }
[TestMethod] [TestMethod]
public void CardTagDuplicateAssignmentIsRejected() public void CardTagDuplicateAssignmentIsRejected() {
{
using var db = new FreshDatabase(); using var db = new FreshDatabase();
SqliteTestHelper.Exec(db.Connection, "INSERT INTO columns (title, created_at, updated_at) VALUES ('c', 1, 1);"); SqliteTestHelper.Exec(db.Connection, "INSERT INTO columns (title, created_at, updated_at) VALUES ('c', 1, 1);");
SqliteTestHelper.Exec(db.Connection, "INSERT INTO cards (column_id, created_at, updated_at) VALUES (1, 1, 1);"); SqliteTestHelper.Exec(db.Connection, "INSERT INTO cards (column_id, created_at, updated_at) VALUES (1, 1, 1);");
@@ -214,8 +151,7 @@ public class WorkspaceSchemaTests
} }
[TestMethod] [TestMethod]
public void DeletingColumnCascadesToCardsAndCardTags() public void DeletingColumnCascadesToCardsAndCardTags() {
{
using var db = new FreshDatabase(); using var db = new FreshDatabase();
InsertBoardRow(db.Connection); InsertBoardRow(db.Connection);
@@ -229,8 +165,7 @@ public class WorkspaceSchemaTests
} }
[TestMethod] [TestMethod]
public void DeletingCardCascadesToCardTagsOnly() public void DeletingCardCascadesToCardTagsOnly() {
{
using var db = new FreshDatabase(); using var db = new FreshDatabase();
InsertBoardRow(db.Connection); InsertBoardRow(db.Connection);
@@ -243,8 +178,7 @@ public class WorkspaceSchemaTests
} }
[TestMethod] [TestMethod]
public void DeletingTagRemovesAssignmentsButKeepsCards() public void DeletingTagRemovesAssignmentsButKeepsCards() {
{
using var db = new FreshDatabase(); using var db = new FreshDatabase();
InsertBoardRow(db.Connection); InsertBoardRow(db.Connection);
@@ -261,8 +195,7 @@ public class WorkspaceSchemaTests
/// Inserts one column, one card, one tag and their assignment, ready for a cascade test. /// Inserts one column, one card, one tag and their assignment, ready for a cascade test.
/// </summary> /// </summary>
/// <param name="connection">An open workspace-schema connection.</param> /// <param name="connection">An open workspace-schema connection.</param>
private static void InsertBoardRow(SqliteConnection connection) private static void InsertBoardRow(SqliteConnection connection) {
{
SqliteTestHelper.Exec(connection, "INSERT INTO columns (title, created_at, updated_at) VALUES ('c', 1, 1);"); SqliteTestHelper.Exec(connection, "INSERT INTO columns (title, created_at, updated_at) VALUES ('c', 1, 1);");
SqliteTestHelper.Exec(connection, "INSERT INTO cards (column_id, created_at, updated_at) VALUES (1, 1, 1);"); SqliteTestHelper.Exec(connection, "INSERT INTO cards (column_id, created_at, updated_at) VALUES (1, 1, 1);");
SqliteTestHelper.Exec(connection, "INSERT INTO tags (name, color) VALUES ('bug', '#112233');"); SqliteTestHelper.Exec(connection, "INSERT INTO tags (name, color) VALUES ('bug', '#112233');");
@@ -10,11 +10,9 @@ namespace YKanBan.Tests.Storage.Workspace;
/// the whole session and the repository is usable through it. /// the whole session and the repository is usable through it.
/// </summary> /// </summary>
[TestClass] [TestClass]
public class WorkspaceSessionTests public class WorkspaceSessionTests {
{
[TestMethod] [TestMethod]
public void OpenHoldsLockUntilDisposed() public void OpenHoldsLockUntilDisposed() {
{
using var directory = new TempDirectory(); using var directory = new TempDirectory();
WorkspaceInitializer.Initialize(directory.FullPath); WorkspaceInitializer.Initialize(directory.FullPath);
@@ -25,8 +23,7 @@ public class WorkspaceSessionTests
} }
[TestMethod] [TestMethod]
public void DisposeReleasesLockForReopen() public void DisposeReleasesLockForReopen() {
{
using var directory = new TempDirectory(); using var directory = new TempDirectory();
WorkspaceInitializer.Initialize(directory.FullPath); WorkspaceInitializer.Initialize(directory.FullPath);
@@ -37,8 +34,7 @@ public class WorkspaceSessionTests
} }
[TestMethod] [TestMethod]
public void OpenUninitializedFolderThrowsNotInitialized() public void OpenUninitializedFolderThrowsNotInitialized() {
{
using var directory = new TempDirectory(); using var directory = new TempDirectory();
Assert.ThrowsExactly<WorkspaceNotInitializedException>( Assert.ThrowsExactly<WorkspaceNotInitializedException>(
@@ -46,8 +42,43 @@ public class WorkspaceSessionTests
} }
[TestMethod] [TestMethod]
public void RepositoryIsUsableThroughSession() public void OpenWithoutDatabaseThrowsDatabaseMissing() {
{ using var directory = new TempDirectory();
WorkspaceInitializer.Initialize(directory.FullPath);
File.Delete(WorkspacePaths.Database(directory.FullPath));
Assert.ThrowsExactly<WorkspaceDatabaseMissingException>(
() => WorkspaceSession.Open(directory.FullPath));
}
[TestMethod]
public void InitializeHoldsLockAndSeedsPreset() {
using var directory = new TempDirectory();
using WorkspaceSession session = WorkspaceSession.Initialize(directory.FullPath);
// The lock is held for the whole session, so a second initialize cannot interleave.
Assert.ThrowsExactly<WorkspaceLockException>(() => WorkspaceSession.Initialize(directory.FullPath));
// The preset columns and tags were written under the same lock.
Assert.AreEqual(3, session.Repository.GetColumns().Count);
Assert.AreEqual(8, session.Repository.GetTags().Count);
}
[TestMethod]
public void InitializeExistingWorkspaceThrowsAndReleasesLock() {
using var directory = new TempDirectory();
WorkspaceInitializer.Initialize(directory.FullPath);
Assert.ThrowsExactly<InvalidOperationException>(() => WorkspaceSession.Initialize(directory.FullPath));
// The failed initialize released the lock, so the workspace can still be opened.
using WorkspaceSession session = WorkspaceSession.Open(directory.FullPath);
Assert.AreEqual(directory.FullPath, session.FolderPath);
}
[TestMethod]
public void RepositoryIsUsableThroughSession() {
using var directory = new TempDirectory(); using var directory = new TempDirectory();
WorkspaceInitializer.Initialize(directory.FullPath); WorkspaceInitializer.Initialize(directory.FullPath);
@@ -1,50 +0,0 @@
using YKanBan.ViewModels.Dialogs;
namespace YKanBan.Tests.TestUtilities;
/// <summary>
/// Records every dialog shown and lets a test script answer it. The result
/// is whatever the dialog closed with; a dialog the script leaves open
/// counts as dismissed. The save-file dialog answers with
/// <see cref="SaveFilePath"/>.
/// </summary>
internal sealed class ScriptedDialogService : IDialogService
{
public List<DialogViewModelBase> Shown { get; } = [];
public Func<DialogViewModelBase, Task> Script { get; set; } = _ => Task.CompletedTask;
public string? SaveFilePath { get; set; }
public List<string> SuggestedFileNames { get; } = [];
public async Task<bool> ShowAsync(DialogViewModelBase dialog)
{
Shown.Add(dialog);
bool? result = null;
dialog.CloseRequested += (_, closed) => result ??= closed;
await Script(dialog);
return result ?? false;
}
public Task<string?> PickSaveFilePathAsync(string suggestedFileName)
{
SuggestedFileNames.Add(suggestedFileName);
return Task.FromResult(SaveFilePath);
}
/// <summary>Answers every confirmation dialog with the given choice.</summary>
public static Func<DialogViewModelBase, Task> AnswerConfirmations(bool confirm) => dialog =>
{
if (dialog is ConfirmDialogViewModel confirmation)
{
if (confirm)
{
confirmation.ConfirmCommand.Execute(null);
return Task.CompletedTask;
}
return confirmation.CancelCommand.ExecuteAsync(null);
}
return Task.CompletedTask;
};
}
+44 -18
View File
@@ -1,4 +1,5 @@
using Microsoft.Data.Sqlite; using Microsoft.Data.Sqlite;
using YKanBan.Storage; using YKanBan.Storage;
using YKanBan.Storage.Workspace; using YKanBan.Storage.Workspace;
@@ -8,8 +9,7 @@ namespace YKanBan.Tests.TestUtilities;
/// Shared helpers for the storage tests: small SQL conveniences plus opening a /// Shared helpers for the storage tests: small SQL conveniences plus opening a
/// workspace database with the real migration list. /// workspace database with the real migration list.
/// </summary> /// </summary>
public static class SqliteTestHelper public static class SqliteTestHelper {
{
/// <summary> /// <summary>
/// Executes a non-query SQL statement and returns the affected row count. /// Executes a non-query SQL statement and returns the affected row count.
/// </summary> /// </summary>
@@ -17,12 +17,10 @@ public static class SqliteTestHelper
/// <param name="sql">The statement to execute.</param> /// <param name="sql">The statement to execute.</param>
/// <param name="parameters">Name/value pairs bound as SQL parameters.</param> /// <param name="parameters">Name/value pairs bound as SQL parameters.</param>
/// <returns>The number of affected rows.</returns> /// <returns>The number of affected rows.</returns>
public static int Exec(SqliteConnection connection, string sql, params (string Name, object? Value)[] parameters) public static int Exec(SqliteConnection connection, string sql, params (string Name, object? Value)[] parameters) {
{
using var command = connection.CreateCommand(); using var command = connection.CreateCommand();
command.CommandText = sql; command.CommandText = sql;
foreach ((string name, object? value) in parameters) foreach ((string name, object? value) in parameters) {
{
command.Parameters.AddWithValue(name, value); command.Parameters.AddWithValue(name, value);
} }
return command.ExecuteNonQuery(); return command.ExecuteNonQuery();
@@ -34,8 +32,7 @@ public static class SqliteTestHelper
/// <param name="connection">An open database connection.</param> /// <param name="connection">An open database connection.</param>
/// <param name="sql">The query to execute.</param> /// <param name="sql">The query to execute.</param>
/// <returns>The scalar result cast to a string.</returns> /// <returns>The scalar result cast to a string.</returns>
public static string ScalarString(SqliteConnection connection, string sql) public static string ScalarString(SqliteConnection connection, string sql) {
{
using var command = connection.CreateCommand(); using var command = connection.CreateCommand();
command.CommandText = sql; command.CommandText = sql;
return (string)command.ExecuteScalar()!; return (string)command.ExecuteScalar()!;
@@ -47,8 +44,7 @@ public static class SqliteTestHelper
/// <param name="connection">An open database connection.</param> /// <param name="connection">An open database connection.</param>
/// <param name="sql">The query to execute.</param> /// <param name="sql">The query to execute.</param>
/// <returns>The scalar result cast to a long.</returns> /// <returns>The scalar result cast to a long.</returns>
public static long ScalarLong(SqliteConnection connection, string sql) public static long ScalarLong(SqliteConnection connection, string sql) {
{
using var command = connection.CreateCommand(); using var command = connection.CreateCommand();
command.CommandText = sql; command.CommandText = sql;
return (long)command.ExecuteScalar()!; return (long)command.ExecuteScalar()!;
@@ -60,8 +56,7 @@ public static class SqliteTestHelper
/// <param name="connection">An open database connection.</param> /// <param name="connection">An open database connection.</param>
/// <param name="tableName">The table name to look for.</param> /// <param name="tableName">The table name to look for.</param>
/// <returns><see langword="true"/> when the table exists.</returns> /// <returns><see langword="true"/> when the table exists.</returns>
public static bool TableExists(SqliteConnection connection, string tableName) public static bool TableExists(SqliteConnection connection, string tableName) {
{
using var command = connection.CreateCommand(); using var command = connection.CreateCommand();
command.CommandText = "SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name=$name;"; command.CommandText = "SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name=$name;";
command.Parameters.AddWithValue("$name", tableName); command.Parameters.AddWithValue("$name", tableName);
@@ -73,27 +68,58 @@ public static class SqliteTestHelper
/// </summary> /// </summary>
/// <param name="connection">An open database connection.</param> /// <param name="connection">An open database connection.</param>
/// <returns>The column titles in id order.</returns> /// <returns>The column titles in id order.</returns>
public static List<string> GetColumnTitles(SqliteConnection connection) public static List<string> GetColumnTitles(SqliteConnection connection) {
{
using var command = connection.CreateCommand(); using var command = connection.CreateCommand();
command.CommandText = "SELECT title FROM columns ORDER BY id ASC;"; command.CommandText = "SELECT title FROM columns ORDER BY id ASC;";
using var reader = command.ExecuteReader(); using var reader = command.ExecuteReader();
var titles = new List<string>(); var titles = new List<string>();
while (reader.Read()) while (reader.Read()) {
{
titles.Add(reader.GetString(0)); titles.Add(reader.GetString(0));
} }
return titles; return titles;
} }
/// <summary>
/// Returns the descriptions of all columns, ordered by id ascending.
/// </summary>
/// <param name="connection">An open database connection.</param>
/// <returns>The column descriptions in id order.</returns>
public static List<string> GetColumnDescriptions(SqliteConnection connection) {
using var command = connection.CreateCommand();
command.CommandText = "SELECT description FROM columns ORDER BY id ASC;";
using var reader = command.ExecuteReader();
var descriptions = new List<string>();
while (reader.Read()) {
descriptions.Add(reader.GetString(0));
}
return descriptions;
}
/// <summary>
/// Returns all tags as name/color/description tuples, ordered by id ascending.
/// </summary>
/// <param name="connection">An open database connection.</param>
/// <returns>The tags in id order.</returns>
public static List<(string Name, string Color, string Description)> GetTags(SqliteConnection connection) {
using var command = connection.CreateCommand();
command.CommandText = "SELECT name, color, description FROM tags ORDER BY id ASC;";
using var reader = command.ExecuteReader();
var tags = new List<(string, string, string)>();
while (reader.Read()) {
tags.Add((reader.GetString(0), reader.GetString(1), reader.GetString(2)));
}
return tags;
}
/// <summary> /// <summary>
/// Opens a workspace database with the real workspace migration list. /// Opens a workspace database with the real workspace migration list.
/// </summary> /// </summary>
/// <param name="folderPath">The workspace folder path.</param> /// <param name="folderPath">The workspace folder path.</param>
/// <returns>An open, migrated connection.</returns> /// <returns>An open, migrated connection.</returns>
public static SqliteConnection OpenWorkspace(string folderPath) public static SqliteConnection OpenWorkspace(string folderPath) {
{
return SqliteDatabase.Open(WorkspacePaths.Database(folderPath), WorkspaceSchema.Migrations); return SqliteDatabase.Open(WorkspacePaths.Database(folderPath), WorkspaceSchema.Migrations);
} }
} }
+12 -16
View File
@@ -5,15 +5,13 @@ namespace YKanBan.Tests.TestUtilities;
/// disposal. The removal is retried once because SQLite WAL sidecar files can /// disposal. The removal is retried once because SQLite WAL sidecar files can
/// linger for a moment after the connections close. /// linger for a moment after the connections close.
/// </summary> /// </summary>
public sealed class TempDirectory : IDisposable public sealed class TempDirectory : IDisposable {
{
/// <summary> /// <summary>
/// Gets the unique directory path managed by this instance. /// Gets the unique directory path managed by this instance.
/// </summary> /// </summary>
public string FullPath { get; } public string FullPath { get; }
public TempDirectory() public TempDirectory() {
{
FullPath = Path.Combine(Path.GetTempPath(), "ykanban-tests-" + Guid.NewGuid().ToString("N")); FullPath = Path.Combine(Path.GetTempPath(), "ykanban-tests-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(FullPath); Directory.CreateDirectory(FullPath);
} }
@@ -21,21 +19,19 @@ public sealed class TempDirectory : IDisposable
/// <summary> /// <summary>
/// Deletes the directory tree, retrying once after a short delay. /// Deletes the directory tree, retrying once after a short delay.
/// </summary> /// </summary>
public void Dispose() public void Dispose() {
{ try {
try // SAFETY: Recursive directory delete is safe: FullPath is the
{ // read-only, GUID-named directory this instance created under the
// OS temp folder, so it can never target user data or the temp root.
Directory.Delete(FullPath, recursive: true); Directory.Delete(FullPath, recursive: true);
} } catch (IOException) {
catch (IOException)
{
Thread.Sleep(100); Thread.Sleep(100);
try try {
{ // SAFETY: Retry of the same recursive delete, still confined to
// this instance's own temp directory.
Directory.Delete(FullPath, recursive: true); Directory.Delete(FullPath, recursive: true);
} } catch (IOException) {
catch (IOException)
{
// Leftovers in the OS temp folder are harmless; never fail a test over cleanup. // Leftovers in the OS temp folder are harmless; never fail a test over cleanup.
} }
} }
@@ -1,357 +0,0 @@
using YKanBan.Models;
using YKanBan.Search;
using YKanBan.Storage;
using YKanBan.Storage.AppData;
using YKanBan.Storage.Workspace;
using YKanBan.Tests.TestUtilities;
using YKanBan.ViewModels.Board;
using YKanBan.ViewModels.Dialogs;
namespace YKanBan.Tests.ViewModels;
/// <summary>
/// View-model tests of the board and its dialogs against a real temporary
/// workspace, with a scripted dialog service standing in for the modal windows.
/// </summary>
[TestClass]
public class BoardViewModelTests
{
private sealed class Fixture : IDisposable
{
public TempDirectory Directory { get; } = new();
public WorkspaceRepository Repository { get; }
public AppConfig Config { get; } = new();
public ScriptedDialogService Dialogs { get; } = new();
public Fixture()
{
WorkspaceInitializer.Initialize(Directory.FullPath);
Repository = new WorkspaceRepository(Directory.FullPath);
}
public BoardViewModel CreateBoard() => new(Repository, Config, Dialogs);
public void Dispose()
{
Repository.Dispose();
Directory.Dispose();
}
}
[TestMethod]
public void RefreshListsColumnsInIdOrderAndSortsCardsWithinEachColumn()
{
using var fixture = new Fixture();
ColumnModel first = fixture.Repository.AddColumn("A", "");
ColumnModel second = fixture.Repository.AddColumn("B", "");
fixture.Repository.AddCard(first.Id, "zeta", "", []);
fixture.Repository.AddCard(first.Id, "alpha", "", []);
fixture.Repository.AddCard(second.Id, "x", "", []);
fixture.Config.Sort.Card = CardSortOption.Title;
BoardViewModel board = fixture.CreateBoard();
CollectionAssert.AreEqual(new[] { "A", "B" }, board.Columns.Select(column => column.Title).ToArray());
CollectionAssert.AreEqual(new[] { "alpha", "zeta" }, board.Columns[0].Cards.Select(card => card.Title).ToArray());
Assert.AreEqual(1, board.Columns[1].CardCount);
}
[TestMethod]
public void ChangingTheSortPersistsItToTheConfigurationAndResorts()
{
using var fixture = new Fixture();
ColumnModel column = fixture.Repository.AddColumn("A", "");
fixture.Repository.AddCard(column.Id, "b", "", []);
fixture.Repository.AddCard(column.Id, "a", "", []);
BoardViewModel board = fixture.CreateBoard();
CollectionAssert.AreEqual(new[] { "b", "a" }, board.Columns[0].Cards.Select(card => card.Title).ToArray());
board.SelectedSort = board.SortOptions.Single(option => (CardSortOption)option.Value == CardSortOption.Title);
Assert.AreEqual(CardSortOption.Title, fixture.Config.Sort.Card);
CollectionAssert.AreEqual(new[] { "a", "b" }, board.Columns[0].Cards.Select(card => card.Title).ToArray());
}
[TestMethod]
public async Task WritesRefreshWithTheActiveFilterAndKeepEmptyColumns()
{
using var fixture = new Fixture();
ColumnModel todo = fixture.Repository.AddColumn("Todo", "");
ColumnModel done = fixture.Repository.AddColumn("Done", "");
CardModel match = fixture.Repository.AddCard(todo.Id, "match me", "", []);
fixture.Repository.AddCard(todo.Id, "other", "", []);
BoardViewModel board = fixture.CreateBoard();
board.ActiveFilter = SearchSqlCompiler.Compile(SearchQueryParser.Parse("match")!);
board.Refresh();
Assert.AreEqual(1, board.Columns[0].CardCount);
// A move is a write: the board re-queries with the active filter.
CardViewModel card = board.Columns[0].Cards.Single();
MoveTargetViewModel target = card.MoveTargets.Single(entry => entry.ColumnId == done.Id);
Assert.IsFalse(card.MoveTargets.Single(entry => entry.ColumnId == todo.Id).IsEnabled);
await target.Command.ExecuteAsync(target.ColumnId);
Assert.AreEqual(2, board.Columns.Count, "Columns emptied by the filter stay on the board.");
Assert.AreEqual(0, board.Columns[0].CardCount);
Assert.AreEqual(match.Id, board.Columns[1].Cards.Single().Card.Id);
}
[TestMethod]
public async Task DeclinedColumnDeletionKeepsTheColumnAndShowsItsCardCount()
{
using var fixture = new Fixture();
ColumnModel column = fixture.Repository.AddColumn("A", "");
fixture.Repository.AddCard(column.Id, "", "", []);
fixture.Repository.AddCard(column.Id, "", "", []);
BoardViewModel board = fixture.CreateBoard();
fixture.Dialogs.Script = ScriptedDialogService.AnswerConfirmations(false);
await board.Columns[0].DeleteCommand.ExecuteAsync(null);
var confirmation = (ConfirmDialogViewModel)fixture.Dialogs.Shown.Single();
StringAssert.Contains(confirmation.Message, "2");
Assert.AreEqual(1, fixture.Repository.GetColumns().Count);
}
[TestMethod]
public async Task ColumnDeletionWithoutConfirmationDeletesImmediately()
{
using var fixture = new Fixture();
fixture.Repository.AddColumn("A", "");
fixture.Config.Confirmations.DeleteColumn = false;
BoardViewModel board = fixture.CreateBoard();
await board.Columns[0].DeleteCommand.ExecuteAsync(null);
Assert.AreEqual(0, fixture.Dialogs.Shown.Count);
Assert.AreEqual(0, board.Columns.Count);
}
[TestMethod]
public async Task ConfirmedCardDeletionDeletesTheCard()
{
using var fixture = new Fixture();
ColumnModel column = fixture.Repository.AddColumn("A", "");
fixture.Repository.AddCard(column.Id, "gone", "", []);
BoardViewModel board = fixture.CreateBoard();
fixture.Dialogs.Script = ScriptedDialogService.AnswerConfirmations(true);
await board.Columns[0].Cards[0].DeleteCommand.ExecuteAsync(null);
Assert.AreEqual(0, board.Columns[0].CardCount);
Assert.AreEqual(0, fixture.Repository.GetCards().Count);
}
[TestMethod]
public async Task DuplicateColumnTitleIsReportedInsideTheDialog()
{
using var fixture = new Fixture();
fixture.Repository.AddColumn("Todo", "");
BoardViewModel board = fixture.CreateBoard();
ColumnEditorDialogViewModel? editor = null;
bool closed = false;
fixture.Dialogs.Script = dialog =>
{
editor = (ColumnEditorDialogViewModel)dialog;
editor.CloseRequested += (_, _) => closed = true;
editor.ColumnTitle = "TODO";
editor.ConfirmCommand.Execute(null);
return Task.CompletedTask;
};
await board.AddColumnCommand.ExecuteAsync(null);
Assert.IsNotNull(editor);
Assert.IsFalse(closed, "The dialog stays open on a constraint violation.");
Assert.IsTrue(editor.HasError);
StringAssert.Contains(editor.ErrorMessage, "TODO");
Assert.AreEqual(1, fixture.Repository.GetColumns().Count);
}
[TestMethod]
public async Task NewCardIsWrittenWithItsTagsOnConfirmation()
{
using var fixture = new Fixture();
ColumnModel column = fixture.Repository.AddColumn("A", "");
TagModel bug = fixture.Repository.AddTag("bug", new RgbColor(255, 0, 0), "");
BoardViewModel board = fixture.CreateBoard();
fixture.Dialogs.Script = async dialog =>
{
switch (dialog)
{
case CardEditorDialogViewModel editor:
editor.CardTitle = "Fix it";
editor.Content = "Details";
await editor.AddTagCommand.ExecuteAsync(null);
editor.ConfirmCommand.Execute(null);
break;
case TagPickerDialogViewModel picker:
picker.PickCommand.Execute(picker.FilteredTags.Single());
break;
}
};
await board.Columns[0].AddCardCommand.ExecuteAsync(null);
CardModel card = fixture.Repository.GetCards().Single();
Assert.AreEqual("Fix it", card.Title);
Assert.AreEqual("Details", card.Content);
Assert.AreEqual(bug.Id, card.Tags.Single().Id);
Assert.AreEqual(card.Id, board.Columns[0].Cards.Single().Card.Id);
}
[TestMethod]
public void UnchangedEditConfirmationWritesNothing()
{
using var fixture = new Fixture();
ColumnModel column = fixture.Repository.AddColumn("A", "");
CardModel card = fixture.Repository.AddCard(column.Id, "t", "c", []);
using (var connection = SqliteTestHelper.OpenWorkspace(fixture.Directory.FullPath))
{
SqliteTestHelper.Exec(connection, "UPDATE cards SET updated_at = 100;");
}
card = fixture.Repository.GetCard(card.Id)!;
var editor = CardEditorDialogViewModel.ForExistingCard(fixture.Repository, fixture.Dialogs, card, confirmDiscard: true);
editor.CardTitle = "changed";
editor.CardTitle = "t";
Assert.IsFalse(editor.IsDirty);
editor.ConfirmCommand.Execute(null);
Assert.AreEqual(100, fixture.Repository.GetCard(card.Id)!.UpdatedAt);
}
[TestMethod]
public async Task DirtyCancelAsksAndStaysOpenWhenDeclined()
{
using var fixture = new Fixture();
ColumnModel column = fixture.Repository.AddColumn("A", "");
var editor = CardEditorDialogViewModel.ForNewCard(fixture.Repository, fixture.Dialogs, column.Id, confirmDiscard: true);
bool? closedWith = null;
editor.CloseRequested += (_, result) => closedWith = result;
editor.Content = "draft";
fixture.Dialogs.Script = ScriptedDialogService.AnswerConfirmations(false);
await editor.RequestCancelAsync();
Assert.IsNull(closedWith, "Declining the discard keeps the editor open.");
fixture.Dialogs.Script = ScriptedDialogService.AnswerConfirmations(true);
await editor.RequestCancelAsync();
Assert.IsFalse(closedWith);
Assert.AreEqual(0, fixture.Repository.GetCards().Count);
}
[TestMethod]
public async Task CleanCancelClosesWithoutAsking()
{
using var fixture = new Fixture();
ColumnModel column = fixture.Repository.AddColumn("A", "");
var editor = CardEditorDialogViewModel.ForNewCard(fixture.Repository, fixture.Dialogs, column.Id, confirmDiscard: true);
bool? closedWith = null;
editor.CloseRequested += (_, result) => closedWith = result;
await editor.RequestCancelAsync();
Assert.IsFalse(closedWith);
Assert.AreEqual(0, fixture.Dialogs.Shown.Count);
}
[TestMethod]
public async Task TagCreatedInThePickerSurvivesACancelledCardEdit()
{
using var fixture = new Fixture();
ColumnModel column = fixture.Repository.AddColumn("A", "");
var editor = CardEditorDialogViewModel.ForNewCard(fixture.Repository, fixture.Dialogs, column.Id, confirmDiscard: false);
fixture.Dialogs.Script = dialog =>
{
if (dialog is TagPickerDialogViewModel picker)
{
picker.NewName = "fresh";
picker.NewColor = "#123456";
picker.CreateCommand.Execute(null);
}
return Task.CompletedTask;
};
await editor.AddTagCommand.ExecuteAsync(null);
Assert.AreEqual("fresh", editor.Tags.Single().Name);
await editor.RequestCancelAsync();
Assert.AreEqual("fresh", fixture.Repository.GetTags().Single().Name);
Assert.AreEqual(0, fixture.Repository.GetCards().Count);
}
[TestMethod]
public void TagPickerReportsInvalidColorAndDuplicateNameWithoutClosing()
{
using var fixture = new Fixture();
fixture.Repository.AddTag("bug", new RgbColor(1, 2, 3), "");
var picker = new TagPickerDialogViewModel(fixture.Repository, []);
bool closed = false;
picker.CloseRequested += (_, _) => closed = true;
picker.NewName = "new";
picker.NewColor = "red";
picker.CreateCommand.Execute(null);
Assert.AreEqual(YKanBan.Resources.Error_Tag_InvalidColor, picker.ErrorMessage);
picker.NewName = "BUG";
picker.NewColor = "#ff0000";
picker.CreateCommand.Execute(null);
StringAssert.Contains(picker.ErrorMessage, "BUG");
Assert.IsFalse(closed);
Assert.AreEqual(1, fixture.Repository.GetTags().Count);
}
[TestMethod]
public void TagPickerHidesAssignedTagsAndFiltersCaseInsensitively()
{
using var fixture = new Fixture();
TagModel bug = fixture.Repository.AddTag("Bug", new RgbColor(1, 2, 3), "");
fixture.Repository.AddTag("UI", new RgbColor(1, 2, 3), "");
fixture.Repository.AddTag("Build", new RgbColor(1, 2, 3), "");
var picker = new TagPickerDialogViewModel(fixture.Repository, [bug.Id]);
picker.FilterText = "bu";
CollectionAssert.AreEqual(new[] { "Build" }, picker.FilteredTags.Select(tag => tag.Name).ToArray());
picker.FilterText = "zzz";
Assert.IsTrue(picker.NoMatches);
}
[TestMethod]
public void ColumnWidthDialogCommitsPresetsAndClampsCustomPixels()
{
var settings = new ColumnWidthSettings();
var dialog = new ColumnWidthDialogViewModel(settings) { IsStandard = false, IsCustom = true, CustomPixels = 5000 };
dialog.ConfirmCommand.Execute(null);
Assert.AreEqual(ColumnWidthPreset.Custom, settings.Preset);
Assert.AreEqual(AppConfig.MaxColumnPixels, settings.CustomPixels);
Assert.AreEqual(AppConfig.MaxColumnPixels, ColumnWidths.Resolve(settings));
dialog = new ColumnWidthDialogViewModel(settings) { IsCustom = false, IsWide = true };
dialog.ConfirmCommand.Execute(null);
Assert.AreEqual(ColumnWidthPreset.Wide, settings.Preset);
Assert.AreEqual(ColumnWidths.Wide, ColumnWidths.Resolve(settings));
}
[TestMethod]
public void CardHeaderAndExcerptFollowTheDisplayRules()
{
var untitled = new CardModel(61, 1, "", "", 0, 0, []);
var titled = untitled with { Title = "Foo bar" };
Assert.AreEqual("#61", CardViewModel.FormatHeader(untitled));
Assert.AreEqual("#61 Foo bar", CardViewModel.FormatHeader(titled));
Assert.AreEqual("short", CardViewModel.MakeExcerpt(" short \n"));
string longContent = string.Concat(Enumerable.Repeat("😀", CardViewModel.ExcerptLength + 5));
string excerpt = CardViewModel.MakeExcerpt(longContent);
Assert.IsTrue(excerpt.EndsWith('…'));
Assert.AreEqual((CardViewModel.ExcerptLength * 2) + 1, excerpt.Length, "Surrogate pairs are kept whole.");
}
}
@@ -1,5 +1,7 @@
using System.Globalization; using System.Globalization;
using Microsoft.Data.Sqlite; using Microsoft.Data.Sqlite;
using YKanBan.Storage; using YKanBan.Storage;
using YKanBan.ViewModels.ErrorPages; using YKanBan.ViewModels.ErrorPages;
@@ -12,20 +14,15 @@ namespace YKanBan.Tests.ViewModels;
/// </summary> /// </summary>
[TestClass] [TestClass]
[DoNotParallelize] [DoNotParallelize]
public class OpenFailedPageViewModelTests public class OpenFailedPageViewModelTests {
{
private const string Folder = "/work/repo"; private const string Folder = "/work/repo";
private static void WithCulture(string language, Action action) private static void WithCulture(string language, Action action) {
{
CultureInfo? original = Resources.Culture; CultureInfo? original = Resources.Culture;
try try {
{
Resources.Culture = new CultureInfo(language); Resources.Culture = new CultureInfo(language);
action(); action();
} } finally {
finally
{
Resources.Culture = original; Resources.Culture = original;
} }
} }
@@ -36,13 +33,14 @@ public class OpenFailedPageViewModelTests
[TestMethod] [TestMethod]
[DataRow("en")] [DataRow("en")]
[DataRow("zh-Hans")] [DataRow("zh-Hans")]
public void EachRecognizedExceptionTypeHasItsOwnMessage(string language) public void EachRecognizedExceptionTypeHasItsOwnMessage(string language) {
{ WithCulture(language, () => {
WithCulture(language, () =>
{
Assert.AreEqual( Assert.AreEqual(
Expected(Resources.Error_OpenFailed_SchemaTooNew, 3L, 1), Expected(Resources.Error_OpenFailed_SchemaTooNew, 3L, 1),
OpenFailedPageViewModel.BuildMessage(Folder, new SchemaVersionException(3, 1))); OpenFailedPageViewModel.BuildMessage(Folder, new SchemaVersionException(3, 1)));
Assert.AreEqual(
Expected(Resources.Error_OpenFailed_DatabaseMissing),
OpenFailedPageViewModel.BuildMessage(Folder, new WorkspaceDatabaseMissingException("/work/repo/.ykanban/ykanban.db")));
Assert.AreEqual( Assert.AreEqual(
Expected(Resources.Error_OpenFailed_Database), Expected(Resources.Error_OpenFailed_Database),
OpenFailedPageViewModel.BuildMessage(Folder, new SqliteException("file is not a database", 26))); OpenFailedPageViewModel.BuildMessage(Folder, new SqliteException("file is not a database", 26)));
@@ -59,10 +57,8 @@ public class OpenFailedPageViewModelTests
} }
[TestMethod] [TestMethod]
public void UnrecognizedExceptionGetsTheGenericMessage() public void UnrecognizedExceptionGetsTheGenericMessage() {
{ WithCulture("en", () => {
WithCulture("en", () =>
{
Assert.AreEqual( Assert.AreEqual(
Expected(Resources.Error_OpenFailed_Generic), Expected(Resources.Error_OpenFailed_Generic),
OpenFailedPageViewModel.BuildMessage(Folder, new InvalidOperationException())); OpenFailedPageViewModel.BuildMessage(Folder, new InvalidOperationException()));
@@ -73,10 +69,8 @@ public class OpenFailedPageViewModelTests
} }
[TestMethod] [TestMethod]
public void DetailsCarryTheEnglishExceptionTextInAnyLanguage() public void DetailsCarryTheEnglishExceptionTextInAnyLanguage() {
{ WithCulture("zh-Hans", () => {
WithCulture("zh-Hans", () =>
{
var exception = new SchemaVersionException(3, 1); var exception = new SchemaVersionException(3, 1);
var page = new OpenFailedPageViewModel(Folder, exception); var page = new OpenFailedPageViewModel(Folder, exception);
@@ -1,400 +0,0 @@
using YKanBan.Models;
using YKanBan.Storage.AppData;
using YKanBan.Storage.Workspace;
using YKanBan.Tests.TestUtilities;
using YKanBan.ViewModels;
using YKanBan.ViewModels.Board;
using YKanBan.ViewModels.Dialogs;
using YKanBan.ViewModels.Tags;
namespace YKanBan.Tests.ViewModels;
/// <summary>
/// View-model tests of the search bar, the tags tab, the cross-tab refresh and
/// the export wiring, against a real temporary workspace with a scripted
/// dialog service.
/// </summary>
[TestClass]
public class TagsAndSearchViewModelTests
{
private sealed class Fixture : IDisposable
{
public TempDirectory Directory { get; } = new();
public WorkspaceSession Session { get; }
public WorkspaceRepository Repository => Session.Repository;
public AppConfig Config { get; } = new();
public ScriptedDialogService Dialogs { get; } = new();
public Fixture()
{
WorkspaceInitializer.Initialize(Directory.FullPath);
Session = WorkspaceSession.Open(Directory.FullPath);
}
public BoardViewModel CreateBoard() => new(Repository, Config, Dialogs);
public TagsViewModel CreateTags() => new(Repository, Config, Dialogs);
public WorkspaceViewModel CreateWorkspace() =>
new(Session, new Interaction<Unit>(), new Interaction<Unit>(), Config, Dialogs);
public void Dispose()
{
Session.Dispose();
Directory.Dispose();
}
}
private static string[] VisibleTitles(BoardViewModel board) =>
board.Columns.SelectMany(column => column.Cards).Select(card => card.Title).Order(StringComparer.Ordinal).ToArray();
/// <summary>Moves a visible card through its menu command.</summary>
private static Task MoveAsync(BoardViewModel board, long cardId, long columnId) =>
board.Columns.SelectMany(column => column.Cards).Single(card => card.Card.Id == cardId)
.MoveToCommand.ExecuteAsync(columnId);
#region Search
[TestMethod]
public async Task SearchFiltersCardsAndKeepsEmptyColumns()
{
using var fixture = new Fixture();
ColumnModel first = fixture.Repository.AddColumn("A", "");
ColumnModel second = fixture.Repository.AddColumn("B", "");
TagModel bug = fixture.Repository.AddTag("bug", new RgbColor(1, 2, 3), "");
fixture.Repository.AddCard(first.Id, "crash", "", [bug.Id]);
fixture.Repository.AddCard(second.Id, "idea", "", []);
BoardViewModel board = fixture.CreateBoard();
board.SearchText = "tag:BUG";
await board.SearchCommand.ExecuteAsync(null);
CollectionAssert.AreEqual(new[] { "crash" }, VisibleTitles(board));
Assert.AreEqual(2, board.Columns.Count);
Assert.AreEqual(0, board.Columns[1].CardCount);
Assert.IsNotNull(board.ActiveFilter);
Assert.AreEqual(0, fixture.Dialogs.Shown.Count);
}
[TestMethod]
public async Task InvalidSearchShowsTheErrorAndKeepsTextAndPreviousResult()
{
using var fixture = new Fixture();
ColumnModel column = fixture.Repository.AddColumn("A", "");
fixture.Repository.AddCard(column.Id, "alpha", "", []);
fixture.Repository.AddCard(column.Id, "beta", "", []);
BoardViewModel board = fixture.CreateBoard();
board.SearchText = "alpha";
await board.SearchCommand.ExecuteAsync(null);
board.SearchText = "alpha AND";
await board.SearchCommand.ExecuteAsync(null);
var error = (MessageDialogViewModel)fixture.Dialogs.Shown.Single();
Assert.AreEqual(Resources.Search_Error_Title, error.Title);
Assert.AreEqual("alpha AND", board.SearchText);
CollectionAssert.AreEqual(new[] { "alpha" }, VisibleTitles(board));
}
[TestMethod]
public async Task WritesRefreshWithTheLastSuccessfulExpressionNotTheBoxText()
{
using var fixture = new Fixture();
ColumnModel first = fixture.Repository.AddColumn("A", "");
ColumnModel second = fixture.Repository.AddColumn("B", "");
CardModel alpha = fixture.Repository.AddCard(first.Id, "alpha", "", []);
fixture.Repository.AddCard(first.Id, "beta", "", []);
BoardViewModel board = fixture.CreateBoard();
board.SearchText = "alpha";
await board.SearchCommand.ExecuteAsync(null);
board.SearchText = "beta";
await MoveAsync(board, alpha.Id, second.Id);
CollectionAssert.AreEqual(new[] { "alpha" }, VisibleTitles(board));
Assert.AreEqual(1, board.Columns[1].CardCount);
}
[TestMethod]
public async Task BlankSearchAndClearShowEveryCard()
{
using var fixture = new Fixture();
ColumnModel column = fixture.Repository.AddColumn("A", "");
fixture.Repository.AddCard(column.Id, "alpha", "", []);
fixture.Repository.AddCard(column.Id, "beta", "", []);
BoardViewModel board = fixture.CreateBoard();
board.SearchText = "alpha";
await board.SearchCommand.ExecuteAsync(null);
board.SearchText = " ";
await board.SearchCommand.ExecuteAsync(null);
Assert.IsNull(board.ActiveFilter);
CollectionAssert.AreEqual(new[] { "alpha", "beta" }, VisibleTitles(board));
board.SearchText = "alpha";
await board.SearchCommand.ExecuteAsync(null);
Assert.IsTrue(board.HasSearchText);
board.ClearSearchCommand.Execute(null);
Assert.AreEqual("", board.SearchText);
Assert.IsFalse(board.HasSearchText);
Assert.IsNull(board.ActiveFilter);
CollectionAssert.AreEqual(new[] { "alpha", "beta" }, VisibleTitles(board));
}
[TestMethod]
public async Task DataWrittenIsRaisedForWritesButNotForSearchOrSort()
{
using var fixture = new Fixture();
ColumnModel first = fixture.Repository.AddColumn("A", "");
ColumnModel second = fixture.Repository.AddColumn("B", "");
CardModel card = fixture.Repository.AddCard(first.Id, "x", "", []);
BoardViewModel board = fixture.CreateBoard();
int raised = 0;
board.DataWritten += (_, _) => raised++;
board.SearchText = "x";
await board.SearchCommand.ExecuteAsync(null);
board.SelectedSort = board.SortOptions[1];
Assert.AreEqual(0, raised);
await MoveAsync(board, card.Id, second.Id);
Assert.AreEqual(1, raised);
}
#endregion
#region Tags tab
[TestMethod]
public void TagsListInIdOrderWithUsageCounts()
{
using var fixture = new Fixture();
ColumnModel column = fixture.Repository.AddColumn("A", "");
TagModel bug = fixture.Repository.AddTag("bug", new RgbColor(1, 2, 3), "Broken");
TagModel unused = fixture.Repository.AddTag("unused", new RgbColor(4, 5, 6), "");
fixture.Repository.AddCard(column.Id, "a", "", [bug.Id]);
fixture.Repository.AddCard(column.Id, "b", "", [bug.Id]);
TagsViewModel tags = fixture.CreateTags();
CollectionAssert.AreEqual(new[] { bug.Id, unused.Id }, tags.Tags.Select(row => row.Tag.Id).ToArray());
CollectionAssert.AreEqual(new long[] { 2, 0 }, tags.Tags.Select(row => row.UsageCount).ToArray());
Assert.IsTrue(tags.Tags[0].HasDescription);
Assert.AreEqual("#010203", tags.Tags[0].ColorText);
Assert.IsFalse(tags.IsEmpty);
}
[TestMethod]
public async Task NewTagIsWrittenAndAnnounced()
{
using var fixture = new Fixture();
TagsViewModel tags = fixture.CreateTags();
int changed = 0;
tags.TagsChanged += (_, _) => changed++;
fixture.Dialogs.Script = dialog =>
{
var editor = (TagEditorDialogViewModel)dialog;
editor.Name = "ui";
editor.PickSwatchCommand.Execute(TagColors.Palette[2].ToString());
editor.Description = "Looks";
editor.ConfirmCommand.Execute(null);
return Task.CompletedTask;
};
await tags.AddTagCommand.ExecuteAsync(null);
TagModel created = fixture.Repository.GetTags().Single();
Assert.AreEqual("ui", created.Name);
Assert.AreEqual(TagColors.Palette[2], created.Color);
Assert.AreEqual("Looks", created.Description);
Assert.AreEqual(1, tags.Tags.Count);
Assert.AreEqual(1, changed);
}
[TestMethod]
public async Task TagEditorKeepsTheDialogOpenOnDuplicateNameOrInvalidColor()
{
using var fixture = new Fixture();
fixture.Repository.AddTag("Bug", new RgbColor(1, 2, 3), "");
TagsViewModel tags = fixture.CreateTags();
TagEditorDialogViewModel? editor = null;
bool closed = false;
fixture.Dialogs.Script = dialog =>
{
editor = (TagEditorDialogViewModel)dialog;
editor.CloseRequested += (_, _) => closed = true;
editor.Name = "bug";
editor.ConfirmCommand.Execute(null);
return Task.CompletedTask;
};
await tags.AddTagCommand.ExecuteAsync(null);
Assert.IsNotNull(editor);
Assert.IsTrue(editor.HasError);
Assert.IsFalse(closed);
Assert.AreEqual("bug", editor.Name);
editor.Name = "other";
editor.Color = "red";
editor.ConfirmCommand.Execute(null);
Assert.AreEqual(Resources.Error_Tag_InvalidColor, editor.ErrorMessage);
Assert.IsFalse(closed);
Assert.AreEqual(1, fixture.Repository.GetTags().Count);
}
[TestMethod]
public async Task EditingATagRenamesRecolorsAndDescribesIt()
{
using var fixture = new Fixture();
TagModel tag = fixture.Repository.AddTag("bug", new RgbColor(1, 2, 3), "");
TagsViewModel tags = fixture.CreateTags();
fixture.Dialogs.Script = dialog =>
{
var editor = (TagEditorDialogViewModel)dialog;
Assert.AreEqual("bug", editor.Name);
Assert.AreEqual("#010203", editor.Color);
editor.Name = "defect";
editor.Color = "#ABCDEF";
editor.Description = "Broken";
editor.ConfirmCommand.Execute(null);
return Task.CompletedTask;
};
await tags.Tags[0].EditCommand.ExecuteAsync(null);
TagModel updated = fixture.Repository.GetTags().Single();
Assert.AreEqual(tag.Id, updated.Id);
Assert.AreEqual("defect", updated.Name);
Assert.AreEqual(new RgbColor(0xab, 0xcd, 0xef), updated.Color);
Assert.AreEqual("Broken", updated.Description);
Assert.AreEqual("defect", tags.Tags[0].Badge.Name);
}
[TestMethod]
public async Task DeletingATagAsksFirstAndKeepsTheCards()
{
using var fixture = new Fixture();
ColumnModel column = fixture.Repository.AddColumn("A", "");
TagModel bug = fixture.Repository.AddTag("bug", new RgbColor(1, 2, 3), "");
CardModel card = fixture.Repository.AddCard(column.Id, "a", "", [bug.Id]);
TagsViewModel tags = fixture.CreateTags();
fixture.Dialogs.Script = ScriptedDialogService.AnswerConfirmations(false);
await tags.Tags[0].DeleteCommand.ExecuteAsync(null);
Assert.AreEqual(1, fixture.Repository.GetTags().Count);
fixture.Dialogs.Script = ScriptedDialogService.AnswerConfirmations(true);
await tags.Tags[0].DeleteCommand.ExecuteAsync(null);
Assert.AreEqual(0, fixture.Repository.GetTags().Count);
Assert.IsTrue(tags.IsEmpty);
CardModel kept = fixture.Repository.GetCard(card.Id)!;
Assert.AreEqual(0, kept.Tags.Count);
}
[TestMethod]
public async Task DeletingATagWithoutConfirmationShowsNoDialog()
{
using var fixture = new Fixture();
fixture.Repository.AddTag("bug", new RgbColor(1, 2, 3), "");
fixture.Config.Confirmations.DeleteTag = false;
TagsViewModel tags = fixture.CreateTags();
await tags.Tags[0].DeleteCommand.ExecuteAsync(null);
Assert.AreEqual(0, fixture.Dialogs.Shown.Count);
Assert.AreEqual(0, fixture.Repository.GetTags().Count);
}
#endregion
#region Workspace wiring and export
[TestMethod]
public async Task TagWritesRefreshTheBoardAndBoardWritesRefreshTheTags()
{
using var fixture = new Fixture();
ColumnModel first = fixture.Repository.AddColumn("A", "");
ColumnModel second = fixture.Repository.AddColumn("B", "");
TagModel bug = fixture.Repository.AddTag("bug", new RgbColor(1, 2, 3), "");
CardModel card = fixture.Repository.AddCard(first.Id, "a", "", [bug.Id]);
WorkspaceViewModel workspace = fixture.CreateWorkspace();
// A filtered board drops the card once the tag is gone.
workspace.Board.SearchText = "tag:bug";
await workspace.Board.SearchCommand.ExecuteAsync(null);
fixture.Dialogs.Script = ScriptedDialogService.AnswerConfirmations(true);
await workspace.Tags.Tags[0].DeleteCommand.ExecuteAsync(null);
Assert.AreEqual(0, workspace.Board.Columns.Sum(column => column.CardCount));
// Re-tag through the repository, then a board write updates the usage count.
workspace.Board.ClearSearchCommand.Execute(null);
TagModel ui = fixture.Repository.AddTag("ui", new RgbColor(4, 5, 6), "");
fixture.Repository.UpdateCard(card.Id, "a", "", [ui.Id]);
Assert.AreEqual(0, workspace.Tags.Tags.Count);
await MoveAsync(workspace.Board, card.Id, second.Id);
Assert.AreEqual(1, workspace.Tags.Tags.Single().UsageCount);
}
[TestMethod]
public async Task ExportWritesTheWholeWorkspaceIgnoringTheSearch()
{
using var fixture = new Fixture();
ColumnModel column = fixture.Repository.AddColumn("A", "");
fixture.Repository.AddCard(column.Id, "alpha", "", []);
fixture.Repository.AddCard(column.Id, "beta", "", []);
WorkspaceViewModel workspace = fixture.CreateWorkspace();
workspace.Board.SearchText = "alpha";
await workspace.Board.SearchCommand.ExecuteAsync(null);
string path = Path.Combine(fixture.Directory.FullPath, "out.md");
fixture.Dialogs.SaveFilePath = path;
await workspace.ExportCommand.ExecuteAsync(null);
string suggested = fixture.Dialogs.SuggestedFileNames.Single();
StringAssert.StartsWith(suggested, workspace.WorkspaceName);
StringAssert.EndsWith(suggested, ".md");
string markdown = File.ReadAllText(path);
StringAssert.Contains(markdown, "alpha");
StringAssert.Contains(markdown, "beta");
byte[] bytes = File.ReadAllBytes(path);
Assert.AreNotEqual(0xEF, bytes[0], "The export must not start with a UTF-8 BOM.");
Assert.AreEqual(0, fixture.Dialogs.Shown.Count);
}
[TestMethod]
public async Task CancelledExportWritesNothing()
{
using var fixture = new Fixture();
WorkspaceViewModel workspace = fixture.CreateWorkspace();
fixture.Dialogs.SaveFilePath = null;
await workspace.ExportCommand.ExecuteAsync(null);
Assert.AreEqual(1, fixture.Dialogs.SuggestedFileNames.Count);
Assert.AreEqual(0, fixture.Dialogs.Shown.Count);
Assert.AreEqual(0, System.IO.Directory.GetFiles(fixture.Directory.FullPath, "*.md").Length);
}
[TestMethod]
public async Task ExportWriteFailureIsReportedInAMessageDialog()
{
using var fixture = new Fixture();
WorkspaceViewModel workspace = fixture.CreateWorkspace();
fixture.Dialogs.SaveFilePath = Path.Combine(fixture.Directory.FullPath, "missing-folder", "out.md");
await workspace.ExportCommand.ExecuteAsync(null);
var message = (MessageDialogViewModel)fixture.Dialogs.Shown.Single();
Assert.AreEqual(Resources.Export_Failed_Title, message.Title);
Assert.IsTrue(message.HasDetails);
}
#endregion
}
+10 -9
View File
@@ -12,6 +12,7 @@
<Application.Styles> <Application.Styles>
<!-- Semi.Avalonia provides the light and dark palettes; icons need their own theme. --> <!-- Semi.Avalonia provides the light and dark palettes; icons need their own theme. -->
<semi:SemiTheme/> <semi:SemiTheme/>
<semi:ColorPickerSemiTheme/>
<StyleInclude Source="avares://IconPacks.Avalonia.Lucide/Lucide.axaml"/> <StyleInclude Source="avares://IconPacks.Avalonia.Lucide/Lucide.axaml"/>
</Application.Styles> </Application.Styles>
@@ -26,20 +27,20 @@
<ResourceDictionary x:Key="Light"> <ResourceDictionary x:Key="Light">
<SolidColorBrush x:Key="TopBarBackgroundBrush" Color="#F6F7F9"/> <SolidColorBrush x:Key="TopBarBackgroundBrush" Color="#F6F7F9"/>
<SolidColorBrush x:Key="TopBarBorderBrush" Color="#E2E4EA"/> <SolidColorBrush x:Key="TopBarBorderBrush" Color="#E2E4EA"/>
<SolidColorBrush x:Key="PanelBorderBrush" Color="#E2E4EA"/> <SolidColorBrush x:Key="BoardColumnBackgroundBrush" Color="#F1F2F5"/>
<SolidColorBrush x:Key="ColumnBackgroundBrush" Color="#F3F4F7"/> <SolidColorBrush x:Key="BoardColumnBorderBrush" Color="#E2E4EA"/>
<SolidColorBrush x:Key="CardBackgroundBrush" Color="#FFFFFF"/> <SolidColorBrush x:Key="CardBackgroundBrush" Color="#FFFFFF"/>
<SolidColorBrush x:Key="CardForegroundBrush" Color="#1C1F23"/> <SolidColorBrush x:Key="CardBorderBrush" Color="#E2E4EA"/>
<SolidColorBrush x:Key="ErrorTextBrush" Color="#D52515"/> <SolidColorBrush x:Key="ErrorTextBrush" Color="#C0392B"/>
</ResourceDictionary> </ResourceDictionary>
<ResourceDictionary x:Key="Dark"> <ResourceDictionary x:Key="Dark">
<SolidColorBrush x:Key="TopBarBackgroundBrush" Color="#1C1E24"/> <SolidColorBrush x:Key="TopBarBackgroundBrush" Color="#1C1E24"/>
<SolidColorBrush x:Key="TopBarBorderBrush" Color="#2C2F37"/> <SolidColorBrush x:Key="TopBarBorderBrush" Color="#2C2F37"/>
<SolidColorBrush x:Key="PanelBorderBrush" Color="#33363F"/> <SolidColorBrush x:Key="BoardColumnBackgroundBrush" Color="#17181C"/>
<SolidColorBrush x:Key="ColumnBackgroundBrush" Color="#1A1C21"/> <SolidColorBrush x:Key="BoardColumnBorderBrush" Color="#2C2F37"/>
<SolidColorBrush x:Key="CardBackgroundBrush" Color="#25282F"/> <SolidColorBrush x:Key="CardBackgroundBrush" Color="#23252B"/>
<SolidColorBrush x:Key="CardForegroundBrush" Color="#E6E8EC"/> <SolidColorBrush x:Key="CardBorderBrush" Color="#33363F"/>
<SolidColorBrush x:Key="ErrorTextBrush" Color="#FC725A"/> <SolidColorBrush x:Key="ErrorTextBrush" Color="#FF6B6B"/>
</ResourceDictionary> </ResourceDictionary>
</ResourceDictionary.ThemeDictionaries> </ResourceDictionary.ThemeDictionaries>
</ResourceDictionary> </ResourceDictionary>
+17 -31
View File
@@ -1,20 +1,22 @@
using System.Globalization; using System.Globalization;
using Avalonia; using Avalonia;
using Avalonia.Controls.ApplicationLifetimes; using Avalonia.Controls.ApplicationLifetimes;
using Avalonia.Data.Core.Plugins; using Avalonia.Data.Core.Plugins;
using Avalonia.Markup.Xaml; using Avalonia.Markup.Xaml;
using Avalonia.Media; using Avalonia.Media;
using Avalonia.Styling; using Avalonia.Styling;
using YKanBan.Services; using YKanBan.Services;
using YKanBan.Storage.AppData; using YKanBan.Storage.AppData;
using YKanBan.ViewModels; using YKanBan.ViewModels;
using YKanBan.Views; using YKanBan.Views;
using Resx = YKanBan.Resources; using Resx = YKanBan.Resources;
namespace YKanBan; namespace YKanBan;
public partial class App : Application public partial class App : Application {
{
/// <summary> /// <summary>
/// Gets the process-wide composition root, created at startup. /// Gets the process-wide composition root, created at startup.
/// </summary> /// </summary>
@@ -32,15 +34,12 @@ public partial class App : Application
/// </summary> /// </summary>
public static FlowDirection UiFlowDirection { get; private set; } = FlowDirection.LeftToRight; public static FlowDirection UiFlowDirection { get; private set; } = FlowDirection.LeftToRight;
public override void Initialize() public override void Initialize() {
{
AvaloniaXamlLoader.Load(this); AvaloniaXamlLoader.Load(this);
} }
public override void OnFrameworkInitializationCompleted() public override void OnFrameworkInitializationCompleted() {
{ if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop) {
if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
{
DisableAvaloniaDataAnnotationValidation(); DisableAvaloniaDataAnnotationValidation();
// Startup order: apply the configured culture, its RTL flow direction // Startup order: apply the configured culture, its RTL flow direction
@@ -58,15 +57,11 @@ public partial class App : Application
: FlowDirection.LeftToRight; : FlowDirection.LeftToRight;
ApplyTheme(Services.Config.Theme); ApplyTheme(Services.Config.Theme);
var dialogs = new DialogService(); var viewModel = new MainWindowViewModel(Services, desktop.Args ?? []);
var viewModel = new MainWindowViewModel(Services, dialogs, desktop.Args ?? []); desktop.MainWindow = new MainWindow {
var mainWindow = new MainWindow
{
DataContext = viewModel, DataContext = viewModel,
FlowDirection = UiFlowDirection, FlowDirection = UiFlowDirection,
}; };
dialogs.Attach(mainWindow);
desktop.MainWindow = mainWindow;
} }
base.OnFrameworkInitializationCompleted(); base.OnFrameworkInitializationCompleted();
@@ -77,14 +72,10 @@ public partial class App : Application
/// </summary> /// </summary>
/// <param name="language">The language code from app.json.</param> /// <param name="language">The language code from app.json.</param>
/// <returns>The resolved culture.</returns> /// <returns>The resolved culture.</returns>
public static CultureInfo ResolveCulture(string language) public static CultureInfo ResolveCulture(string language) {
{ try {
try
{
return new CultureInfo(language); return new CultureInfo(language);
} } catch (CultureNotFoundException) {
catch (CultureNotFoundException)
{
return new CultureInfo(AppConfig.DefaultLanguage); return new CultureInfo(AppConfig.DefaultLanguage);
} }
} }
@@ -94,28 +85,23 @@ public partial class App : Application
/// inherits the operating system preference. /// inherits the operating system preference.
/// </summary> /// </summary>
/// <param name="option">The theme selection.</param> /// <param name="option">The theme selection.</param>
public static void ApplyTheme(ThemeOption option) public static void ApplyTheme(ThemeOption option) {
{ if (Current is null) {
if (Current is null)
{
return; return;
} }
Current.RequestedThemeVariant = option switch Current.RequestedThemeVariant = option switch {
{
ThemeOption.Light => ThemeVariant.Light, ThemeOption.Light => ThemeVariant.Light,
ThemeOption.Dark => ThemeVariant.Dark, ThemeOption.Dark => ThemeVariant.Dark,
_ => ThemeVariant.Default, _ => ThemeVariant.Default,
}; };
} }
private static void DisableAvaloniaDataAnnotationValidation() private static void DisableAvaloniaDataAnnotationValidation() {
{
var dataValidationPluginsToRemove = var dataValidationPluginsToRemove =
BindingPlugins.DataValidators.OfType<DataAnnotationsValidationPlugin>().ToArray(); BindingPlugins.DataValidators.OfType<DataAnnotationsValidationPlugin>().ToArray();
foreach (var plugin in dataValidationPluginsToRemove) foreach (var plugin in dataValidationPluginsToRemove) {
{
BindingPlugins.DataValidators.Remove(plugin); BindingPlugins.DataValidators.Remove(plugin);
} }
} }
+460
View File
@@ -0,0 +1,460 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Japanese (ja) satellite resources.
This file is embedded beside the neutral resources; see YKanBan.csproj.
-->
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="App_Name" xml:space="preserve">
<value>YKanBan</value>
</data>
<data name="Common_Ok" xml:space="preserve">
<value>OK</value>
</data>
<data name="Common_Cancel" xml:space="preserve">
<value>キャンセル</value>
</data>
<data name="Common_Delete" xml:space="preserve">
<value>削除</value>
</data>
<data name="Common_Edit" xml:space="preserve">
<value>編集</value>
</data>
<data name="Main_Export" xml:space="preserve">
<value>エクスポート</value>
</data>
<data name="Main_Settings" xml:space="preserve">
<value>設定</value>
</data>
<data name="Main_About" xml:space="preserve">
<value>このアプリについて</value>
</data>
<data name="Tab_Tags" xml:space="preserve">
<value>タグ</value>
</data>
<data name="Tab_Board" xml:space="preserve">
<value>ボード</value>
</data>
<data name="Board_SearchPlaceholder" xml:space="preserve">
<value>検索…</value>
</data>
<data name="Board_Search" xml:space="preserve">
<value>検索</value>
</data>
<data name="Board_ClearSearch" xml:space="preserve">
<value>クリア</value>
</data>
<data name="Board_AddColumn" xml:space="preserve">
<value>列を追加</value>
</data>
<data name="Board_ColumnWidth" xml:space="preserve">
<value>列の幅</value>
</data>
<data name="Board_SortCard" xml:space="preserve">
<value>カードの並べ替え</value>
</data>
<data name="Board_SortColumn" xml:space="preserve">
<value>列の並べ替え</value>
</data>
<data name="Board_Display" xml:space="preserve">
<value>表示</value>
</data>
<data name="Board_NoColumns" xml:space="preserve">
<value>列がまだありません。</value>
</data>
<data name="Board_FilterActive" xml:space="preserve">
<value>ボードにフィルターが適用されています</value>
</data>
<data name="Board_FilterInactive" xml:space="preserve">
<value>ボードにフィルターは適用されていません</value>
</data>
<data name="Search_Error_Title" xml:space="preserve">
<value>無効な検索式</value>
</data>
<data name="Search_Error_Message" xml:space="preserve">
<value>検索式が正しくありません。詳細: {0}</value>
</data>
<data name="Sort_IdAsc" xml:space="preserve">
<value>ID 昇順</value>
</data>
<data name="Sort_IdDesc" xml:space="preserve">
<value>ID 降順</value>
</data>
<data name="Sort_CreatedAsc" xml:space="preserve">
<value>作成日時 昇順</value>
</data>
<data name="Sort_CreatedDesc" xml:space="preserve">
<value>作成日時 降順</value>
</data>
<data name="Sort_UpdatedAsc" xml:space="preserve">
<value>更新日時 昇順</value>
</data>
<data name="Sort_UpdatedDesc" xml:space="preserve">
<value>更新日時 降順</value>
</data>
<data name="Sort_TitleAsc" xml:space="preserve">
<value>タイトル 昇順</value>
</data>
<data name="Sort_TitleDesc" xml:space="preserve">
<value>タイトル 降順</value>
</data>
<data name="Column_AddCard" xml:space="preserve">
<value>カードを追加</value>
</data>
<data name="Column_Edit" xml:space="preserve">
<value>編集</value>
</data>
<data name="Column_Delete" xml:space="preserve">
<value>削除</value>
</data>
<data name="Card_Delete" xml:space="preserve">
<value>削除</value>
</data>
<data name="Card_Move" xml:space="preserve">
<value>列へ移動…</value>
</data>
<data name="ColumnDialog_AddTitle" xml:space="preserve">
<value>新しい列</value>
</data>
<data name="ColumnDialog_EditTitle" xml:space="preserve">
<value>列を編集</value>
</data>
<data name="ColumnDialog_Title" xml:space="preserve">
<value>タイトル</value>
</data>
<data name="ColumnDialog_Description" xml:space="preserve">
<value>説明</value>
</data>
<data name="ColumnDialog_InvalidTitle" xml:space="preserve">
<value>タイトルが空であるか、すでに使用されています。</value>
</data>
<data name="CardDialog_AddTitle" xml:space="preserve">
<value>新しいカード</value>
</data>
<data name="CardDialog_EditTitle" xml:space="preserve">
<value>カードを編集</value>
</data>
<data name="CardDialog_Title" xml:space="preserve">
<value>タイトル</value>
</data>
<data name="CardDialog_Content" xml:space="preserve">
<value>内容</value>
</data>
<data name="CardDialog_Tags" xml:space="preserve">
<value>タグ</value>
</data>
<data name="CardDialog_AddTag" xml:space="preserve">
<value>タグを追加</value>
</data>
<data name="CardDialog_Id" xml:space="preserve">
<value>ID: {0}</value>
</data>
<data name="CardDialog_Created" xml:space="preserve">
<value>作成日時: {0}</value>
</data>
<data name="CardDialog_Modified" xml:space="preserve">
<value>更新日時: {0}</value>
</data>
<data name="CardDialog_TimePattern" xml:space="preserve">
<value>yyyy年M月d日 HH:mm</value>
</data>
<data name="CardDialog_Error" xml:space="preserve">
<value>カードを保存できませんでした。</value>
</data>
<data name="TagDialog_Title" xml:space="preserve">
<value>タグの追加</value>
</data>
<data name="TagDialog_Target" xml:space="preserve">
<value>タグ</value>
</data>
<data name="TagDialog_NoTargets" xml:space="preserve">
<value>追加できるタグがありません。</value>
</data>
<data name="Tags_AddTag" xml:space="preserve">
<value>タグを追加</value>
</data>
<data name="Tags_Count" xml:space="preserve">
<value>{0} 個のタグ</value>
</data>
<data name="Tags_Empty" xml:space="preserve">
<value>タグがまだありません。</value>
</data>
<data name="Tags_Usage" xml:space="preserve">
<value>{0} 枚のカード</value>
</data>
<data name="TagEditor_AddTitle" xml:space="preserve">
<value>新しいタグ</value>
</data>
<data name="TagEditor_EditTitle" xml:space="preserve">
<value>タグを編集</value>
</data>
<data name="TagEditor_Name" xml:space="preserve">
<value>名前</value>
</data>
<data name="TagEditor_Color" xml:space="preserve">
<value>色</value>
</data>
<data name="TagEditor_Description" xml:space="preserve">
<value>説明</value>
</data>
<data name="TagEditor_InvalidName" xml:space="preserve">
<value>名前が空であるか、すでに使用されています。</value>
</data>
<data name="DeleteTag_Confirm_Title" xml:space="preserve">
<value>タグの削除</value>
</data>
<data name="DeleteTag_Confirm_Message" xml:space="preserve">
<value>タグ「{0}」を削除しますか?{1} 枚のカードから削除されます。</value>
</data>
<data name="MoveDialog_Title" xml:space="preserve">
<value>カードの移動</value>
</data>
<data name="MoveDialog_Target" xml:space="preserve">
<value>移動先の列</value>
</data>
<data name="MoveDialog_NoTargets" xml:space="preserve">
<value>カードの移動先がありません。</value>
</data>
<data name="WidthPreset_Narrow" xml:space="preserve">
<value>狭い</value>
</data>
<data name="WidthPreset_Standard" xml:space="preserve">
<value>標準</value>
</data>
<data name="WidthPreset_Wide" xml:space="preserve">
<value>広い</value>
</data>
<data name="WidthPreset_Custom" xml:space="preserve">
<value>カスタム</value>
</data>
<data name="WidthDialog_Pixels" xml:space="preserve">
<value>ピクセル(160–720)</value>
</data>
<data name="Confirm_DeleteColumn_Title" xml:space="preserve">
<value>列の削除</value>
</data>
<data name="Confirm_DeleteColumn_Message" xml:space="preserve">
<value>列「{0}」とその {1} 枚のカードを削除しますか?</value>
</data>
<data name="Confirm_DeleteCard_Title" xml:space="preserve">
<value>カードの削除</value>
</data>
<data name="Confirm_DeleteCard_Message" xml:space="preserve">
<value>カード #{0} を削除しますか?</value>
</data>
<data name="Confirm_Discard_Title" xml:space="preserve">
<value>変更の破棄</value>
</data>
<data name="Confirm_Discard_Message" xml:space="preserve">
<value>未保存の変更を破棄しますか?</value>
</data>
<data name="Error_Argument_Title" xml:space="preserve">
<value>無効な引数</value>
</data>
<data name="Error_Argument_Message" xml:space="preserve">
<value>YKanBan の起動引数が無効です。</value>
</data>
<data name="Error_Argument_Usage" xml:space="preserve">
<value>使用法: ykanban &lt;パス&gt;</value>
</data>
<data name="Error_NotInitialized_Title" xml:space="preserve">
<value>ワークスペースがありません</value>
</data>
<data name="Error_NotInitialized_Message" xml:space="preserve">
<value>このフォルダーには .ykanban ワークスペースがありません:{0}</value>
</data>
<data name="Error_NotInitialized_Initialize" xml:space="preserve">
<value>ワークスペースを初期化</value>
</data>
<data name="Error_LockConflict_Title" xml:space="preserve">
<value>ワークスペースはロックされています</value>
</data>
<data name="Error_LockConflict_Message" xml:space="preserve">
<value>このワークスペースは別のインスタンスで開かれています:{0}</value>
</data>
<data name="Settings_Title" xml:space="preserve">
<value>設定</value>
</data>
<data name="Settings_Language" xml:space="preserve">
<value>言語</value>
</data>
<data name="Settings_Language_RestartNotice" xml:space="preserve">
<value>再起動後に有効になります</value>
</data>
<data name="Settings_Theme" xml:space="preserve">
<value>テーマ</value>
</data>
<data name="Settings_ThemeLight" xml:space="preserve">
<value>ライト</value>
</data>
<data name="Settings_ThemeDark" xml:space="preserve">
<value>ダーク</value>
</data>
<data name="Settings_ThemeFollowSystem" xml:space="preserve">
<value>システムに従う</value>
</data>
<data name="Settings_Confirmations" xml:space="preserve">
<value>確認ダイアログ</value>
</data>
<data name="Settings_ConfirmDeleteCard" xml:space="preserve">
<value>カードを削除する前に確認する</value>
</data>
<data name="Settings_ConfirmDeleteColumn" xml:space="preserve">
<value>列を削除する前に確認する</value>
</data>
<data name="Settings_ConfirmDeleteTag" xml:space="preserve">
<value>タグを削除する前に確認する</value>
</data>
<data name="Settings_ConfirmDiscardEdit" xml:space="preserve">
<value>カードの編集を破棄する前に確認する</value>
</data>
<data name="About_Title" xml:space="preserve">
<value>このアプリについて</value>
</data>
<data name="About_Version" xml:space="preserve">
<value>バージョン {0}</value>
</data>
<data name="About_Repository" xml:space="preserve">
<value>リポジトリ</value>
</data>
<data name="About_License" xml:space="preserve">
<value>ライセンス</value>
</data>
<data name="About_LicenseValue" xml:space="preserve">
<value>MIT</value>
</data>
<data name="PresetColumn_Todo" xml:space="preserve">
<value>未着手</value>
</data>
<data name="PresetColumn_Todo_Description" xml:space="preserve">
<value>計画済みで、まだ開始していないタスクです。</value>
</data>
<data name="PresetColumn_InProgress" xml:space="preserve">
<value>進行中</value>
</data>
<data name="PresetColumn_InProgress_Description" xml:space="preserve">
<value>現在取り組んでいるタスクです。</value>
</data>
<data name="PresetColumn_Done" xml:space="preserve">
<value>完了</value>
</data>
<data name="PresetColumn_Done_Description" xml:space="preserve">
<value>完了したタスクです。</value>
</data>
<data name="PresetTag_Bug_Name" xml:space="preserve">
<value>バグ</value>
</data>
<data name="PresetTag_Bug_Description" xml:space="preserve">
<value>機能が正しく動作していません。</value>
</data>
<data name="PresetTag_Documentation_Name" xml:space="preserve">
<value>ドキュメント</value>
</data>
<data name="PresetTag_Documentation_Description" xml:space="preserve">
<value>ドキュメントの改善または追加。</value>
</data>
<data name="PresetTag_Duplicate_Name" xml:space="preserve">
<value>重複</value>
</data>
<data name="PresetTag_Duplicate_Description" xml:space="preserve">
<value>この課題またはプルリクエストはすでに存在します。</value>
</data>
<data name="PresetTag_Enhancement_Name" xml:space="preserve">
<value>機能追加</value>
</data>
<data name="PresetTag_Enhancement_Description" xml:space="preserve">
<value>新しい機能やリクエスト。</value>
</data>
<data name="PresetTag_HelpWanted_Name" xml:space="preserve">
<value>ヘルプ募集</value>
</data>
<data name="PresetTag_HelpWanted_Description" xml:space="preserve">
<value>特別な注意が必要です。</value>
</data>
<data name="PresetTag_Invalid_Name" xml:space="preserve">
<value>無効</value>
</data>
<data name="PresetTag_Invalid_Description" xml:space="preserve">
<value>正しくないようです。</value>
</data>
<data name="PresetTag_Question_Name" xml:space="preserve">
<value>質問</value>
</data>
<data name="PresetTag_Question_Description" xml:space="preserve">
<value>さらなる情報が必要です。</value>
</data>
<data name="PresetTag_Wontfix_Name" xml:space="preserve">
<value>対応予定なし</value>
</data>
<data name="PresetTag_Wontfix_Description" xml:space="preserve">
<value>対応する予定はありません。</value>
</data>
<data name="Export_FileNamePattern" xml:space="preserve">
<value>{0}-エクスポート-{1:yyyyMMdd-HHmmss}.md</value>
</data>
<data name="Export_TimePattern" xml:space="preserve">
<value>yyyy年M月d日 HH:mm:ss</value>
</data>
<data name="Export_WorkspaceHeading" xml:space="preserve">
<value># {0}</value>
</data>
<data name="Export_ExportedAtLine" xml:space="preserve">
<value>&gt; エクスポート日時:{0}</value>
</data>
<data name="Export_ColumnHeading" xml:space="preserve">
<value>## 列:{0}({1})</value>
</data>
<data name="Export_TagsLine" xml:space="preserve">
<value>- タグ:{0}</value>
</data>
<data name="Export_CreatedModifiedLine" xml:space="preserve">
<value>- 作成日時:{0} 更新日時:{1}</value>
</data>
<data name="Export_TagsSummaryHeading" xml:space="preserve">
<value>## タグ一覧</value>
</data>
<data name="Export_TagsTableHeader" xml:space="preserve">
<value>| 名前 | 色 | 説明 | 使用数 |</value>
</data>
<data name="Export_Done_Title" xml:space="preserve">
<value>エクスポート完了</value>
</data>
<data name="Export_Done_Message" xml:space="preserve">
<value>エクスポート先:{0}</value>
</data>
<data name="Error_OpenFailed_Title" xml:space="preserve">
<value>ワークスペースを開けません</value>
</data>
<data name="Error_OpenFailed_SchemaTooNew" xml:space="preserve">
<value>ワークスペースデータベースはより新しいバージョンの YKanBan で作成されています(schema バージョン {1}、このバージョンは {2} まで対応):{0}</value>
</data>
<data name="Error_OpenFailed_Database" xml:space="preserve">
<value>ワークスペースデータベースを開けないか、破損しています:{0}</value>
</data>
<data name="Error_OpenFailed_DatabaseMissing" xml:space="preserve">
<value>ワークスペースデータベース(.ykanban/ykanban.db)が見つかりません。-wal、-shm ファイルと一緒にバックアップから復元するか、.ykanban フォルダーを削除してワークスペースを再初期化してください:{0}</value>
</data>
<data name="Error_OpenFailed_AccessDenied" xml:space="preserve">
<value>ワークスペースへのアクセスが拒否されました:{0}</value>
</data>
<data name="Error_OpenFailed_Io" xml:space="preserve">
<value>ワークスペースを開くときにファイルシステムエラーが発生しました:{0}</value>
</data>
<data name="Error_OpenFailed_Generic" xml:space="preserve">
<value>ワークスペースを開くときに予期しないエラーが発生しました:{0}</value>
</data>
<data name="Error_OpenFailed_Details" xml:space="preserve">
<value>詳細</value>
</data>
</root>
+298 -229
View File
@@ -25,6 +25,12 @@
<data name="Common_Cancel" xml:space="preserve"> <data name="Common_Cancel" xml:space="preserve">
<value>Cancel</value> <value>Cancel</value>
</data> </data>
<data name="Common_Delete" xml:space="preserve">
<value>Delete</value>
</data>
<data name="Common_Edit" xml:space="preserve">
<value>Edit</value>
</data>
<data name="Main_Export" xml:space="preserve"> <data name="Main_Export" xml:space="preserve">
<value>Export</value> <value>Export</value>
</data> </data>
@@ -40,6 +46,219 @@
<data name="Tab_Board" xml:space="preserve"> <data name="Tab_Board" xml:space="preserve">
<value>Board</value> <value>Board</value>
</data> </data>
<data name="Board_SearchPlaceholder" xml:space="preserve">
<value>Search…</value>
</data>
<data name="Board_Search" xml:space="preserve">
<value>Search</value>
</data>
<data name="Board_ClearSearch" xml:space="preserve">
<value>Clear</value>
</data>
<data name="Board_AddColumn" xml:space="preserve">
<value>Add Column</value>
</data>
<data name="Board_ColumnWidth" xml:space="preserve">
<value>Column Width</value>
</data>
<data name="Board_SortCard" xml:space="preserve">
<value>Card Sort</value>
</data>
<data name="Board_SortColumn" xml:space="preserve">
<value>Column Sort</value>
</data>
<data name="Board_Display" xml:space="preserve">
<value>Display</value>
</data>
<data name="Board_NoColumns" xml:space="preserve">
<value>No columns yet.</value>
</data>
<data name="Board_FilterActive" xml:space="preserve">
<value>Board is filtered</value>
</data>
<data name="Board_FilterInactive" xml:space="preserve">
<value>Board is not filtered</value>
</data>
<data name="Search_Error_Title" xml:space="preserve">
<value>Invalid search</value>
</data>
<data name="Search_Error_Message" xml:space="preserve">
<value>The query expression is invalid. Details: {0}</value>
</data>
<data name="Sort_IdAsc" xml:space="preserve">
<value>ID Ascending</value>
</data>
<data name="Sort_IdDesc" xml:space="preserve">
<value>ID Descending</value>
</data>
<data name="Sort_CreatedAsc" xml:space="preserve">
<value>Created Ascending</value>
</data>
<data name="Sort_CreatedDesc" xml:space="preserve">
<value>Created Descending</value>
</data>
<data name="Sort_UpdatedAsc" xml:space="preserve">
<value>Modified Ascending</value>
</data>
<data name="Sort_UpdatedDesc" xml:space="preserve">
<value>Modified Descending</value>
</data>
<data name="Sort_TitleAsc" xml:space="preserve">
<value>Title Ascending</value>
</data>
<data name="Sort_TitleDesc" xml:space="preserve">
<value>Title Descending</value>
</data>
<data name="Column_AddCard" xml:space="preserve">
<value>New Card</value>
</data>
<data name="Column_Edit" xml:space="preserve">
<value>Edit</value>
</data>
<data name="Column_Delete" xml:space="preserve">
<value>Delete</value>
</data>
<data name="Card_Delete" xml:space="preserve">
<value>Delete</value>
</data>
<data name="Card_Move" xml:space="preserve">
<value>Move to Column…</value>
</data>
<data name="ColumnDialog_AddTitle" xml:space="preserve">
<value>New Column</value>
</data>
<data name="ColumnDialog_EditTitle" xml:space="preserve">
<value>Edit Column</value>
</data>
<data name="ColumnDialog_Title" xml:space="preserve">
<value>Title</value>
</data>
<data name="ColumnDialog_Description" xml:space="preserve">
<value>Description</value>
</data>
<data name="ColumnDialog_InvalidTitle" xml:space="preserve">
<value>The title is empty or already used.</value>
</data>
<data name="CardDialog_AddTitle" xml:space="preserve">
<value>New Card</value>
</data>
<data name="CardDialog_EditTitle" xml:space="preserve">
<value>Edit Card</value>
</data>
<data name="CardDialog_Title" xml:space="preserve">
<value>Title</value>
</data>
<data name="CardDialog_Content" xml:space="preserve">
<value>Content</value>
</data>
<data name="CardDialog_Tags" xml:space="preserve">
<value>Tags</value>
</data>
<data name="CardDialog_AddTag" xml:space="preserve">
<value>Add Tag</value>
</data>
<data name="CardDialog_Id" xml:space="preserve">
<value>ID: {0}</value>
</data>
<data name="CardDialog_Created" xml:space="preserve">
<value>Created: {0}</value>
</data>
<data name="CardDialog_Modified" xml:space="preserve">
<value>Modified: {0}</value>
</data>
<data name="CardDialog_TimePattern" xml:space="preserve">
<value>yyyy-MM-dd HH:mm</value>
</data>
<data name="CardDialog_Error" xml:space="preserve">
<value>Could not save the card.</value>
</data>
<data name="TagDialog_Title" xml:space="preserve">
<value>Add Tag</value>
</data>
<data name="TagDialog_Target" xml:space="preserve">
<value>Tag</value>
</data>
<data name="TagDialog_NoTargets" xml:space="preserve">
<value>There are no more tags to add.</value>
</data>
<data name="Tags_AddTag" xml:space="preserve">
<value>Add Tag</value>
</data>
<data name="Tags_Count" xml:space="preserve">
<value>{0} tags</value>
</data>
<data name="Tags_Empty" xml:space="preserve">
<value>No tags yet.</value>
</data>
<data name="Tags_Usage" xml:space="preserve">
<value>{0} cards</value>
</data>
<data name="TagEditor_AddTitle" xml:space="preserve">
<value>New Tag</value>
</data>
<data name="TagEditor_EditTitle" xml:space="preserve">
<value>Edit Tag</value>
</data>
<data name="TagEditor_Name" xml:space="preserve">
<value>Name</value>
</data>
<data name="TagEditor_Color" xml:space="preserve">
<value>Color</value>
</data>
<data name="TagEditor_Description" xml:space="preserve">
<value>Description</value>
</data>
<data name="TagEditor_InvalidName" xml:space="preserve">
<value>The name is empty or already used.</value>
</data>
<data name="DeleteTag_Confirm_Title" xml:space="preserve">
<value>Delete Tag</value>
</data>
<data name="DeleteTag_Confirm_Message" xml:space="preserve">
<value>Delete tag "{0}"? It will be removed from {1} card(s).</value>
</data>
<data name="MoveDialog_Title" xml:space="preserve">
<value>Move Card</value>
</data>
<data name="MoveDialog_Target" xml:space="preserve">
<value>Target Column</value>
</data>
<data name="MoveDialog_NoTargets" xml:space="preserve">
<value>There is nowhere to move this card.</value>
</data>
<data name="WidthPreset_Narrow" xml:space="preserve">
<value>Narrow</value>
</data>
<data name="WidthPreset_Standard" xml:space="preserve">
<value>Standard</value>
</data>
<data name="WidthPreset_Wide" xml:space="preserve">
<value>Wide</value>
</data>
<data name="WidthPreset_Custom" xml:space="preserve">
<value>Custom</value>
</data>
<data name="WidthDialog_Pixels" xml:space="preserve">
<value>Pixels (160–720)</value>
</data>
<data name="Confirm_DeleteColumn_Title" xml:space="preserve">
<value>Delete Column</value>
</data>
<data name="Confirm_DeleteColumn_Message" xml:space="preserve">
<value>Delete column "{0}" and its {1} card(s)?</value>
</data>
<data name="Confirm_DeleteCard_Title" xml:space="preserve">
<value>Delete Card</value>
</data>
<data name="Confirm_DeleteCard_Message" xml:space="preserve">
<value>Delete card #{0}?</value>
</data>
<data name="Confirm_Discard_Title" xml:space="preserve">
<value>Discard Changes</value>
</data>
<data name="Confirm_Discard_Message" xml:space="preserve">
<value>Discard the unsaved changes?</value>
</data>
<data name="Error_Argument_Title" xml:space="preserve"> <data name="Error_Argument_Title" xml:space="preserve">
<value>Invalid arguments</value> <value>Invalid arguments</value>
</data> </data>
@@ -49,12 +268,6 @@
<data name="Error_Argument_Usage" xml:space="preserve"> <data name="Error_Argument_Usage" xml:space="preserve">
<value>Usage: ykanban &lt;path&gt;</value> <value>Usage: ykanban &lt;path&gt;</value>
</data> </data>
<data name="Error_DirectoryMissing_Title" xml:space="preserve">
<value>Folder not found</value>
</data>
<data name="Error_DirectoryMissing_Message" xml:space="preserve">
<value>The folder does not exist: {0}</value>
</data>
<data name="Error_NotInitialized_Title" xml:space="preserve"> <data name="Error_NotInitialized_Title" xml:space="preserve">
<value>No workspace here</value> <value>No workspace here</value>
</data> </data>
@@ -62,7 +275,7 @@
<value>The folder does not contain a .ykanban workspace: {0}</value> <value>The folder does not contain a .ykanban workspace: {0}</value>
</data> </data>
<data name="Error_NotInitialized_Initialize" xml:space="preserve"> <data name="Error_NotInitialized_Initialize" xml:space="preserve">
<value>Initialize workspace</value> <value>Initialize Workspace</value>
</data> </data>
<data name="Error_LockConflict_Title" xml:space="preserve"> <data name="Error_LockConflict_Title" xml:space="preserve">
<value>Workspace locked</value> <value>Workspace locked</value>
@@ -70,27 +283,6 @@
<data name="Error_LockConflict_Message" xml:space="preserve"> <data name="Error_LockConflict_Message" xml:space="preserve">
<value>The workspace is already open in another instance: {0}</value> <value>The workspace is already open in another instance: {0}</value>
</data> </data>
<data name="Error_OpenFailed_Title" xml:space="preserve">
<value>Cannot open workspace</value>
</data>
<data name="Error_OpenFailed_SchemaTooNew" xml:space="preserve">
<value>The workspace database was created by a newer version of YKanBan (schema version {1}; this version supports up to {2}): {0}</value>
</data>
<data name="Error_OpenFailed_Database" xml:space="preserve">
<value>The workspace database cannot be opened or is damaged: {0}</value>
</data>
<data name="Error_OpenFailed_AccessDenied" xml:space="preserve">
<value>Access to the workspace was denied: {0}</value>
</data>
<data name="Error_OpenFailed_Io" xml:space="preserve">
<value>A file system error occurred while opening the workspace: {0}</value>
</data>
<data name="Error_OpenFailed_Generic" xml:space="preserve">
<value>An unexpected error occurred while opening the workspace: {0}</value>
</data>
<data name="Error_OpenFailed_Details" xml:space="preserve">
<value>Details</value>
</data>
<data name="Settings_Title" xml:space="preserve"> <data name="Settings_Title" xml:space="preserve">
<value>Settings</value> <value>Settings</value>
</data> </data>
@@ -100,12 +292,6 @@
<data name="Settings_Language_RestartNotice" xml:space="preserve"> <data name="Settings_Language_RestartNotice" xml:space="preserve">
<value>Takes effect after restart</value> <value>Takes effect after restart</value>
</data> </data>
<data name="Settings_LanguageEnglish" xml:space="preserve">
<value>English</value>
</data>
<data name="Settings_LanguageChinese" xml:space="preserve">
<value>简体中文</value>
</data>
<data name="Settings_Theme" xml:space="preserve"> <data name="Settings_Theme" xml:space="preserve">
<value>Theme</value> <value>Theme</value>
</data> </data>
@@ -116,7 +302,7 @@
<value>Dark</value> <value>Dark</value>
</data> </data>
<data name="Settings_ThemeFollowSystem" xml:space="preserve"> <data name="Settings_ThemeFollowSystem" xml:space="preserve">
<value>Follow system</value> <value>Follow System</value>
</data> </data>
<data name="Settings_Confirmations" xml:space="preserve"> <data name="Settings_Confirmations" xml:space="preserve">
<value>Confirmations</value> <value>Confirmations</value>
@@ -151,12 +337,69 @@
<data name="PresetColumn_Todo" xml:space="preserve"> <data name="PresetColumn_Todo" xml:space="preserve">
<value>To Do</value> <value>To Do</value>
</data> </data>
<data name="PresetColumn_Todo_Description" xml:space="preserve">
<value>Tasks that are planned but not started.</value>
</data>
<data name="PresetColumn_InProgress" xml:space="preserve"> <data name="PresetColumn_InProgress" xml:space="preserve">
<value>In Progress</value> <value>In Progress</value>
</data> </data>
<data name="PresetColumn_InProgress_Description" xml:space="preserve">
<value>Tasks that are currently being worked on.</value>
</data>
<data name="PresetColumn_Done" xml:space="preserve"> <data name="PresetColumn_Done" xml:space="preserve">
<value>Done</value> <value>Done</value>
</data> </data>
<data name="PresetColumn_Done_Description" xml:space="preserve">
<value>Tasks that have been completed.</value>
</data>
<data name="PresetTag_Bug_Name" xml:space="preserve">
<value>bug</value>
</data>
<data name="PresetTag_Bug_Description" xml:space="preserve">
<value>Something isn't working</value>
</data>
<data name="PresetTag_Documentation_Name" xml:space="preserve">
<value>documentation</value>
</data>
<data name="PresetTag_Documentation_Description" xml:space="preserve">
<value>Improvements or additions to documentation</value>
</data>
<data name="PresetTag_Duplicate_Name" xml:space="preserve">
<value>duplicate</value>
</data>
<data name="PresetTag_Duplicate_Description" xml:space="preserve">
<value>This issue or pull request already exists</value>
</data>
<data name="PresetTag_Enhancement_Name" xml:space="preserve">
<value>enhancement</value>
</data>
<data name="PresetTag_Enhancement_Description" xml:space="preserve">
<value>New feature or request</value>
</data>
<data name="PresetTag_HelpWanted_Name" xml:space="preserve">
<value>help-wanted</value>
</data>
<data name="PresetTag_HelpWanted_Description" xml:space="preserve">
<value>Extra attention is needed</value>
</data>
<data name="PresetTag_Invalid_Name" xml:space="preserve">
<value>invalid</value>
</data>
<data name="PresetTag_Invalid_Description" xml:space="preserve">
<value>This doesn't seem right</value>
</data>
<data name="PresetTag_Question_Name" xml:space="preserve">
<value>question</value>
</data>
<data name="PresetTag_Question_Description" xml:space="preserve">
<value>Further information is requested</value>
</data>
<data name="PresetTag_Wontfix_Name" xml:space="preserve">
<value>wontfix</value>
</data>
<data name="PresetTag_Wontfix_Description" xml:space="preserve">
<value>This will not be worked on</value>
</data>
<data name="Export_FileNamePattern" xml:space="preserve"> <data name="Export_FileNamePattern" xml:space="preserve">
<value>{0}-export-{1:yyyyMMdd-HHmmss}.md</value> <value>{0}-export-{1:yyyyMMdd-HHmmss}.md</value>
</data> </data>
@@ -184,208 +427,34 @@
<data name="Export_TagsTableHeader" xml:space="preserve"> <data name="Export_TagsTableHeader" xml:space="preserve">
<value>| Name | Color | Description | Usage |</value> <value>| Name | Color | Description | Usage |</value>
</data> </data>
<data name="Common_Delete" xml:space="preserve"> <data name="Export_Done_Title" xml:space="preserve">
<value>Delete</value> <value>Export Complete</value>
</data> </data>
<data name="Common_Discard" xml:space="preserve"> <data name="Export_Done_Message" xml:space="preserve">
<value>Discard</value> <value>Exported to: {0}</value>
</data> </data>
<data name="Common_TimePattern" xml:space="preserve"> <data name="Error_OpenFailed_Title" xml:space="preserve">
<value>yyyy-MM-dd HH:mm</value> <value>Cannot open workspace</value>
</data> </data>
<data name="Board_AddColumn" xml:space="preserve"> <data name="Error_OpenFailed_SchemaTooNew" xml:space="preserve">
<value>New column</value> <value>The workspace database was created by a newer version of YKanBan (schema version {1}; this version supports up to {2}): {0}</value>
</data> </data>
<data name="Board_ColumnWidth" xml:space="preserve"> <data name="Error_OpenFailed_Database" xml:space="preserve">
<value>Column width</value> <value>The workspace database cannot be opened or is damaged: {0}</value>
</data> </data>
<data name="Board_Sort" xml:space="preserve"> <data name="Error_OpenFailed_DatabaseMissing" xml:space="preserve">
<value>Card order</value> <value>The workspace database (.ykanban/ykanban.db) is missing. Restore it from a backup together with its -wal and -shm files, or delete the .ykanban folder to initialize the workspace again: {0}</value>
</data> </data>
<data name="Board_AddCard" xml:space="preserve"> <data name="Error_OpenFailed_AccessDenied" xml:space="preserve">
<value>New card</value> <value>Access to the workspace was denied: {0}</value>
</data> </data>
<data name="Sort_Id" xml:space="preserve"> <data name="Error_OpenFailed_Io" xml:space="preserve">
<value>By id</value> <value>A file system error occurred while opening the workspace: {0}</value>
</data> </data>
<data name="Sort_UpdatedAt" xml:space="preserve"> <data name="Error_OpenFailed_Generic" xml:space="preserve">
<value>Recently modified</value> <value>An unexpected error occurred while opening the workspace: {0}</value>
</data> </data>
<data name="Sort_Title" xml:space="preserve"> <data name="Error_OpenFailed_Details" xml:space="preserve">
<value>By title</value> <value>Details</value>
</data>
<data name="Menu_More" xml:space="preserve">
<value>More</value>
</data>
<data name="Menu_Edit" xml:space="preserve">
<value>Edit</value>
</data>
<data name="Menu_Delete" xml:space="preserve">
<value>Delete</value>
</data>
<data name="Menu_MoveTo" xml:space="preserve">
<value>Move to column</value>
</data>
<data name="Field_Title" xml:space="preserve">
<value>Title</value>
</data>
<data name="Field_Description" xml:space="preserve">
<value>Description</value>
</data>
<data name="Field_Content" xml:space="preserve">
<value>Content</value>
</data>
<data name="Field_Tags" xml:space="preserve">
<value>Tags</value>
</data>
<data name="Field_Name" xml:space="preserve">
<value>Name</value>
</data>
<data name="Field_Color" xml:space="preserve">
<value>#RRGGBB</value>
</data>
<data name="ColumnEditor_TitleNew" xml:space="preserve">
<value>New column</value>
</data>
<data name="ColumnEditor_TitleEdit" xml:space="preserve">
<value>Edit column</value>
</data>
<data name="ColumnWidth_Title" xml:space="preserve">
<value>Column width</value>
</data>
<data name="ColumnWidth_Narrow" xml:space="preserve">
<value>Narrow ({0} px)</value>
</data>
<data name="ColumnWidth_Standard" xml:space="preserve">
<value>Standard ({0} px)</value>
</data>
<data name="ColumnWidth_Wide" xml:space="preserve">
<value>Wide ({0} px)</value>
</data>
<data name="ColumnWidth_Custom" xml:space="preserve">
<value>Custom</value>
</data>
<data name="ColumnWidth_Range" xml:space="preserve">
<value>{0}–{1} px</value>
</data>
<data name="CardEditor_TitleNew" xml:space="preserve">
<value>New card</value>
</data>
<data name="CardEditor_TitleEdit" xml:space="preserve">
<value>Edit card</value>
</data>
<data name="CardEditor_TitleWatermark" xml:space="preserve">
<value>No title</value>
</data>
<data name="CardEditor_Created" xml:space="preserve">
<value>Created {0}</value>
</data>
<data name="CardEditor_Modified" xml:space="preserve">
<value>Modified {0}</value>
</data>
<data name="CardEditor_AddTag" xml:space="preserve">
<value>Add tag</value>
</data>
<data name="CardEditor_RemoveTag" xml:space="preserve">
<value>Remove tag</value>
</data>
<data name="TagPicker_Title" xml:space="preserve">
<value>Add tag</value>
</data>
<data name="TagPicker_FilterWatermark" xml:space="preserve">
<value>Filter tags</value>
</data>
<data name="TagPicker_NoMatches" xml:space="preserve">
<value>No matching tags</value>
</data>
<data name="TagPicker_NewTag" xml:space="preserve">
<value>New tag</value>
</data>
<data name="TagPicker_Create" xml:space="preserve">
<value>Create and add</value>
</data>
<data name="Confirm_Title" xml:space="preserve">
<value>Confirm</value>
</data>
<data name="Confirm_DeleteCard" xml:space="preserve">
<value>Delete card "{0}"?</value>
</data>
<data name="Confirm_DeleteColumn" xml:space="preserve">
<value>Delete column "{0}" and its {1} card(s)?</value>
</data>
<data name="Confirm_DiscardEdit" xml:space="preserve">
<value>Discard the unsaved changes?</value>
</data>
<data name="Error_Column_TitleRequired" xml:space="preserve">
<value>The column title is required.</value>
</data>
<data name="Error_Column_Duplicate" xml:space="preserve">
<value>A column named "{0}" already exists (names are case-insensitive).</value>
</data>
<data name="Error_Tag_NameRequired" xml:space="preserve">
<value>The tag name is required.</value>
</data>
<data name="Error_Tag_Duplicate" xml:space="preserve">
<value>A tag named "{0}" already exists (names are case-insensitive).</value>
</data>
<data name="Error_Tag_InvalidColor" xml:space="preserve">
<value>The color must be written as #RRGGBB.</value>
</data>
<data name="Error_SaveFailed" xml:space="preserve">
<value>Saving failed: {0}</value>
</data>
<data name="Error_Operation_Title" xml:space="preserve">
<value>Operation failed</value>
</data>
<data name="Error_Operation_Message" xml:space="preserve">
<value>The change could not be written to the workspace. The board shows the stored state.</value>
</data>
<data name="TagEditor_TitleNew" xml:space="preserve">
<value>New tag</value>
</data>
<data name="TagEditor_TitleEdit" xml:space="preserve">
<value>Edit tag</value>
</data>
<data name="TagEditor_ColorLabel" xml:space="preserve">
<value>Color</value>
</data>
<data name="Tags_AddTag" xml:space="preserve">
<value>New tag</value>
</data>
<data name="Tags_Summary" xml:space="preserve">
<value>{0} tag(s)</value>
</data>
<data name="Tags_UsageCount" xml:space="preserve">
<value>{0} card(s)</value>
</data>
<data name="Tags_Empty" xml:space="preserve">
<value>No tags yet.</value>
</data>
<data name="Confirm_DeleteTag" xml:space="preserve">
<value>Delete tag "{0}"? It will be removed from {1} card(s).</value>
</data>
<data name="Board_SearchWatermark" xml:space="preserve">
<value>Search, e.g. tag:bug OR title:login</value>
</data>
<data name="Board_Search" xml:space="preserve">
<value>Search</value>
</data>
<data name="Board_ClearSearch" xml:space="preserve">
<value>Clear</value>
</data>
<data name="Search_Error_Title" xml:space="preserve">
<value>Invalid search</value>
</data>
<data name="Search_Error_Message" xml:space="preserve">
<value>The query expression is invalid. Details: {0}</value>
</data>
<data name="Export_FileTypeMarkdown" xml:space="preserve">
<value>Markdown document</value>
</data>
<data name="Export_Failed_Title" xml:space="preserve">
<value>Export failed</value>
</data>
<data name="Export_Failed_Message" xml:space="preserve">
<value>The export file could not be written.</value>
</data> </data>
</root> </root>
+296 -227
View File
@@ -25,6 +25,12 @@
<data name="Common_Cancel" xml:space="preserve"> <data name="Common_Cancel" xml:space="preserve">
<value>取消</value> <value>取消</value>
</data> </data>
<data name="Common_Delete" xml:space="preserve">
<value>删除</value>
</data>
<data name="Common_Edit" xml:space="preserve">
<value>编辑</value>
</data>
<data name="Main_Export" xml:space="preserve"> <data name="Main_Export" xml:space="preserve">
<value>导出</value> <value>导出</value>
</data> </data>
@@ -40,6 +46,219 @@
<data name="Tab_Board" xml:space="preserve"> <data name="Tab_Board" xml:space="preserve">
<value>看板</value> <value>看板</value>
</data> </data>
<data name="Board_SearchPlaceholder" xml:space="preserve">
<value>搜索…</value>
</data>
<data name="Board_Search" xml:space="preserve">
<value>搜索</value>
</data>
<data name="Board_ClearSearch" xml:space="preserve">
<value>清空</value>
</data>
<data name="Board_AddColumn" xml:space="preserve">
<value>新增列</value>
</data>
<data name="Board_ColumnWidth" xml:space="preserve">
<value>列宽</value>
</data>
<data name="Board_SortCard" xml:space="preserve">
<value>卡片排序</value>
</data>
<data name="Board_SortColumn" xml:space="preserve">
<value>列排序</value>
</data>
<data name="Board_Display" xml:space="preserve">
<value>显示</value>
</data>
<data name="Board_NoColumns" xml:space="preserve">
<value>还没有列。</value>
</data>
<data name="Board_FilterActive" xml:space="preserve">
<value>看板处于过滤状态</value>
</data>
<data name="Board_FilterInactive" xml:space="preserve">
<value>看板未处于过滤状态</value>
</data>
<data name="Search_Error_Title" xml:space="preserve">
<value>搜索表达式有误</value>
</data>
<data name="Search_Error_Message" xml:space="preserve">
<value>查询表达式有误,详情:{0}</value>
</data>
<data name="Sort_IdAsc" xml:space="preserve">
<value>ID 正序</value>
</data>
<data name="Sort_IdDesc" xml:space="preserve">
<value>ID 倒序</value>
</data>
<data name="Sort_CreatedAsc" xml:space="preserve">
<value>创建时间正序</value>
</data>
<data name="Sort_CreatedDesc" xml:space="preserve">
<value>创建时间倒序</value>
</data>
<data name="Sort_UpdatedAsc" xml:space="preserve">
<value>修改时间正序</value>
</data>
<data name="Sort_UpdatedDesc" xml:space="preserve">
<value>修改时间倒序</value>
</data>
<data name="Sort_TitleAsc" xml:space="preserve">
<value>标题正序</value>
</data>
<data name="Sort_TitleDesc" xml:space="preserve">
<value>标题倒序</value>
</data>
<data name="Column_AddCard" xml:space="preserve">
<value>新建卡片</value>
</data>
<data name="Column_Edit" xml:space="preserve">
<value>编辑</value>
</data>
<data name="Column_Delete" xml:space="preserve">
<value>删除</value>
</data>
<data name="Card_Delete" xml:space="preserve">
<value>删除</value>
</data>
<data name="Card_Move" xml:space="preserve">
<value>移动到列…</value>
</data>
<data name="ColumnDialog_AddTitle" xml:space="preserve">
<value>新增列</value>
</data>
<data name="ColumnDialog_EditTitle" xml:space="preserve">
<value>编辑列</value>
</data>
<data name="ColumnDialog_Title" xml:space="preserve">
<value>标题</value>
</data>
<data name="ColumnDialog_Description" xml:space="preserve">
<value>描述</value>
</data>
<data name="ColumnDialog_InvalidTitle" xml:space="preserve">
<value>标题为空或已被使用。</value>
</data>
<data name="CardDialog_AddTitle" xml:space="preserve">
<value>新增卡片</value>
</data>
<data name="CardDialog_EditTitle" xml:space="preserve">
<value>编辑卡片</value>
</data>
<data name="CardDialog_Title" xml:space="preserve">
<value>标题</value>
</data>
<data name="CardDialog_Content" xml:space="preserve">
<value>内容</value>
</data>
<data name="CardDialog_Tags" xml:space="preserve">
<value>标签</value>
</data>
<data name="CardDialog_AddTag" xml:space="preserve">
<value>添加标签</value>
</data>
<data name="CardDialog_Id" xml:space="preserve">
<value>编号:{0}</value>
</data>
<data name="CardDialog_Created" xml:space="preserve">
<value>创建:{0}</value>
</data>
<data name="CardDialog_Modified" xml:space="preserve">
<value>修改:{0}</value>
</data>
<data name="CardDialog_TimePattern" xml:space="preserve">
<value>yyyy年M月d日 HH:mm</value>
</data>
<data name="CardDialog_Error" xml:space="preserve">
<value>无法保存卡片。</value>
</data>
<data name="TagDialog_Title" xml:space="preserve">
<value>添加标签</value>
</data>
<data name="TagDialog_Target" xml:space="preserve">
<value>标签</value>
</data>
<data name="TagDialog_NoTargets" xml:space="preserve">
<value>没有可添加的标签。</value>
</data>
<data name="Tags_AddTag" xml:space="preserve">
<value>添加标签</value>
</data>
<data name="Tags_Count" xml:space="preserve">
<value>{0} 个标签</value>
</data>
<data name="Tags_Empty" xml:space="preserve">
<value>还没有标签。</value>
</data>
<data name="Tags_Usage" xml:space="preserve">
<value>{0} 张卡片</value>
</data>
<data name="TagEditor_AddTitle" xml:space="preserve">
<value>新建标签</value>
</data>
<data name="TagEditor_EditTitle" xml:space="preserve">
<value>编辑标签</value>
</data>
<data name="TagEditor_Name" xml:space="preserve">
<value>名称</value>
</data>
<data name="TagEditor_Color" xml:space="preserve">
<value>颜色</value>
</data>
<data name="TagEditor_Description" xml:space="preserve">
<value>描述</value>
</data>
<data name="TagEditor_InvalidName" xml:space="preserve">
<value>名称为空或已被使用。</value>
</data>
<data name="DeleteTag_Confirm_Title" xml:space="preserve">
<value>删除标签</value>
</data>
<data name="DeleteTag_Confirm_Message" xml:space="preserve">
<value>删除标签“{0}”?将从 {1} 张卡片中移除。</value>
</data>
<data name="MoveDialog_Title" xml:space="preserve">
<value>移动卡片</value>
</data>
<data name="MoveDialog_Target" xml:space="preserve">
<value>目标列</value>
</data>
<data name="MoveDialog_NoTargets" xml:space="preserve">
<value>没有可移动到的目标列。</value>
</data>
<data name="WidthPreset_Narrow" xml:space="preserve">
<value>窄</value>
</data>
<data name="WidthPreset_Standard" xml:space="preserve">
<value>标准</value>
</data>
<data name="WidthPreset_Wide" xml:space="preserve">
<value>宽</value>
</data>
<data name="WidthPreset_Custom" xml:space="preserve">
<value>自定义</value>
</data>
<data name="WidthDialog_Pixels" xml:space="preserve">
<value>像素(160–720)</value>
</data>
<data name="Confirm_DeleteColumn_Title" xml:space="preserve">
<value>删除列</value>
</data>
<data name="Confirm_DeleteColumn_Message" xml:space="preserve">
<value>删除列“{0}”及其 {1} 张卡片?</value>
</data>
<data name="Confirm_DeleteCard_Title" xml:space="preserve">
<value>删除卡片</value>
</data>
<data name="Confirm_DeleteCard_Message" xml:space="preserve">
<value>删除卡片 #{0}?</value>
</data>
<data name="Confirm_Discard_Title" xml:space="preserve">
<value>放弃修改</value>
</data>
<data name="Confirm_Discard_Message" xml:space="preserve">
<value>放弃未保存的修改?</value>
</data>
<data name="Error_Argument_Title" xml:space="preserve"> <data name="Error_Argument_Title" xml:space="preserve">
<value>参数错误</value> <value>参数错误</value>
</data> </data>
@@ -49,12 +268,6 @@
<data name="Error_Argument_Usage" xml:space="preserve"> <data name="Error_Argument_Usage" xml:space="preserve">
<value>用法:ykanban &lt;路径&gt;</value> <value>用法:ykanban &lt;路径&gt;</value>
</data> </data>
<data name="Error_DirectoryMissing_Title" xml:space="preserve">
<value>目录不存在</value>
</data>
<data name="Error_DirectoryMissing_Message" xml:space="preserve">
<value>目录不存在:{0}</value>
</data>
<data name="Error_NotInitialized_Title" xml:space="preserve"> <data name="Error_NotInitialized_Title" xml:space="preserve">
<value>尚未初始化</value> <value>尚未初始化</value>
</data> </data>
@@ -70,27 +283,6 @@
<data name="Error_LockConflict_Message" xml:space="preserve"> <data name="Error_LockConflict_Message" xml:space="preserve">
<value>该工作区已在另一个实例中打开:{0}</value> <value>该工作区已在另一个实例中打开:{0}</value>
</data> </data>
<data name="Error_OpenFailed_Title" xml:space="preserve">
<value>无法打开工作区</value>
</data>
<data name="Error_OpenFailed_SchemaTooNew" xml:space="preserve">
<value>工作区数据库由更新版本的 YKanBan 创建(schema 版本 {1},当前版本最高支持 {2}):{0}</value>
</data>
<data name="Error_OpenFailed_Database" xml:space="preserve">
<value>工作区数据库无法打开或已损坏:{0}</value>
</data>
<data name="Error_OpenFailed_AccessDenied" xml:space="preserve">
<value>没有访问该工作区的权限:{0}</value>
</data>
<data name="Error_OpenFailed_Io" xml:space="preserve">
<value>打开工作区时发生文件系统错误:{0}</value>
</data>
<data name="Error_OpenFailed_Generic" xml:space="preserve">
<value>打开工作区时发生意外错误:{0}</value>
</data>
<data name="Error_OpenFailed_Details" xml:space="preserve">
<value>详细信息</value>
</data>
<data name="Settings_Title" xml:space="preserve"> <data name="Settings_Title" xml:space="preserve">
<value>设置</value> <value>设置</value>
</data> </data>
@@ -100,12 +292,6 @@
<data name="Settings_Language_RestartNotice" xml:space="preserve"> <data name="Settings_Language_RestartNotice" xml:space="preserve">
<value>重启后生效</value> <value>重启后生效</value>
</data> </data>
<data name="Settings_LanguageEnglish" xml:space="preserve">
<value>English</value>
</data>
<data name="Settings_LanguageChinese" xml:space="preserve">
<value>简体中文</value>
</data>
<data name="Settings_Theme" xml:space="preserve"> <data name="Settings_Theme" xml:space="preserve">
<value>主题</value> <value>主题</value>
</data> </data>
@@ -151,12 +337,69 @@
<data name="PresetColumn_Todo" xml:space="preserve"> <data name="PresetColumn_Todo" xml:space="preserve">
<value>待办</value> <value>待办</value>
</data> </data>
<data name="PresetColumn_Todo_Description" xml:space="preserve">
<value>已计划但尚未开始的任务。</value>
</data>
<data name="PresetColumn_InProgress" xml:space="preserve"> <data name="PresetColumn_InProgress" xml:space="preserve">
<value>进行中</value> <value>进行中</value>
</data> </data>
<data name="PresetColumn_InProgress_Description" xml:space="preserve">
<value>正在处理中的任务。</value>
</data>
<data name="PresetColumn_Done" xml:space="preserve"> <data name="PresetColumn_Done" xml:space="preserve">
<value>已完成</value> <value>已完成</value>
</data> </data>
<data name="PresetColumn_Done_Description" xml:space="preserve">
<value>已完成的任务。</value>
</data>
<data name="PresetTag_Bug_Name" xml:space="preserve">
<value>缺陷</value>
</data>
<data name="PresetTag_Bug_Description" xml:space="preserve">
<value>功能没有正常工作</value>
</data>
<data name="PresetTag_Documentation_Name" xml:space="preserve">
<value>文档</value>
</data>
<data name="PresetTag_Documentation_Description" xml:space="preserve">
<value>文档的改进或补充</value>
</data>
<data name="PresetTag_Duplicate_Name" xml:space="preserve">
<value>重复</value>
</data>
<data name="PresetTag_Duplicate_Description" xml:space="preserve">
<value>该问题或请求已存在</value>
</data>
<data name="PresetTag_Enhancement_Name" xml:space="preserve">
<value>增强</value>
</data>
<data name="PresetTag_Enhancement_Description" xml:space="preserve">
<value>新功能或请求</value>
</data>
<data name="PresetTag_HelpWanted_Name" xml:space="preserve">
<value>需要帮助</value>
</data>
<data name="PresetTag_HelpWanted_Description" xml:space="preserve">
<value>需要额外关注</value>
</data>
<data name="PresetTag_Invalid_Name" xml:space="preserve">
<value>无效</value>
</data>
<data name="PresetTag_Invalid_Description" xml:space="preserve">
<value>似乎不正确</value>
</data>
<data name="PresetTag_Question_Name" xml:space="preserve">
<value>疑问</value>
</data>
<data name="PresetTag_Question_Description" xml:space="preserve">
<value>需要进一步信息</value>
</data>
<data name="PresetTag_Wontfix_Name" xml:space="preserve">
<value>不予处理</value>
</data>
<data name="PresetTag_Wontfix_Description" xml:space="preserve">
<value>不会被处理</value>
</data>
<data name="Export_FileNamePattern" xml:space="preserve"> <data name="Export_FileNamePattern" xml:space="preserve">
<value>{0}-导出-{1:yyyyMMdd-HHmmss}.md</value> <value>{0}-导出-{1:yyyyMMdd-HHmmss}.md</value>
</data> </data>
@@ -184,208 +427,34 @@
<data name="Export_TagsTableHeader" xml:space="preserve"> <data name="Export_TagsTableHeader" xml:space="preserve">
<value>| 名称 | 颜色 | 描述 | 使用数 |</value> <value>| 名称 | 颜色 | 描述 | 使用数 |</value>
</data> </data>
<data name="Common_Delete" xml:space="preserve"> <data name="Export_Done_Title" xml:space="preserve">
<value>删除</value> <value>导出完成</value>
</data> </data>
<data name="Common_Discard" xml:space="preserve"> <data name="Export_Done_Message" xml:space="preserve">
<value>丢弃</value> <value>已导出到:{0}</value>
</data> </data>
<data name="Common_TimePattern" xml:space="preserve"> <data name="Error_OpenFailed_Title" xml:space="preserve">
<value>yyyy年M月d日 HH:mm</value> <value>无法打开工作区</value>
</data> </data>
<data name="Board_AddColumn" xml:space="preserve"> <data name="Error_OpenFailed_SchemaTooNew" xml:space="preserve">
<value>新建列</value> <value>工作区数据库由更新版本的 YKanBan 创建(schema 版本 {1},当前版本最高支持 {2}):{0}</value>
</data> </data>
<data name="Board_ColumnWidth" xml:space="preserve"> <data name="Error_OpenFailed_Database" xml:space="preserve">
<value>列宽</value> <value>工作区数据库无法打开或已损坏:{0}</value>
</data> </data>
<data name="Board_Sort" xml:space="preserve"> <data name="Error_OpenFailed_DatabaseMissing" xml:space="preserve">
<value>卡片排序</value> <value>工作区数据库(.ykanban/ykanban.db)不存在。请从备份恢复(连同 -wal、-shm 文件),或删除 .ykanban 文件夹后重新初始化:{0}</value>
</data> </data>
<data name="Board_AddCard" xml:space="preserve"> <data name="Error_OpenFailed_AccessDenied" xml:space="preserve">
<value>新建卡片</value> <value>没有访问该工作区的权限:{0}</value>
</data> </data>
<data name="Sort_Id" xml:space="preserve"> <data name="Error_OpenFailed_Io" xml:space="preserve">
<value>按 ID</value> <value>打开工作区时发生文件系统错误:{0}</value>
</data> </data>
<data name="Sort_UpdatedAt" xml:space="preserve"> <data name="Error_OpenFailed_Generic" xml:space="preserve">
<value>最近修改</value> <value>打开工作区时发生意外错误:{0}</value>
</data> </data>
<data name="Sort_Title" xml:space="preserve"> <data name="Error_OpenFailed_Details" xml:space="preserve">
<value>按标题</value> <value>详细信息</value>
</data>
<data name="Menu_More" xml:space="preserve">
<value>更多</value>
</data>
<data name="Menu_Edit" xml:space="preserve">
<value>编辑</value>
</data>
<data name="Menu_Delete" xml:space="preserve">
<value>删除</value>
</data>
<data name="Menu_MoveTo" xml:space="preserve">
<value>移动到列</value>
</data>
<data name="Field_Title" xml:space="preserve">
<value>标题</value>
</data>
<data name="Field_Description" xml:space="preserve">
<value>描述</value>
</data>
<data name="Field_Content" xml:space="preserve">
<value>内容</value>
</data>
<data name="Field_Tags" xml:space="preserve">
<value>标签</value>
</data>
<data name="Field_Name" xml:space="preserve">
<value>名称</value>
</data>
<data name="Field_Color" xml:space="preserve">
<value>#RRGGBB</value>
</data>
<data name="ColumnEditor_TitleNew" xml:space="preserve">
<value>新建列</value>
</data>
<data name="ColumnEditor_TitleEdit" xml:space="preserve">
<value>编辑列</value>
</data>
<data name="ColumnWidth_Title" xml:space="preserve">
<value>列宽</value>
</data>
<data name="ColumnWidth_Narrow" xml:space="preserve">
<value>窄({0} px)</value>
</data>
<data name="ColumnWidth_Standard" xml:space="preserve">
<value>标准({0} px)</value>
</data>
<data name="ColumnWidth_Wide" xml:space="preserve">
<value>宽({0} px)</value>
</data>
<data name="ColumnWidth_Custom" xml:space="preserve">
<value>自定义</value>
</data>
<data name="ColumnWidth_Range" xml:space="preserve">
<value>{0}–{1} px</value>
</data>
<data name="CardEditor_TitleNew" xml:space="preserve">
<value>新建卡片</value>
</data>
<data name="CardEditor_TitleEdit" xml:space="preserve">
<value>编辑卡片</value>
</data>
<data name="CardEditor_TitleWatermark" xml:space="preserve">
<value>无标题</value>
</data>
<data name="CardEditor_Created" xml:space="preserve">
<value>创建于 {0}</value>
</data>
<data name="CardEditor_Modified" xml:space="preserve">
<value>修改于 {0}</value>
</data>
<data name="CardEditor_AddTag" xml:space="preserve">
<value>添加标签</value>
</data>
<data name="CardEditor_RemoveTag" xml:space="preserve">
<value>移除标签</value>
</data>
<data name="TagPicker_Title" xml:space="preserve">
<value>添加标签</value>
</data>
<data name="TagPicker_FilterWatermark" xml:space="preserve">
<value>筛选标签</value>
</data>
<data name="TagPicker_NoMatches" xml:space="preserve">
<value>没有匹配的标签</value>
</data>
<data name="TagPicker_NewTag" xml:space="preserve">
<value>新建标签</value>
</data>
<data name="TagPicker_Create" xml:space="preserve">
<value>新建并添加</value>
</data>
<data name="Confirm_Title" xml:space="preserve">
<value>确认</value>
</data>
<data name="Confirm_DeleteCard" xml:space="preserve">
<value>删除卡片“{0}”?</value>
</data>
<data name="Confirm_DeleteColumn" xml:space="preserve">
<value>删除列“{0}”及其中的 {1} 张卡片?</value>
</data>
<data name="Confirm_DiscardEdit" xml:space="preserve">
<value>放弃未保存的更改?</value>
</data>
<data name="Error_Column_TitleRequired" xml:space="preserve">
<value>列标题不能为空。</value>
</data>
<data name="Error_Column_Duplicate" xml:space="preserve">
<value>已存在名为“{0}”的列(名称不区分大小写)。</value>
</data>
<data name="Error_Tag_NameRequired" xml:space="preserve">
<value>标签名称不能为空。</value>
</data>
<data name="Error_Tag_Duplicate" xml:space="preserve">
<value>已存在名为“{0}”的标签(名称不区分大小写)。</value>
</data>
<data name="Error_Tag_InvalidColor" xml:space="preserve">
<value>颜色须为 #RRGGBB 格式。</value>
</data>
<data name="Error_SaveFailed" xml:space="preserve">
<value>保存失败:{0}</value>
</data>
<data name="Error_Operation_Title" xml:space="preserve">
<value>操作失败</value>
</data>
<data name="Error_Operation_Message" xml:space="preserve">
<value>更改未能写入工作区,看板显示的是已保存的状态。</value>
</data>
<data name="TagEditor_TitleNew" xml:space="preserve">
<value>新建标签</value>
</data>
<data name="TagEditor_TitleEdit" xml:space="preserve">
<value>编辑标签</value>
</data>
<data name="TagEditor_ColorLabel" xml:space="preserve">
<value>颜色</value>
</data>
<data name="Tags_AddTag" xml:space="preserve">
<value>新建标签</value>
</data>
<data name="Tags_Summary" xml:space="preserve">
<value>共 {0} 个标签</value>
</data>
<data name="Tags_UsageCount" xml:space="preserve">
<value>{0} 张卡片</value>
</data>
<data name="Tags_Empty" xml:space="preserve">
<value>还没有标签。</value>
</data>
<data name="Confirm_DeleteTag" xml:space="preserve">
<value>删除标签“{0}”?将从 {1} 张卡片移除该标签。</value>
</data>
<data name="Board_SearchWatermark" xml:space="preserve">
<value>搜索,例如 tag:bug OR title:登录</value>
</data>
<data name="Board_Search" xml:space="preserve">
<value>搜索</value>
</data>
<data name="Board_ClearSearch" xml:space="preserve">
<value>清空</value>
</data>
<data name="Search_Error_Title" xml:space="preserve">
<value>搜索表达式错误</value>
</data>
<data name="Search_Error_Message" xml:space="preserve">
<value>查询表达式有误,详情:{0}</value>
</data>
<data name="Export_FileTypeMarkdown" xml:space="preserve">
<value>Markdown 文档</value>
</data>
<data name="Export_Failed_Title" xml:space="preserve">
<value>导出失败</value>
</data>
<data name="Export_Failed_Message" xml:space="preserve">
<value>无法写入导出文件。</value>
</data> </data>
</root> </root>
Binary file not shown.

Before

Width:  |  Height:  |  Size: 172 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 48 KiB

+47 -39
View File
@@ -1,25 +1,27 @@
using System.Globalization; using System.Globalization;
using System.Text; using System.Text;
using YKanBan.Models; using YKanBan.Models;
namespace YKanBan.Export; namespace YKanBan.Export;
/// <summary> /// <summary>
/// Generates the human-readable Markdown snapshot of a whole board. All /// Generates the human-readable Markdown snapshot of a whole board. All
/// template text and the time format come from the ResX resources in the current /// template text and the one time format come from the ResX resources in the
/// UI language; every timestamp (export time and card created/modified times) /// current UI language; every timestamp (export time and card created/modified
/// uses that one per-language pattern. Card bodies and column descriptions are /// times) uses that per-language pattern. The document uses the platform's
/// emitted verbatim; tag names become inline code with a long enough backtick /// newline. Card bodies and column descriptions are emitted verbatim; column and
/// fence; tag table cells escape '|' and turn line breaks into &lt;br&gt;. The /// card titles are collapsed to one line; tag names become inline code with a
/// output is meant for reading only — there is no re-import. /// long enough backtick fence; tag table cells escape '\' and '|' and turn line
/// breaks into &lt;br&gt;. The output is meant for reading only — there is no
/// re-import.
/// </summary> /// </summary>
public static class MarkdownExporter public static class MarkdownExporter {
{
/// <summary> /// <summary>
/// Renders the whole board to Markdown. /// Renders the whole board to Markdown.
/// </summary> /// </summary>
/// <param name="workspaceName">Workspace display name (the folder name).</param> /// <param name="workspaceName">Workspace display name (the folder name).</param>
/// <param name="columns">All columns; emitted in id order, empty columns kept.</param> /// <param name="columns">All columns, in id order; empty columns are kept.</param>
/// <param name="cards">All cards; grouped by column, id order within a column.</param> /// <param name="cards">All cards; grouped by column, id order within a column.</param>
/// <param name="tags">All tags with usage counts, in id order.</param> /// <param name="tags">All tags with usage counts, in id order.</param>
/// <param name="exportedAt">Export moment in local time.</param> /// <param name="exportedAt">Export moment in local time.</param>
@@ -29,33 +31,29 @@ public static class MarkdownExporter
IReadOnlyList<ColumnModel> columns, IReadOnlyList<ColumnModel> columns,
IReadOnlyList<CardModel> cards, IReadOnlyList<CardModel> cards,
IReadOnlyList<(TagModel Tag, long UsageCount)> tags, IReadOnlyList<(TagModel Tag, long UsageCount)> tags,
DateTimeOffset exportedAt) DateTimeOffset exportedAt) {
{
CultureInfo culture = Resources.Culture ?? CultureInfo.CurrentUICulture; CultureInfo culture = Resources.Culture ?? CultureInfo.CurrentUICulture;
var builder = new StringBuilder(); var builder = new StringBuilder();
// Header: workspace name and the export timestamp in the UI language's format. // Header: workspace name and the export timestamp in the UI language's format.
builder.AppendLine(string.Format(culture, Resources.Export_WorkspaceHeading, workspaceName)); builder.AppendLine(string.Format(culture, Resources.Export_WorkspaceHeading, SingleLine(workspaceName)));
builder.AppendLine(string.Format( builder.AppendLine(string.Format(
culture, Resources.Export_ExportedAtLine, exportedAt.ToString(Resources.Export_TimePattern, culture))); culture, Resources.Export_ExportedAtLine, exportedAt.ToString(Resources.Export_TimePattern, culture)));
builder.AppendLine(); builder.AppendLine();
// Board body: every column in id order, empty ones included; independent of // Board body: every column in id order, empty ones included; independent of
// the board's search filter and card sort option. // the board's search filter and card sort option.
foreach (ColumnModel column in columns.OrderBy(column => column.Id)) foreach (ColumnModel column in columns.OrderBy(column => column.Id)) {
{
IReadOnlyList<CardModel> cardsInColumn = IReadOnlyList<CardModel> cardsInColumn =
cards.Where(card => card.ColumnId == column.Id).OrderBy(card => card.Id).ToArray(); cards.Where(card => card.ColumnId == column.Id).OrderBy(card => card.Id).ToArray();
builder.AppendLine(string.Format(culture, Resources.Export_ColumnHeading, column.Title, cardsInColumn.Count)); builder.AppendLine(string.Format(culture, Resources.Export_ColumnHeading, SingleLine(column.Title), cardsInColumn.Count));
if (column.Description.Length > 0) if (column.Description.Length > 0) {
{
builder.AppendLine(column.Description); builder.AppendLine(column.Description);
} }
builder.AppendLine(); builder.AppendLine();
foreach (CardModel card in cardsInColumn) foreach (CardModel card in cardsInColumn) {
{
AppendCard(builder, card, culture); AppendCard(builder, card, culture);
} }
} }
@@ -66,16 +64,31 @@ public static class MarkdownExporter
/// <summary> /// <summary>
/// Builds the default export file name in the UI language, for example /// Builds the default export file name in the UI language, for example
/// "MyRepo-export-20260930-142537.md". /// "MyRepo-export-20260930-142537.md". Characters that are not allowed in a
/// file name on any supported platform are dropped from the workspace name
/// (a workspace at a drive root is named "D:\"); a name left empty falls
/// back to the application name.
/// </summary> /// </summary>
/// <param name="workspaceName">Workspace display name.</param> /// <param name="workspaceName">Workspace display name.</param>
/// <param name="exportedAt">Export moment.</param> /// <param name="exportedAt">Export moment.</param>
/// <returns>The file name.</returns> /// <returns>The file name.</returns>
public static string BuildFileName(string workspaceName, DateTimeOffset exportedAt) public static string BuildFileName(string workspaceName, DateTimeOffset exportedAt) {
{
CultureInfo culture = Resources.Culture ?? CultureInfo.CurrentUICulture; CultureInfo culture = Resources.Culture ?? CultureInfo.CurrentUICulture;
return string.Format(culture, Resources.Export_FileNamePattern, workspaceName, exportedAt); string safeName = new(workspaceName.Where(character => !IsInvalidFileNameCharacter(character)).ToArray());
if (safeName.Length == 0) {
safeName = Resources.App_Name;
} }
return string.Format(culture, Resources.Export_FileNamePattern, safeName, exportedAt);
}
/// <summary>
/// Tells whether a character is invalid in a file name on Windows, Linux or
/// macOS; the Windows set is the widest, so the result is the same on every platform.
/// </summary>
/// <param name="character">The character to test.</param>
/// <returns><see langword="true"/> when the character must not appear in a file name.</returns>
private static bool IsInvalidFileNameCharacter(char character) =>
character < ' ' || character is '<' or '>' or ':' or '"' or '/' or '\\' or '|' or '?' or '*';
/// <summary> /// <summary>
/// Appends one card block: heading, body, tags line and timestamps line. /// Appends one card block: heading, body, tags line and timestamps line.
@@ -83,20 +96,17 @@ public static class MarkdownExporter
/// <param name="builder">The output builder.</param> /// <param name="builder">The output builder.</param>
/// <param name="card">The card to render.</param> /// <param name="card">The card to render.</param>
/// <param name="culture">The UI culture.</param> /// <param name="culture">The UI culture.</param>
private static void AppendCard(StringBuilder builder, CardModel card, CultureInfo culture) private static void AppendCard(StringBuilder builder, CardModel card, CultureInfo culture) {
{
// Heading: "#id title"; an untitled card shows only the id. // Heading: "#id title"; an untitled card shows only the id.
builder.AppendLine(card.Title.Length == 0 builder.AppendLine(card.Title.Length == 0
? $"### #{card.Id}" ? $"### #{card.Id}"
: $"### #{card.Id} {SingleLine(card.Title)}"); : $"### #{card.Id} {SingleLine(card.Title)}");
if (card.Content.Length > 0) if (card.Content.Length > 0) {
{
builder.AppendLine(card.Content); builder.AppendLine(card.Content);
} }
if (card.Tags.Count > 0) if (card.Tags.Count > 0) {
{
string names = string.Join(" ", card.Tags.Select(tag => InlineCode(tag.Name))); string names = string.Join(" ", card.Tags.Select(tag => InlineCode(tag.Name)));
builder.AppendLine(string.Format(culture, Resources.Export_TagsLine, names)); builder.AppendLine(string.Format(culture, Resources.Export_TagsLine, names));
} }
@@ -116,25 +126,25 @@ public static class MarkdownExporter
private static void AppendTagTable( private static void AppendTagTable(
StringBuilder builder, StringBuilder builder,
IReadOnlyList<(TagModel Tag, long UsageCount)> tags, IReadOnlyList<(TagModel Tag, long UsageCount)> tags,
CultureInfo culture) CultureInfo culture) {
{
builder.AppendLine(Resources.Export_TagsSummaryHeading); builder.AppendLine(Resources.Export_TagsSummaryHeading);
builder.AppendLine(Resources.Export_TagsTableHeader); builder.AppendLine(Resources.Export_TagsTableHeader);
builder.AppendLine("|---|---|---|---|"); builder.AppendLine("|---|---|---|---|");
foreach ((TagModel tag, long usage) in tags) foreach ((TagModel tag, long usage) in tags) {
{
// '|' and line breaks would break the table row; neutralize them. // '|' and line breaks would break the table row; neutralize them.
builder.AppendLine($"| {Cell(tag.Name)} | {tag.Color} | {Cell(tag.Description)} | {usage} |"); builder.AppendLine($"| {Cell(tag.Name)} | {tag.Color} | {Cell(tag.Description)} | {usage} |");
} }
} }
/// <summary> /// <summary>
/// Formats a table cell: escaped pipe characters, line breaks as &lt;br&gt;. /// Formats a table cell: escaped backslashes and pipe characters, line breaks as &lt;br&gt;.
/// </summary> /// </summary>
/// <param name="text">The raw cell text.</param> /// <param name="text">The raw cell text.</param>
/// <returns>The escaped single-line text.</returns> /// <returns>The escaped single-line text.</returns>
private static string Cell(string text) => private static string Cell(string text) =>
text.Replace("|", "\\|").Replace("\r\n", "<br>").Replace("\r", "<br>").Replace("\n", "<br>"); // Backslashes first: the table splitter reads "\\" as an escaped backslash, so the
// '|' after a literal backslash would otherwise end the cell.
text.Replace("\\", "\\\\").Replace("|", "\\|").Replace("\r\n", "<br>").Replace("\r", "<br>").Replace("\n", "<br>");
/// <summary> /// <summary>
/// Renders text as an inline code span whose backtick fence is one longer than /// Renders text as an inline code span whose backtick fence is one longer than
@@ -143,12 +153,10 @@ public static class MarkdownExporter
/// </summary> /// </summary>
/// <param name="text">The raw text.</param> /// <param name="text">The raw text.</param>
/// <returns>The inline code span.</returns> /// <returns>The inline code span.</returns>
private static string InlineCode(string text) private static string InlineCode(string text) {
{
int longestRun = 0; int longestRun = 0;
int run = 0; int run = 0;
foreach (char character in text) foreach (char character in text) {
{
run = character == '`' ? run + 1 : 0; run = character == '`' ? run + 1 : 0;
longestRun = Math.Max(longestRun, run); longestRun = Math.Max(longestRun, run);
} }
+21 -20
View File
@@ -4,39 +4,40 @@ namespace YKanBan.Launching;
/// <summary> /// <summary>
/// Parses raw command-line arguments. The only accepted form is a single, /// Parses raw command-line arguments. The only accepted form is a single,
/// non-blank workspace path (<c>ykanban &lt;path&gt;</c>); zero arguments, /// non-blank, existing workspace folder (<c>ykanban &lt;path&gt;</c>); zero
/// more than one argument, a blank argument, an argument starting with /// arguments, more than one argument, a blank argument, an argument starting
/// <c>-</c> (any option form, <c>--help</c> included) or a malformed path is /// with <c>-</c> (any option form, <c>--help</c> included), a malformed path or
/// rejected as an argument error. A relative path is resolved against the /// a path that is not an existing folder is rejected as an argument error. A
/// process's current directory; the path itself is not checked for existence /// relative path is resolved against the process's current directory.
/// here.
/// </summary> /// </summary>
public static class LaunchArguments public static class LaunchArguments {
{
/// <summary> /// <summary>
/// Tries to parse command-line arguments following the /// Tries to parse command-line arguments following the
/// <c>ykanban &lt;path&gt;</c> contract. /// <c>ykanban &lt;path&gt;</c> contract.
/// </summary> /// </summary>
/// <param name="arguments">The raw arguments, excluding the executable name.</param> /// <param name="arguments">The raw arguments, excluding the executable name.</param>
/// <param name="folderPath">The absolute workspace path on success, otherwise <see langword="null"/>.</param> /// <param name="folderPath">The absolute, existing workspace folder on success, otherwise <see langword="null"/>.</param>
/// <returns><see langword="true"/> when exactly one usable path was supplied.</returns> /// <returns><see langword="true"/> when exactly one usable path was supplied.</returns>
public static bool TryParse(IReadOnlyList<string> arguments, [NotNullWhen(true)] out string? folderPath) public static bool TryParse(IReadOnlyList<string> arguments, [NotNullWhen(true)] out string? folderPath) {
{
folderPath = null; folderPath = null;
if (arguments.Count != 1 || string.IsNullOrWhiteSpace(arguments[0]) || arguments[0].StartsWith('-')) if (arguments.Count != 1 || string.IsNullOrWhiteSpace(arguments[0]) || arguments[0].StartsWith('-')) {
{
return false; return false;
} }
try string fullPath;
{ try {
folderPath = Path.GetFullPath(arguments[0]); fullPath = Path.GetFullPath(arguments[0]);
return true; } catch (Exception exception) when (exception is ArgumentException or NotSupportedException or PathTooLongException) {
}
catch (Exception exception) when (exception is ArgumentException or NotSupportedException or PathTooLongException)
{
// A path the OS cannot even represent is a bad argument, not a missing folder. // A path the OS cannot even represent is a bad argument, not a missing folder.
return false; return false;
} }
// Existence is checked here so every caller gets an already validated folder.
if (!Directory.Exists(fullPath)) {
return false;
}
folderPath = fullPath;
return true;
} }
} }
-70
View File
@@ -1,70 +0,0 @@
using System.Text;
using YKanBan.Storage.AppData;
namespace YKanBan.Models;
/// <summary>
/// Computes the in-column card display order for a <see cref="CardSortOption"/>.
/// Columns are not affected: they always stay in id order. Every option falls
/// back to id ascending as the final tie-breaker, so the order is total.
/// </summary>
public static class CardOrdering
{
/// <summary>
/// Orders cards for display.
/// </summary>
/// <param name="cards">The cards to order, typically those of one column.</param>
/// <param name="option">The selected sort option.</param>
/// <returns>The cards in display order.</returns>
public static IReadOnlyList<CardModel> Sort(IEnumerable<CardModel> cards, CardSortOption option)
{
IOrderedEnumerable<CardModel> ordered = option switch
{
CardSortOption.Id => cards.OrderBy(card => card.Id),
// Most recently modified first.
CardSortOption.UpdatedAt => cards.OrderByDescending(card => card.UpdatedAt).ThenBy(card => card.Id),
// Code point order, matching SQLite's BINARY collation; the empty title sorts first.
CardSortOption.Title => cards.OrderBy(card => card.Title, CodePointComparer.Instance).ThenBy(card => card.Id),
_ => throw new ArgumentOutOfRangeException(nameof(option), option, "Unknown card sort option."),
};
return ordered.ToList();
}
/// <summary>
/// Compares strings by Unicode code points. Unlike ordinal UTF-16 comparison
/// it orders supplementary characters after U+E000–U+FFFF, as BINARY does on UTF-8.
/// </summary>
private sealed class CodePointComparer : IComparer<string>
{
public static readonly CodePointComparer Instance = new();
public int Compare(string? x, string? y)
{
if (x is null || y is null)
{
return x is null ? (y is null ? 0 : -1) : 1;
}
StringRuneEnumerator left = x.EnumerateRunes();
StringRuneEnumerator right = y.EnumerateRunes();
while (true)
{
bool hasLeft = left.MoveNext();
bool hasRight = right.MoveNext();
if (!hasLeft || !hasRight)
{
return hasLeft.CompareTo(hasRight);
}
int result = left.Current.Value.CompareTo(right.Current.Value);
if (result != 0)
{
return result;
}
}
}
}
}
+7 -14
View File
@@ -10,8 +10,7 @@ namespace YKanBan.Models;
/// always produces the canonical lowercase form (for example "#ff0a00"). It is /// always produces the canonical lowercase form (for example "#ff0a00"). It is
/// not specific to tags and may be reused anywhere a color value is needed. /// not specific to tags and may be reused anywhere a color value is needed.
/// </summary> /// </summary>
public readonly record struct RgbColor(byte R, byte G, byte B) public readonly record struct RgbColor(byte R, byte G, byte B) {
{
/// <summary> /// <summary>
/// Parses a "#RRGGBB" text with case-insensitive hex digits. /// Parses a "#RRGGBB" text with case-insensitive hex digits.
/// </summary> /// </summary>
@@ -29,17 +28,14 @@ public readonly record struct RgbColor(byte R, byte G, byte B)
/// <param name="text">The text to parse.</param> /// <param name="text">The text to parse.</param>
/// <param name="color">The parsed color on success, otherwise the default value.</param> /// <param name="color">The parsed color on success, otherwise the default value.</param>
/// <returns><see langword="true"/> when the text is exactly #RRGGBB.</returns> /// <returns><see langword="true"/> when the text is exactly #RRGGBB.</returns>
public static bool TryParse(string? text, out RgbColor color) public static bool TryParse(string? text, out RgbColor color) {
{
color = default; color = default;
if (text is not { Length: 7 } || text[0] != '#') if (text is not { Length: 7 } || text[0] != '#') {
{
return false; return false;
} }
// Two hex digits per component: R, G, B. // Two hex digits per component: R, G, B.
if (TryHexPair(text, 1, out byte r) && TryHexPair(text, 3, out byte g) && TryHexPair(text, 5, out byte b)) if (TryHexPair(text, 1, out byte r) && TryHexPair(text, 3, out byte g) && TryHexPair(text, 5, out byte b)) {
{
color = new RgbColor(r, g, b); color = new RgbColor(r, g, b);
return true; return true;
} }
@@ -59,13 +55,11 @@ public readonly record struct RgbColor(byte R, byte G, byte B)
/// <param name="start">Index of the first of the two digits.</param> /// <param name="start">Index of the first of the two digits.</param>
/// <param name="value">The parsed byte value.</param> /// <param name="value">The parsed byte value.</param>
/// <returns><see langword="true"/> when both characters are hex digits.</returns> /// <returns><see langword="true"/> when both characters are hex digits.</returns>
private static bool TryHexPair(string text, int start, out byte value) private static bool TryHexPair(string text, int start, out byte value) {
{
value = 0; value = 0;
int high = HexDigit(text[start]); int high = HexDigit(text[start]);
int low = HexDigit(text[start + 1]); int low = HexDigit(text[start + 1]);
if (high < 0 || low < 0) if (high < 0 || low < 0) {
{
return false; return false;
} }
value = (byte)((high << 4) | low); value = (byte)((high << 4) | low);
@@ -77,8 +71,7 @@ public readonly record struct RgbColor(byte R, byte G, byte B)
/// </summary> /// </summary>
/// <param name="character">The character to convert.</param> /// <param name="character">The character to convert.</param>
/// <returns>The digit value, or -1 for any other character.</returns> /// <returns>The digit value, or -1 for any other character.</returns>
private static int HexDigit(char character) => character switch private static int HexDigit(char character) => character switch {
{
>= '0' and <= '9' => character - '0', >= '0' and <= '9' => character - '0',
>= 'a' and <= 'f' => character - 'a' + 10, >= 'a' and <= 'f' => character - 'a' + 10,
>= 'A' and <= 'F' => character - 'A' + 10, >= 'A' and <= 'F' => character - 'A' + 10,
+2 -4
View File
@@ -2,14 +2,12 @@
namespace YKanBan; namespace YKanBan;
sealed class Program sealed class Program {
{
// Initialization code. Don't use any Avalonia, third-party APIs or any // Initialization code. Don't use any Avalonia, third-party APIs or any
// SynchronizationContext-reliant code before AppMain is called: things aren't initialized // SynchronizationContext-reliant code before AppMain is called: things aren't initialized
// yet and stuff might break. // yet and stuff might break.
[STAThread] [STAThread]
public static void Main(string[] args) public static void Main(string[] args) {
{
BuildAvaloniaApp().StartWithClassicDesktopLifetime(args); BuildAvaloniaApp().StartWithClassicDesktopLifetime(args);
// The lifetime has ended: persist the configuration once, then release services. // The lifetime has ended: persist the configuration once, then release services.
+75 -20
View File
@@ -5,8 +5,7 @@ namespace YKanBan.Search;
/// <summary> /// <summary>
/// Lexical tokens of the search syntax. /// Lexical tokens of the search syntax.
/// </summary> /// </summary>
public abstract record SearchToken public abstract record SearchToken {
{
/// <summary> /// <summary>
/// A bare word; qualifier detection happens later from the text. /// A bare word; qualifier detection happens later from the text.
/// </summary> /// </summary>
@@ -36,11 +35,13 @@ public abstract record SearchToken
/// ///
/// The lexer is strict: inside a phrase only <c>\"</c> and <c>\\</c> are valid /// The lexer is strict: inside a phrase only <c>\"</c> and <c>\\</c> are valid
/// escapes, a bare backslash or an unknown escape is rejected, a backslash in a /// escapes, a bare backslash or an unknown escape is rejected, a backslash in a
/// bare word is rejected, and an unterminated phrase is rejected. Any input not covered by the token rules /// bare word is rejected, and an unterminated phrase is rejected. A phrase
/// is rejected rather than silently ignored. /// must not be empty and must be separated from neighbouring words and
/// phrases by whitespace or a parenthesis, except as a qualifier value glued to
/// its key (<c>tag:"a b"</c>). Any input not covered by the token rules is
/// rejected rather than silently ignored.
/// </summary> /// </summary>
public static class SearchLexer public static class SearchLexer {
{
/// <summary>A valid phrase escape sequence: <c>\"</c> or <c>\\</c>.</summary> /// <summary>A valid phrase escape sequence: <c>\"</c> or <c>\\</c>.</summary>
private static readonly Parser<char, char> PhraseEscape = private static readonly Parser<char, char> PhraseEscape =
Parser.Try(Parser.String("\\\"").Select(_ => '"')) Parser.Try(Parser.String("\\\"").Select(_ => '"'))
@@ -70,37 +71,91 @@ public static class SearchLexer
.AtLeastOnce() .AtLeastOnce()
.Select(chars => (SearchToken)new SearchToken.Word(new string(chars.ToArray()))); .Select(chars => (SearchToken)new SearchToken.Word(new string(chars.ToArray())));
private static readonly Parser<char, SearchToken> TokenParser = // Each token with its source span, so adjacency can be checked afterwards.
private static readonly Parser<char, PositionedToken> TokenParser =
Parser.SkipWhitespaces.Then( Parser.SkipWhitespaces.Then(
PhraseParser from start in Parser<char>.CurrentOffset
from token in PhraseParser
.Or(OpenParenParser) .Or(OpenParenParser)
.Or(CloseParenParser) .Or(CloseParenParser)
.Or(WordParser)); .Or(WordParser)
from end in Parser<char>.CurrentOffset
select new PositionedToken(token, start, end));
// Try(...) keeps a failed token non-consuming so Many stops gracefully; End // Try(...) keeps a failed token non-consuming so Many stops gracefully; End
// then rejects any leftover input, which turns dangling quotes or invalid // then rejects any leftover input, which turns dangling quotes or invalid
// escapes into hard failures instead of silently dropped text. // escapes into hard failures instead of silently dropped text.
private static readonly Parser<char, IReadOnlyList<SearchToken>> Lexer = private static readonly Parser<char, IReadOnlyList<PositionedToken>> Lexer =
Parser.Try(TokenParser).Many() Parser.Try(TokenParser).Many()
.Before(Parser.SkipWhitespaces) .Before(Parser.SkipWhitespaces)
.Before(Parser<char>.End) .Before(Parser<char>.End)
.Select(tokens => (IReadOnlyList<SearchToken>)tokens.ToList()); .Select(tokens => (IReadOnlyList<PositionedToken>)tokens.ToList());
/// <summary> /// <summary>
/// Tokenizes the search text. /// Tokenizes the search text.
/// </summary> /// </summary>
/// <param name="input">The raw search text.</param> /// <param name="input">The raw search text.</param>
/// <returns>The token stream.</returns> /// <returns>The token stream.</returns>
/// <exception cref="SearchSyntaxException">The text contains an invalid escape or an unterminated phrase.</exception> /// <exception cref="SearchSyntaxException">
public static IReadOnlyList<SearchToken> Tokenize(string input) /// The text contains an invalid escape, an unterminated or empty phrase, a
{ /// phrase glued to other text, or whitespace between a qualifier and its phrase value.
try /// </exception>
{ public static IReadOnlyList<SearchToken> Tokenize(string input) {
return Lexer.ParseOrThrow(input); IReadOnlyList<PositionedToken> tokens;
} try {
catch (ParseException exception) tokens = Lexer.ParseOrThrow(input);
{ } catch (ParseException exception) {
throw new SearchSyntaxException(exception.Message, exception); throw new SearchSyntaxException(exception.Message, exception);
} }
EnsurePhrasesAreDelimited(tokens);
return tokens.Select(positioned => positioned.Token).ToList();
} }
/// <summary>
/// Rejects the phrase placements the grammar does not allow but the token
/// rules alone would accept: an empty phrase, a phrase touching a word or
/// another phrase (<c>a"b"</c>, <c>"a"b</c>, <c>"a""b"</c>), and whitespace
/// between <c>key:</c> and its phrase value (<c>tag: "x"</c>). The only
/// legal contact is <c>key:"value"</c>.
/// </summary>
/// <param name="tokens">The positioned token stream.</param>
/// <exception cref="SearchSyntaxException">A phrase is misplaced.</exception>
private static void EnsurePhrasesAreDelimited(IReadOnlyList<PositionedToken> tokens) {
for (int index = 0; index < tokens.Count; index++) {
if (tokens[index].Token is SearchToken.Phrase { Text.Length: 0 }) {
throw new SearchSyntaxException("Empty phrase \"\" is not allowed.");
}
if (index == 0) {
continue;
}
PositionedToken previous = tokens[index - 1];
PositionedToken current = tokens[index];
bool qualifierValue = previous.Token is SearchToken.Word word && word.Text.EndsWith(':')
&& current.Token is SearchToken.Phrase;
bool touching = previous.End == current.Start;
if (qualifierValue && !touching) {
throw new SearchSyntaxException(
$"Qualifier '{((SearchToken.Word)previous.Token).Text}' must be followed directly by its value, without whitespace.");
}
bool phraseInvolved = previous.Token is SearchToken.Phrase || current.Token is SearchToken.Phrase;
bool parenInvolved = previous.Token is SearchToken.OpenParen or SearchToken.CloseParen
|| current.Token is SearchToken.OpenParen or SearchToken.CloseParen;
if (touching && phraseInvolved && !parenInvolved && !qualifierValue) {
throw new SearchSyntaxException("A phrase must be separated from adjacent text by whitespace.");
}
}
}
/// <summary>
/// A token with its source span.
/// </summary>
/// <param name="Token">The token.</param>
/// <param name="Start">Offset of the first character.</param>
/// <param name="End">Offset just past the last character.</param>
private sealed record PositionedToken(SearchToken Token, int Start, int End);
} }
+8 -6
View File
@@ -10,8 +10,7 @@ namespace YKanBan.Search;
/// Root of the search query AST. Search keywords are fixed English grammar /// Root of the search query AST. Search keywords are fixed English grammar
/// and are never localized. /// and are never localized.
/// </summary> /// </summary>
public abstract record SearchNode public abstract record SearchNode {
{
/// <summary> /// <summary>
/// Disjunction: matches when any term matches (OR). /// Disjunction: matches when any term matches (OR).
/// </summary> /// </summary>
@@ -59,11 +58,14 @@ public abstract record SearchNode
/// <summary> /// <summary>
/// The card fields a <see cref="SearchNode.FieldText"/> atom can scope to. /// The card fields a <see cref="SearchNode.FieldText"/> atom can scope to.
/// </summary> /// </summary>
public enum SearchField public enum SearchField {
{ /// <summary>
/// <summary>The card title.</summary> /// The card title.
/// </summary>
Title, Title,
/// <summary>The card content body.</summary> /// <summary>
/// The card content body.
/// </summary>
Content, Content,
} }
+28 -44
View File
@@ -1,4 +1,5 @@
using System.Globalization; using System.Globalization;
using Pidgin; using Pidgin;
namespace YKanBan.Search; namespace YKanBan.Search;
@@ -16,8 +17,7 @@ namespace YKanBan.Search;
/// input returns null and means "show everything". Search keywords and /// input returns null and means "show everything". Search keywords and
/// qualifier keys are fixed English grammar and are never localized. /// qualifier keys are fixed English grammar and are never localized.
/// </summary> /// </summary>
public static class SearchQueryParser public static class SearchQueryParser {
{
/// <summary>The recognized qualifier keys; add new entries here to extend the grammar.</summary> /// <summary>The recognized qualifier keys; add new entries here to extend the grammar.</summary>
private static readonly (string Key, QualifierKind Kind)[] QualifierTable = private static readonly (string Key, QualifierKind Kind)[] QualifierTable =
[ [
@@ -104,20 +104,20 @@ public static class SearchQueryParser
/// <param name="text">The raw search text.</param> /// <param name="text">The raw search text.</param>
/// <returns>The parsed query, or <see langword="null"/> for blank input (meaning: show everything).</returns> /// <returns>The parsed query, or <see langword="null"/> for blank input (meaning: show everything).</returns>
/// <exception cref="SearchSyntaxException">The text violates the grammar.</exception> /// <exception cref="SearchSyntaxException">The text violates the grammar.</exception>
public static SearchNode? Parse(string text) public static SearchNode? Parse(string text) {
{ if (string.IsNullOrWhiteSpace(text)) {
if (string.IsNullOrWhiteSpace(text))
{
return null; return null;
} }
try // YYC MARK: the expression is deliberately not capped by parenthesis
{ // depth or atom count. The app is local-only with no untrusted search
// input, so there is no attack surface; a pathologically deep or long
// expression can still overflow the parser stack or exceed SQLite's
// expression nesting limit, which is accepted here.
try {
List<SearchToken> tokens = SearchLexer.Tokenize(text).ToList(); List<SearchToken> tokens = SearchLexer.Tokenize(text).ToList();
return Query.ParseOrThrow(tokens); return Query.ParseOrThrow(tokens);
} } catch (ParseException exception) {
catch (ParseException exception)
{
throw new SearchSyntaxException(exception.Message, exception); throw new SearchSyntaxException(exception.Message, exception);
} }
} }
@@ -130,11 +130,9 @@ public static class SearchQueryParser
/// </summary> /// </summary>
/// <param name="word">The word token text.</param> /// <param name="word">The word token text.</param>
/// <returns>The parser producing the operand node.</returns> /// <returns>The parser producing the operand node.</returns>
private static Parser<SearchToken, SearchNode> QualifierFrom(string word) private static Parser<SearchToken, SearchNode> QualifierFrom(string word) {
{
int colonIndex = word.IndexOf(':'); int colonIndex = word.IndexOf(':');
if (colonIndex < 0) if (colonIndex < 0) {
{
return Parser<SearchToken>.Return<SearchNode>(new SearchNode.FreeText(word)); return Parser<SearchToken>.Return<SearchNode>(new SearchNode.FreeText(word));
} }
@@ -142,31 +140,26 @@ public static class SearchQueryParser
string key = word[..colonIndex]; string key = word[..colonIndex];
string value = word[(colonIndex + 1)..]; string value = word[(colonIndex + 1)..];
if (!TryLookupQualifier(key, out QualifierKind kind)) if (!TryLookupQualifier(key, out QualifierKind kind)) {
{
return Parser<SearchToken>.Fail<SearchNode>($"Unknown qualifier key '{key}'; quote the text to search for it literally."); return Parser<SearchToken>.Fail<SearchNode>($"Unknown qualifier key '{key}'; quote the text to search for it literally.");
} }
// "key:" without an inline value takes the value from the following phrase, e.g. tag:"a b". // "key:" without an inline value takes the value from the following phrase, e.g. tag:"a b".
if (value.Length == 0) if (value.Length == 0) {
{
return kind == QualifierKind.Id return kind == QualifierKind.Id
? Parser<SearchToken>.Fail<SearchNode>("The id qualifier expects an unquoted positive integer.") ? Parser<SearchToken>.Fail<SearchNode>("The id qualifier expects an unquoted positive integer.")
: PhraseText.Select(text => TextAtom(kind, text)); : PhraseText.Select(phrase => TextAtom(kind, phrase));
} }
if (value.Contains(':')) if (value.Contains(':')) {
{
return Parser<SearchToken>.Fail<SearchNode>($"Unquoted value '{value}' of qualifier '{key}' contains ':'; quote the value."); return Parser<SearchToken>.Fail<SearchNode>($"Unquoted value '{value}' of qualifier '{key}' contains ':'; quote the value.");
} }
if (value is "AND" or "OR") if (value is "AND" or "OR") {
{
return Parser<SearchToken>.Fail<SearchNode>($"Operator {value} cannot be a qualifier value; quote it to search for it literally."); return Parser<SearchToken>.Fail<SearchNode>($"Operator {value} cannot be a qualifier value; quote it to search for it literally.");
} }
if (kind == QualifierKind.Id) if (kind == QualifierKind.Id) {
{
return TryParseCardId(value, out long id) return TryParseCardId(value, out long id)
? Parser<SearchToken>.Return<SearchNode>(new SearchNode.CardId(id)) ? Parser<SearchToken>.Return<SearchNode>(new SearchNode.CardId(id))
: Parser<SearchToken>.Fail<SearchNode>($"The id qualifier expects a positive integer, got '{value}'."); : Parser<SearchToken>.Fail<SearchNode>($"The id qualifier expects a positive integer, got '{value}'.");
@@ -181,8 +174,7 @@ public static class SearchQueryParser
/// <param name="kind">The qualifier kind; never <see cref="QualifierKind.Id"/>.</param> /// <param name="kind">The qualifier kind; never <see cref="QualifierKind.Id"/>.</param>
/// <param name="value">The qualifier value.</param> /// <param name="value">The qualifier value.</param>
/// <returns>The atom node.</returns> /// <returns>The atom node.</returns>
private static SearchNode TextAtom(QualifierKind kind, string value) => kind switch private static SearchNode TextAtom(QualifierKind kind, string value) => kind switch {
{
QualifierKind.Tag => new SearchNode.TagName(value), QualifierKind.Tag => new SearchNode.TagName(value),
QualifierKind.Title => new SearchNode.FieldText(SearchField.Title, value), QualifierKind.Title => new SearchNode.FieldText(SearchField.Title, value),
QualifierKind.Content => new SearchNode.FieldText(SearchField.Content, value), QualifierKind.Content => new SearchNode.FieldText(SearchField.Content, value),
@@ -197,11 +189,9 @@ public static class SearchQueryParser
/// <param name="value">The inline qualifier value.</param> /// <param name="value">The inline qualifier value.</param>
/// <param name="id">The parsed card id.</param> /// <param name="id">The parsed card id.</param>
/// <returns><see langword="true"/> when the value is a valid positive card id.</returns> /// <returns><see langword="true"/> when the value is a valid positive card id.</returns>
private static bool TryParseCardId(string value, out long id) private static bool TryParseCardId(string value, out long id) {
{
ReadOnlySpan<char> digits = value.AsSpan(); ReadOnlySpan<char> digits = value.AsSpan();
if (digits.StartsWith("#")) if (digits.StartsWith("#")) {
{
digits = digits[1..]; digits = digits[1..];
} }
@@ -219,12 +209,9 @@ public static class SearchQueryParser
/// <param name="key">The key text before the colon.</param> /// <param name="key">The key text before the colon.</param>
/// <param name="kind">The matching qualifier kind.</param> /// <param name="kind">The matching qualifier kind.</param>
/// <returns><see langword="true"/> when the key is known.</returns> /// <returns><see langword="true"/> when the key is known.</returns>
private static bool TryLookupQualifier(string key, out QualifierKind kind) private static bool TryLookupQualifier(string key, out QualifierKind kind) {
{ foreach ((string candidate, QualifierKind candidateKind) in QualifierTable) {
foreach ((string candidate, QualifierKind candidateKind) in QualifierTable) if (string.Equals(candidate, key, StringComparison.Ordinal)) {
{
if (string.Equals(candidate, key, StringComparison.Ordinal))
{
kind = candidateKind; kind = candidateKind;
return true; return true;
} }
@@ -240,8 +227,7 @@ public static class SearchQueryParser
/// <param name="first">The first operand.</param> /// <param name="first">The first operand.</param>
/// <param name="rest">The remaining operands.</param> /// <param name="rest">The remaining operands.</param>
/// <returns>The single operand, or an <see cref="SearchNode.And"/> node.</returns> /// <returns>The single operand, or an <see cref="SearchNode.And"/> node.</returns>
private static SearchNode FoldAnd(SearchNode first, IEnumerable<SearchNode> rest) private static SearchNode FoldAnd(SearchNode first, IEnumerable<SearchNode> rest) {
{
List<SearchNode> terms = [first, .. rest]; List<SearchNode> terms = [first, .. rest];
return terms.Count == 1 ? terms[0] : new SearchNode.And(terms); return terms.Count == 1 ? terms[0] : new SearchNode.And(terms);
} }
@@ -251,8 +237,7 @@ public static class SearchQueryParser
/// </summary> /// </summary>
/// <param name="terms">The operands.</param> /// <param name="terms">The operands.</param>
/// <returns>The single operand, or a <see cref="SearchNode.Or"/> node.</returns> /// <returns>The single operand, or a <see cref="SearchNode.Or"/> node.</returns>
private static SearchNode FoldOr(IEnumerable<SearchNode> terms) private static SearchNode FoldOr(IEnumerable<SearchNode> terms) {
{
List<SearchNode> list = terms.ToList(); List<SearchNode> list = terms.ToList();
return list.Count == 1 ? list[0] : new SearchNode.Or(list); return list.Count == 1 ? list[0] : new SearchNode.Or(list);
} }
@@ -260,8 +245,7 @@ public static class SearchQueryParser
#endregion #endregion
/// <summary>The recognized qualifier kinds.</summary> /// <summary>The recognized qualifier kinds.</summary>
private enum QualifierKind private enum QualifierKind {
{
Tag, Tag,
Title, Title,
Content, Content,
+10 -20
View File
@@ -18,15 +18,13 @@ public sealed record CompiledSearch(string Predicate, IReadOnlyList<(string Name
/// ordinally — <c>instr</c> for substrings, <c>=</c> for exact matches. LIKE is /// ordinally — <c>instr</c> for substrings, <c>=</c> for exact matches. LIKE is
/// deliberately not used, so <c>%</c> and <c>_</c> carry no wildcard meaning. /// deliberately not used, so <c>%</c> and <c>_</c> carry no wildcard meaning.
/// </summary> /// </summary>
public static class SearchSqlCompiler public static class SearchSqlCompiler {
{
/// <summary> /// <summary>
/// Compiles the query into a SQL predicate. /// Compiles the query into a SQL predicate.
/// </summary> /// </summary>
/// <param name="query">The parsed search AST.</param> /// <param name="query">The parsed search AST.</param>
/// <returns>The compiled predicate and its parameters.</returns> /// <returns>The compiled predicate and its parameters.</returns>
public static CompiledSearch Compile(SearchNode query) public static CompiledSearch Compile(SearchNode query) {
{
var parameters = new List<(string Name, object Value)>(); var parameters = new List<(string Name, object Value)>();
string predicate = Build(query, parameters); string predicate = Build(query, parameters);
return new CompiledSearch(predicate, parameters); return new CompiledSearch(predicate, parameters);
@@ -38,45 +36,38 @@ public static class SearchSqlCompiler
/// <param name="node">The AST node to compile.</param> /// <param name="node">The AST node to compile.</param>
/// <param name="parameters">The parameter accumulator.</param> /// <param name="parameters">The parameter accumulator.</param>
/// <returns>The SQL boolean expression for the node.</returns> /// <returns>The SQL boolean expression for the node.</returns>
private static string Build(SearchNode node, List<(string Name, object Value)> parameters) private static string Build(SearchNode node, List<(string Name, object Value)> parameters) {
{ switch (node) {
switch (node)
{
case SearchNode.And and: case SearchNode.And and:
return "(" + string.Join(" AND ", and.Terms.Select(term => Build(term, parameters))) + ")"; return "(" + string.Join(" AND ", and.Terms.Select(term => Build(term, parameters))) + ")";
case SearchNode.Or or: case SearchNode.Or or:
return "(" + string.Join(" OR ", or.Terms.Select(term => Build(term, parameters))) + ")"; return "(" + string.Join(" OR ", or.Terms.Select(term => Build(term, parameters))) + ")";
case SearchNode.FreeText freeText: case SearchNode.FreeText freeText: {
{
// A bare word matches a substring of the title OR the content. // A bare word matches a substring of the title OR the content.
string param = AddParameter(parameters, SqliteDatabase.Fold(freeText.Text)); string param = AddParameter(parameters, SqliteDatabase.Fold(freeText.Text));
return $"({Contains("c.title", param)} OR {Contains("c.content", param)})"; return $"({Contains("c.title", param)} OR {Contains("c.content", param)})";
} }
case SearchNode.FieldText field: case SearchNode.FieldText field: {
{
string column = field.Field == SearchField.Title ? "c.title" : "c.content"; string column = field.Field == SearchField.Title ? "c.title" : "c.content";
string param = AddParameter(parameters, SqliteDatabase.Fold(field.Text)); string param = AddParameter(parameters, SqliteDatabase.Fold(field.Text));
return Contains(column, param); return Contains(column, param);
} }
case SearchNode.TagName tag: case SearchNode.TagName tag: {
{
string param = AddParameter(parameters, SqliteDatabase.Fold(tag.Name)); string param = AddParameter(parameters, SqliteDatabase.Fold(tag.Name));
return "EXISTS (SELECT 1 FROM card_tags ct JOIN tags t ON t.id = ct.tag_id " + return "EXISTS (SELECT 1 FROM card_tags ct JOIN tags t ON t.id = ct.tag_id " +
$"WHERE ct.card_id = c.id AND {Folded("t.name")} = {param})"; $"WHERE ct.card_id = c.id AND {Folded("t.name")} = {param})";
} }
case SearchNode.ColumnTitle column: case SearchNode.ColumnTitle column: {
{
string param = AddParameter(parameters, SqliteDatabase.Fold(column.Title)); string param = AddParameter(parameters, SqliteDatabase.Fold(column.Title));
return $"c.column_id IN (SELECT id FROM columns WHERE {Folded("title")} = {param})"; return $"c.column_id IN (SELECT id FROM columns WHERE {Folded("title")} = {param})";
} }
case SearchNode.CardId id: case SearchNode.CardId id: {
{
string param = AddParameter(parameters, id.Id); string param = AddParameter(parameters, id.Id);
return $"c.id = {param}"; return $"c.id = {param}";
} }
@@ -92,8 +83,7 @@ public static class SearchSqlCompiler
/// <param name="parameters">The parameter accumulator.</param> /// <param name="parameters">The parameter accumulator.</param>
/// <param name="value">The value to bind.</param> /// <param name="value">The value to bind.</param>
/// <returns>The placeholder text.</returns> /// <returns>The placeholder text.</returns>
private static string AddParameter(List<(string Name, object Value)> parameters, object value) private static string AddParameter(List<(string Name, object Value)> parameters, object value) {
{
string name = "$p" + parameters.Count.ToString(System.Globalization.CultureInfo.InvariantCulture); string name = "$p" + parameters.Count.ToString(System.Globalization.CultureInfo.InvariantCulture);
parameters.Add((name, value)); parameters.Add((name, value));
return name; return name;
+10 -4
View File
@@ -6,15 +6,21 @@ namespace YKanBan.Search;
/// search error instead of coupling to Pidgin types. The message is never /// search error instead of coupling to Pidgin types. The message is never
/// localized. /// localized.
/// </summary> /// </summary>
public sealed class SearchSyntaxException : Exception public sealed class SearchSyntaxException : Exception {
{ /// <summary>
/// Initializes the exception with a descriptive English message.
/// </summary>
/// <param name="message">The English diagnostic message.</param>
public SearchSyntaxException(string message)
: base(message) {
}
/// <summary> /// <summary>
/// Initializes the exception with a descriptive English message. /// Initializes the exception with a descriptive English message.
/// </summary> /// </summary>
/// <param name="message">The English diagnostic message.</param> /// <param name="message">The English diagnostic message.</param>
/// <param name="innerException">The underlying parse failure.</param> /// <param name="innerException">The underlying parse failure.</param>
public SearchSyntaxException(string message, Exception innerException) public SearchSyntaxException(string message, Exception innerException)
: base(message, innerException) : base(message, innerException) {
{
} }
} }
+30 -9
View File
@@ -6,15 +6,13 @@ namespace YKanBan.Services;
/// <summary> /// <summary>
/// Composition root for the whole process: owns the loaded configuration and /// Composition root for the whole process: owns the loaded configuration and
/// the single open workspace session. The configuration is persisted once at /// the single open workspace session. The configuration is persisted once at
/// shutdown, and only when this session changed it; the session (lock plus connection) lives until disposal. /// shutdown; the session (lock plus connection) lives until disposal.
/// </summary> /// </summary>
public sealed class AppServices : IDisposable public sealed class AppServices : IDisposable {
{
/// <summary> /// <summary>
/// Loads the configuration and prepares the service graph. /// Loads the configuration and prepares the service graph.
/// </summary> /// </summary>
public AppServices() public AppServices() {
{
ConfigStore = new AppConfigStore(AppDataPaths.AppConfigJsonPath); ConfigStore = new AppConfigStore(AppDataPaths.AppConfigJsonPath);
Config = ConfigStore.Load(); Config = ConfigStore.Load();
} }
@@ -42,16 +40,39 @@ public sealed class AppServices : IDisposable
/// <returns>The open session.</returns> /// <returns>The open session.</returns>
/// <exception cref="YKanBan.Storage.WorkspaceNotInitializedException">The folder has no .ykanban structure.</exception> /// <exception cref="YKanBan.Storage.WorkspaceNotInitializedException">The folder has no .ykanban structure.</exception>
/// <exception cref="YKanBan.Storage.WorkspaceLockException">Another instance already holds the lock.</exception> /// <exception cref="YKanBan.Storage.WorkspaceLockException">Another instance already holds the lock.</exception>
public WorkspaceSession OpenWorkspace(string folderPath) public WorkspaceSession OpenWorkspace(string folderPath) {
{
Session = WorkspaceSession.Open(folderPath); Session = WorkspaceSession.Open(folderPath);
return Session; return Session;
} }
/// <summary> /// <summary>
/// Persists the configuration when this session changed a setting; called once at shutdown. /// Initializes a fresh workspace and opens it, holding the lock throughout.
/// </summary> /// </summary>
public void SaveConfiguration() => ConfigStore.SaveIfChanged(Config); /// <param name="folderPath">The folder to initialize.</param>
/// <returns>The open session.</returns>
/// <exception cref="YKanBan.Storage.WorkspaceDirectoryMissingException">The folder does not exist on disk.</exception>
/// <exception cref="YKanBan.Storage.WorkspaceLockException">Another instance already holds the lock.</exception>
public WorkspaceSession InitializeWorkspace(string folderPath) {
Session = WorkspaceSession.Initialize(folderPath);
return Session;
}
/// <summary>
/// Releases the workspace session, if any, and forgets it.
/// </summary>
public void CloseWorkspace() {
Session?.Dispose();
Session = null;
}
/// <summary>
/// Persists the configuration; called once at shutdown.
/// </summary>
// YYC MARK: the whole app.json is rewritten unconditionally at shutdown.
// Running several instances would make the last one to exit overwrite every
// field with its own in-memory state. Multi-instance use is not supported,
// so this last-writer-wins behavior is accepted.
public void SaveConfiguration() => ConfigStore.Save(Config);
/// <summary> /// <summary>
/// Releases the workspace session, if any. /// Releases the workspace session, if any.
+102 -71
View File
@@ -1,45 +1,88 @@
using System.Runtime.Serialization; using System.Runtime.Serialization;
using Newtonsoft.Json; using Newtonsoft.Json;
namespace YKanBan.Storage.AppData; namespace YKanBan.Storage.AppData;
/// <summary> /// <summary>
/// Card ordering options. Every order falls back to id ascending as the final /// Display ordering options, used for both cards and columns. Except for the id
/// tie-breaker. /// order, every option falls back to id ascending as the final tie-breaker.
/// </summary> /// </summary>
public enum CardSortOption public enum SortOption {
{ /// <summary>
/// <summary>Primary key ascending (default).</summary> /// Primary key ascending.
[EnumMember(Value = "id")] /// </summary>
Id, [EnumMember(Value = "id-asc")]
IdAscending,
/// <summary>Last modification time, most recently modified first.</summary> /// <summary>
[EnumMember(Value = "updated-at")] /// Primary key descending.
UpdatedAt, /// </summary>
[EnumMember(Value = "id-desc")]
IdDescending,
/// <summary>Title by code points (BINARY collation); empty titles sort first.</summary> /// <summary>
[EnumMember(Value = "title")] /// Creation time ascending.
Title, /// </summary>
[EnumMember(Value = "created-asc")]
CreatedAscending,
/// <summary>
/// Creation time descending.
/// </summary>
[EnumMember(Value = "created-desc")]
CreatedDescending,
/// <summary>
/// Last modification time ascending.
/// </summary>
[EnumMember(Value = "updated-asc")]
UpdatedAscending,
/// <summary>
/// Last modification time descending.
/// </summary>
[EnumMember(Value = "updated-desc")]
UpdatedDescending,
/// <summary>
/// Title by code points (BINARY collation) ascending.
/// </summary>
[EnumMember(Value = "title-asc")]
TitleAscending,
/// <summary>
/// Title by code points (BINARY collation) descending.
/// </summary>
[EnumMember(Value = "title-desc")]
TitleDescending,
} }
/// <summary> /// <summary>
/// Column width presets. <see cref="Custom"/> uses a user-defined pixel width. /// Column width presets. <see cref="Custom"/> uses a user-defined pixel width.
/// </summary> /// </summary>
public enum ColumnWidthPreset public enum ColumnWidthPreset {
{ /// <summary>
/// <summary>Narrow preset.</summary> /// Narrow preset.
/// </summary>
[EnumMember(Value = "narrow")] [EnumMember(Value = "narrow")]
Narrow, Narrow,
/// <summary>Standard preset (320 px, the default).</summary> /// <summary>
/// Standard preset (320 px, the default).
/// </summary>
[EnumMember(Value = "standard")] [EnumMember(Value = "standard")]
Standard, Standard,
/// <summary>Wide preset.</summary> /// <summary>
/// Wide preset.
/// </summary>
[EnumMember(Value = "wide")] [EnumMember(Value = "wide")]
Wide, Wide,
/// <summary>User-defined pixel width (160–720).</summary> /// <summary>
/// User-defined pixel width (160–720).
/// </summary>
[EnumMember(Value = "custom")] [EnumMember(Value = "custom")]
Custom, Custom,
} }
@@ -47,38 +90,30 @@ public enum ColumnWidthPreset
/// <summary> /// <summary>
/// UI theme selection. /// UI theme selection.
/// </summary> /// </summary>
public enum ThemeOption public enum ThemeOption {
{ /// <summary>
/// <summary>Always light.</summary> /// Always light.
/// </summary>
[EnumMember(Value = "light")] [EnumMember(Value = "light")]
Light, Light,
/// <summary>Always dark.</summary> /// <summary>
/// Always dark.
/// </summary>
[EnumMember(Value = "dark")] [EnumMember(Value = "dark")]
Dark, Dark,
/// <summary>Follow the operating system setting (default).</summary> /// <summary>
/// Follow the operating system setting (default).
/// </summary>
[EnumMember(Value = "follow-system")] [EnumMember(Value = "follow-system")]
FollowSystem, FollowSystem,
} }
/// <summary>
/// Card ordering settings. The chosen order is global, not per workspace.
/// </summary>
public sealed class SortSettings
{
/// <summary>
/// Gets or sets the order used by the board.
/// </summary>
[JsonProperty("card")]
public CardSortOption Card { get; set; } = CardSortOption.Id;
}
/// <summary> /// <summary>
/// Board column width settings, applied globally. /// Board column width settings, applied globally.
/// </summary> /// </summary>
public sealed class ColumnWidthSettings public sealed class ColumnWidthSettings {
{
/// <summary> /// <summary>
/// Gets or sets the active width preset. /// Gets or sets the active width preset.
/// </summary> /// </summary>
@@ -93,11 +128,34 @@ public sealed class ColumnWidthSettings
public int CustomPixels { get; set; } = 320; public int CustomPixels { get; set; } = 320;
} }
/// <summary>
/// Everything that controls how the board is displayed: the column width and
/// the card and column ordering.
/// </summary>
public sealed class DisplaySettings {
/// <summary>
/// Gets or sets the board column width settings.
/// </summary>
[JsonProperty("column-width")]
public ColumnWidthSettings ColumnWidth { get; set; } = new();
/// <summary>
/// Gets or sets the order of cards within their column.
/// </summary>
[JsonProperty("card-sort")]
public SortOption CardSort { get; set; } = SortOption.IdAscending;
/// <summary>
/// Gets or sets the left-to-right order of the columns.
/// </summary>
[JsonProperty("column-sort")]
public SortOption ColumnSort { get; set; } = SortOption.IdAscending;
}
/// <summary> /// <summary>
/// Confirmation-dialog toggles for the destructive actions. /// Confirmation-dialog toggles for the destructive actions.
/// </summary> /// </summary>
public sealed class ConfirmationSettings public sealed class ConfirmationSettings {
{
/// <summary> /// <summary>
/// Gets or sets whether deleting a card asks for confirmation. /// Gets or sets whether deleting a card asks for confirmation.
/// </summary> /// </summary>
@@ -129,8 +187,7 @@ public sealed class ConfirmationSettings
/// <see cref="JsonPropertyAttribute"/> and <see cref="EnumMemberAttribute"/>). /// <see cref="JsonPropertyAttribute"/> and <see cref="EnumMemberAttribute"/>).
/// The <c>version</c> field is the migration hook for future format changes. /// The <c>version</c> field is the migration hook for future format changes.
/// </summary> /// </summary>
public sealed class AppConfig public sealed class AppConfig {
{
/// <summary> /// <summary>
/// Current configuration format version. /// Current configuration format version.
/// </summary> /// </summary>
@@ -141,26 +198,6 @@ public sealed class AppConfig
/// </summary> /// </summary>
public const string DefaultLanguage = "en"; public const string DefaultLanguage = "en";
/// <summary>
/// Simplified Chinese UI language code.
/// </summary>
public const string SimplifiedChineseLanguage = "zh-Hans";
/// <summary>
/// Gets the supported UI language codes; any other stored value falls back to <see cref="DefaultLanguage"/>.
/// </summary>
public static IReadOnlyList<string> SupportedLanguages { get; } = [DefaultLanguage, SimplifiedChineseLanguage];
/// <summary>
/// Smallest accepted custom column width in pixels.
/// </summary>
public const int MinColumnPixels = 160;
/// <summary>
/// Largest accepted custom column width in pixels.
/// </summary>
public const int MaxColumnPixels = 720;
/// <summary> /// <summary>
/// Gets or sets the configuration format version of this file. /// Gets or sets the configuration format version of this file.
/// </summary> /// </summary>
@@ -180,16 +217,10 @@ public sealed class AppConfig
public ThemeOption Theme { get; set; } = ThemeOption.FollowSystem; public ThemeOption Theme { get; set; } = ThemeOption.FollowSystem;
/// <summary> /// <summary>
/// Gets or sets the card ordering settings. /// Gets or sets the board display settings (width and ordering).
/// </summary> /// </summary>
[JsonProperty("sort")] [JsonProperty("display")]
public SortSettings Sort { get; set; } = new(); public DisplaySettings Display { get; set; } = new();
/// <summary>
/// Gets or sets the board column width settings.
/// </summary>
[JsonProperty("column-width")]
public ColumnWidthSettings ColumnWidth { get; set; } = new();
/// <summary> /// <summary>
/// Gets or sets the confirmation-dialog settings. /// Gets or sets the confirmation-dialog settings.
+38 -152
View File
@@ -1,43 +1,28 @@
using Newtonsoft.Json; using Newtonsoft.Json;
using Newtonsoft.Json.Converters; using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
namespace YKanBan.Storage.AppData; namespace YKanBan.Storage.AppData;
/// <summary> /// <summary>
/// Loads and saves app.json with graceful degradation: a missing file yields /// Loads and saves app.json with graceful degradation: a missing or unreadable
/// defaults; a file that is not a JSON object is backed up to app.json.bak and /// file yields defaults; a corrupt file is backed up to app.json.bak and then
/// then defaults are used; an individual invalid field (unknown enum value or /// defaults are used. Saving writes the file directly (no atomic replace) —
/// language, out-of-range width, wrong type) falls back to its own default while
/// the other fields are kept. Saving happens only when the configuration differs
/// from what was loaded, and writes the file directly (no atomic replace) —
/// losing the last session's settings to a crash is an accepted trade-off. /// losing the last session's settings to a crash is an accepted trade-off.
/// </summary> /// </summary>
public sealed class AppConfigStore public sealed class AppConfigStore {
{ private static readonly JsonSerializerSettings SerializerSettings = new() {
private static readonly JsonSerializerSettings SerializerSettings = new()
{
Formatting = Formatting.Indented, Formatting = Formatting.Indented,
NullValueHandling = NullValueHandling.Ignore, NullValueHandling = NullValueHandling.Ignore,
// Enums round-trip through the kebab-case strings declared via [EnumMember]; // Enums round-trip through the kebab-case strings declared via [EnumMember];
// numeric enum values are rejected like any other unknown value. // numeric enum values are rejected like any other unknown value.
// YYC MARK: non-enum fields (bool/int/string) are still coerced by
// Newtonsoft (for example 0 or "true" to bool, "500" or 500.0 to int);
// a wrongly typed non-enum value is accepted and converted rather than
// treated as invalid. That leniency is accepted here.
Converters = { new StringEnumConverter { AllowIntegerValues = false } }, Converters = { new StringEnumConverter { AllowIntegerValues = false } },
}; };
private static readonly JsonSerializer FieldTolerantSerializer = JsonSerializer.Create(new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore,
Converters = { new StringEnumConverter { AllowIntegerValues = false } },
// The JSON text is already known to be well formed here, so every error is a
// single member that fails to convert: skip it and keep that member's default.
Error = (_, args) => args.ErrorContext.Handled = true,
});
/// <summary>The serialized form of the configuration as last loaded or saved.</summary>
private string _persistedSnapshot = Serialize(new AppConfig());
/// <summary> /// <summary>
/// Initializes a store bound to a specific app.json path. /// Initializes a store bound to a specific app.json path.
/// </summary> /// </summary>
@@ -50,157 +35,58 @@ public sealed class AppConfigStore
public string FilePath { get; } public string FilePath { get; }
/// <summary> /// <summary>
/// Loads the configuration and records it as the persisted baseline for /// Loads the configuration. A missing file yields defaults; a corrupt file
/// <see cref="SaveIfChanged"/>. A missing file yields defaults; a file that /// is backed up to app.json.bak and then defaults are used; a file that
/// is not a JSON object is backed up to app.json.bak and then defaults are /// exists but cannot be read (I/O or permission error) also yields defaults.
/// used; invalid fields fall back to their defaults individually.
/// </summary> /// </summary>
/// <returns>The loaded configuration, or defaults when none could be read.</returns> /// <returns>The loaded configuration, or defaults when none could be read.</returns>
/// <exception cref="IOException">The file exists but cannot be read.</exception> public AppConfig Load() {
public AppConfig Load()
{
AppConfig config = Read();
// The baseline is the effective configuration, so field fallbacks alone never trigger a write.
_persistedSnapshot = Serialize(config);
return config;
}
/// <summary>
/// Writes the configuration only when it differs from the loaded or last
/// saved one, i.e. when this session changed a setting.
/// </summary>
/// <param name="config">The live configuration.</param>
/// <returns><see langword="true"/> when the file was written.</returns>
public bool SaveIfChanged(AppConfig config)
{
string json = Serialize(config);
if (json == _persistedSnapshot)
{
return false;
}
Write(json);
_persistedSnapshot = json;
return true;
}
/// <summary>
/// Writes the configuration directly to disk (no atomic replace), unconditionally.
/// </summary>
/// <param name="config">The configuration to serialize.</param>
public void Save(AppConfig config)
{
string json = Serialize(config);
Write(json);
_persistedSnapshot = json;
}
/// <summary>
/// Reads and sanitizes the file.
/// </summary>
/// <returns>The effective configuration.</returns>
private AppConfig Read()
{
// Missing file is a normal first-run state: run with defaults. // Missing file is a normal first-run state: run with defaults.
if (!File.Exists(FilePath)) if (!File.Exists(FilePath)) {
{
return new AppConfig(); return new AppConfig();
} }
string json = File.ReadAllText(FilePath); string json;
JToken root; try {
try json = File.ReadAllText(FilePath);
{ } catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) {
root = JToken.Parse(json); // A bad app.json must not stop startup.
}
catch (JsonException)
{
return BackUpAndUseDefaults();
}
// A JSON null literal carries no settings at all; treat it like a missing file.
if (root.Type == JTokenType.Null)
{
return new AppConfig(); return new AppConfig();
} }
// Well-formed JSON of the wrong shape has no field to keep: handle it like corrupt text. try {
if (root is not JObject rootObject) // A JSON null literal deserializes to null; treat it like defaults.
{ AppConfig? config = JsonConvert.DeserializeObject<AppConfig>(json, SerializerSettings);
return BackUpAndUseDefaults(); if (config is null) {
}
AppConfig config = rootObject.ToObject<AppConfig>(FieldTolerantSerializer) ?? new AppConfig();
Sanitize(config);
return config;
}
/// <summary>
/// Keeps a copy of an unusable file for inspection, then continues with defaults.
/// </summary>
/// <returns>The default configuration.</returns>
private AppConfig BackUpAndUseDefaults()
{
File.Copy(FilePath, FilePath + ".bak", overwrite: true);
return new AppConfig(); return new AppConfig();
} }
/// <summary>
/// Replaces every value that converted but is outside its domain with the field default.
/// </summary>
/// <param name="config">The freshly deserialized configuration.</param>
private static void Sanitize(AppConfig config)
{
var defaults = new AppConfig();
// Older or hand-edited files may miss whole sections; each falls back to its defaults. // Older or hand-edited files may miss whole sections; each falls back to its defaults.
config.Sort ??= new SortSettings(); config.Display ??= new DisplaySettings();
config.ColumnWidth ??= new ColumnWidthSettings();
config.Confirmations ??= new ConfirmationSettings(); config.Confirmations ??= new ConfirmationSettings();
return config;
if (config.Language is null || !AppConfig.SupportedLanguages.Contains(config.Language, StringComparer.Ordinal)) } catch (JsonException) {
{ // Corrupt: keep a copy for inspection (best effort), then continue with defaults.
config.Language = defaults.Language; try {
File.Copy(FilePath, FilePath + ".bak", overwrite: true);
} catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) {
// The backup is only a diagnostic aid; starting with defaults matters more.
} }
if (!Enum.IsDefined(config.Theme)) return new AppConfig();
{
config.Theme = defaults.Theme;
}
if (!Enum.IsDefined(config.Sort.Card))
{
config.Sort.Card = defaults.Sort.Card;
}
if (!Enum.IsDefined(config.ColumnWidth.Preset))
{
config.ColumnWidth.Preset = defaults.ColumnWidth.Preset;
}
if (config.ColumnWidth.CustomPixels is < AppConfig.MinColumnPixels or > AppConfig.MaxColumnPixels)
{
config.ColumnWidth.CustomPixels = defaults.ColumnWidth.CustomPixels;
} }
} }
/// <summary> /// <summary>
/// Writes the serialized configuration, creating the parent folder on demand. /// Writes the configuration directly to disk (no atomic replace).
/// </summary> /// </summary>
/// <param name="json">The serialized configuration.</param> /// <param name="config">The configuration to serialize.</param>
private void Write(string json) public void Save(AppConfig config) {
{ // Create the parent folder on demand; normally it already exists.
// Normally the folder already exists.
string? directory = Path.GetDirectoryName(FilePath); string? directory = Path.GetDirectoryName(FilePath);
if (!string.IsNullOrEmpty(directory)) if (!string.IsNullOrEmpty(directory)) {
{
Directory.CreateDirectory(directory); Directory.CreateDirectory(directory);
} }
File.WriteAllText(FilePath, json); File.WriteAllText(FilePath, JsonConvert.SerializeObject(config, SerializerSettings));
} }
/// <summary>
/// Serializes a configuration in the on-disk format.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The JSON text.</returns>
private static string Serialize(AppConfig config) => JsonConvert.SerializeObject(config, SerializerSettings);
} }
+1 -2
View File
@@ -5,8 +5,7 @@ namespace YKanBan.Storage.AppData;
/// (%APPDATA%/YKanBan on Windows and the equivalent directory on other /// (%APPDATA%/YKanBan on Windows and the equivalent directory on other
/// platforms). /// platforms).
/// </summary> /// </summary>
public static class AppDataPaths public static class AppDataPaths {
{
/// <summary> /// <summary>
/// Gets the per-user YKanBan application data folder. /// Gets the per-user YKanBan application data folder.
/// </summary> /// </summary>
+16 -33
View File
@@ -5,11 +5,9 @@ namespace YKanBan.Storage;
/// <summary> /// <summary>
/// Shared SQLite plumbing for workspace databases: opens a connection with /// Shared SQLite plumbing for workspace databases: opens a connection with
/// the mandated PRAGMA configuration (WAL journal, NORMAL synchronous mode, /// the mandated PRAGMA configuration (WAL journal, NORMAL synchronous mode,
/// foreign keys on), registers the custom SQL functions and applies /// foreign keys on) and applies incremental <c>user_version</c> migrations.
/// incremental <c>user_version</c> migrations.
/// </summary> /// </summary>
public static class SqliteDatabase public static class SqliteDatabase {
{
/// <summary> /// <summary>
/// Name of the per-connection SQL function that applies <see cref="Fold"/>; /// Name of the per-connection SQL function that applies <see cref="Fold"/>;
/// search uses it for Unicode case-insensitive matching. /// search uses it for Unicode case-insensitive matching.
@@ -31,10 +29,8 @@ public static class SqliteDatabase
/// <param name="databasePath">Path of the SQLite database file.</param> /// <param name="databasePath">Path of the SQLite database file.</param>
/// <param name="migrations">Contiguous migration list ordered by version, starting at 1.</param> /// <param name="migrations">Contiguous migration list ordered by version, starting at 1.</param>
/// <returns>An open connection with all PRAGMAs applied and the schema migrated.</returns> /// <returns>An open connection with all PRAGMAs applied and the schema migrated.</returns>
public static SqliteConnection Open(string databasePath, IReadOnlyList<SchemaMigration> migrations) public static SqliteConnection Open(string databasePath, IReadOnlyList<SchemaMigration> migrations) {
{ var connection = new SqliteConnection(new SqliteConnectionStringBuilder {
var connection = new SqliteConnection(new SqliteConnectionStringBuilder
{
DataSource = databasePath, DataSource = databasePath,
Mode = SqliteOpenMode.ReadWriteCreate, Mode = SqliteOpenMode.ReadWriteCreate,
@@ -43,15 +39,12 @@ public static class SqliteDatabase
}.ToString()); }.ToString());
connection.Open(); connection.Open();
try try {
{
ApplyPragmas(connection); ApplyPragmas(connection);
RegisterFunctions(connection); RegisterFunctions(connection);
ApplyMigrations(connection, migrations); ApplyMigrations(connection, migrations);
return connection; return connection;
} } catch {
catch
{
connection.Dispose(); connection.Dispose();
throw; throw;
} }
@@ -62,8 +55,7 @@ public static class SqliteDatabase
/// </summary> /// </summary>
/// <param name="connection">An open database connection.</param> /// <param name="connection">An open database connection.</param>
/// <returns>The stored schema version.</returns> /// <returns>The stored schema version.</returns>
public static long ReadUserVersion(SqliteConnection connection) public static long ReadUserVersion(SqliteConnection connection) {
{
using var command = connection.CreateCommand(); using var command = connection.CreateCommand();
command.CommandText = "PRAGMA user_version;"; command.CommandText = "PRAGMA user_version;";
return (long)command.ExecuteScalar()!; return (long)command.ExecuteScalar()!;
@@ -75,8 +67,7 @@ public static class SqliteDatabase
/// enabled on every connection or the DDL cascades never fire. /// enabled on every connection or the DDL cascades never fire.
/// </summary> /// </summary>
/// <param name="connection">An open database connection.</param> /// <param name="connection">An open database connection.</param>
internal static void ApplyPragmas(SqliteConnection connection) internal static void ApplyPragmas(SqliteConnection connection) {
{
// WAL plus NORMAL synchronous is the chosen durability/performance trade-off. // WAL plus NORMAL synchronous is the chosen durability/performance trade-off.
Execute(connection, "PRAGMA journal_mode=WAL;"); Execute(connection, "PRAGMA journal_mode=WAL;");
Execute(connection, "PRAGMA synchronous=NORMAL;"); Execute(connection, "PRAGMA synchronous=NORMAL;");
@@ -88,8 +79,7 @@ public static class SqliteDatabase
/// connection and must be registered on every one. /// connection and must be registered on every one.
/// </summary> /// </summary>
/// <param name="connection">An open database connection.</param> /// <param name="connection">An open database connection.</param>
internal static void RegisterFunctions(SqliteConnection connection) internal static void RegisterFunctions(SqliteConnection connection) {
{
// NULL never reaches it from the NOT NULL text columns, but stays NULL-safe regardless. // NULL never reaches it from the NOT NULL text columns, but stays NULL-safe regardless.
connection.CreateFunction<string?, string?>( connection.CreateFunction<string?, string?>(
FoldFunctionName, text => text is null ? null : Fold(text), isDeterministic: true); FoldFunctionName, text => text is null ? null : Fold(text), isDeterministic: true);
@@ -103,13 +93,10 @@ public static class SqliteDatabase
/// <param name="migrations">Contiguous migration list ordered by version, starting at 1.</param> /// <param name="migrations">Contiguous migration list ordered by version, starting at 1.</param>
/// <exception cref="ArgumentException">The migration list is not contiguous from version 1.</exception> /// <exception cref="ArgumentException">The migration list is not contiguous from version 1.</exception>
/// <exception cref="SchemaVersionException">The database was written by a newer build.</exception> /// <exception cref="SchemaVersionException">The database was written by a newer build.</exception>
internal static void ApplyMigrations(SqliteConnection connection, IReadOnlyList<SchemaMigration> migrations) internal static void ApplyMigrations(SqliteConnection connection, IReadOnlyList<SchemaMigration> migrations) {
{
// Contract check: the list must be ordered, contiguous and start at version 1. // Contract check: the list must be ordered, contiguous and start at version 1.
for (int index = 0; index < migrations.Count; index++) for (int index = 0; index < migrations.Count; index++) {
{ if (migrations[index].Version != index + 1) {
if (migrations[index].Version != index + 1)
{
throw new ArgumentException("Migrations must be contiguous and start at version 1.", nameof(migrations)); throw new ArgumentException("Migrations must be contiguous and start at version 1.", nameof(migrations));
} }
} }
@@ -118,16 +105,13 @@ public static class SqliteDatabase
int latest = migrations.Count; int latest = migrations.Count;
// A database written by a newer build cannot be managed by this one; refuse loudly. // A database written by a newer build cannot be managed by this one; refuse loudly.
if (current > latest) if (current > latest) {
{
throw new SchemaVersionException(current, latest); throw new SchemaVersionException(current, latest);
} }
// Apply each pending migration atomically so a crash never leaves a half-migrated database. // Apply each pending migration atomically so a crash never leaves a half-migrated database.
foreach (SchemaMigration migration in migrations) foreach (SchemaMigration migration in migrations) {
{ if (migration.Version <= current) {
if (migration.Version <= current)
{
continue; continue;
} }
@@ -144,8 +128,7 @@ public static class SqliteDatabase
/// <param name="connection">An open database connection.</param> /// <param name="connection">An open database connection.</param>
/// <param name="commandText">The SQL script to execute.</param> /// <param name="commandText">The SQL script to execute.</param>
/// <param name="transaction">The transaction to enlist in, when any.</param> /// <param name="transaction">The transaction to enlist in, when any.</param>
private static void Execute(SqliteConnection connection, string commandText, SqliteTransaction? transaction = null) private static void Execute(SqliteConnection connection, string commandText, SqliteTransaction? transaction = null) {
{
using var command = connection.CreateCommand(); using var command = connection.CreateCommand();
command.Transaction = transaction; command.Transaction = transaction;
command.CommandText = commandText; command.CommandText = commandText;
+31 -111
View File
@@ -5,24 +5,21 @@ namespace YKanBan.Storage;
/// Exception messages are always English and never localized; the UI maps the /// Exception messages are always English and never localized; the UI maps the
/// exception type to a localized resource key instead. /// exception type to a localized resource key instead.
/// </summary> /// </summary>
public abstract class YKanBanException : Exception public abstract class YKanBanException : Exception {
{
/// <summary> /// <summary>
/// Initializes the exception with an English diagnostic message. /// Initializes the exception with an English diagnostic message.
/// </summary> /// </summary>
/// <param name="message">The English diagnostic message.</param> /// <param name="message">The English diagnostic message.</param>
/// <param name="innerException">The underlying cause, when any.</param> /// <param name="innerException">The underlying cause, when any.</param>
protected YKanBanException(string message, Exception? innerException = null) protected YKanBanException(string message, Exception? innerException = null)
: base(message, innerException) : base(message, innerException) {
{
} }
} }
/// <summary> /// <summary>
/// Signals that the folder passed on the command line does not exist on disk. /// Signals that the folder passed on the command line does not exist on disk.
/// </summary> /// </summary>
public sealed class WorkspaceDirectoryMissingException : YKanBanException public sealed class WorkspaceDirectoryMissingException : YKanBanException {
{
/// <summary> /// <summary>
/// Gets the folder path that was expected to exist. /// Gets the folder path that was expected to exist.
/// </summary> /// </summary>
@@ -33,8 +30,7 @@ public sealed class WorkspaceDirectoryMissingException : YKanBanException
/// </summary> /// </summary>
/// <param name="folderPath">The missing folder path.</param> /// <param name="folderPath">The missing folder path.</param>
public WorkspaceDirectoryMissingException(string folderPath) public WorkspaceDirectoryMissingException(string folderPath)
: base($"The folder does not exist: {folderPath}") : base($"The folder does not exist: {folderPath}") {
{
FolderPath = folderPath; FolderPath = folderPath;
} }
} }
@@ -43,8 +39,7 @@ public sealed class WorkspaceDirectoryMissingException : YKanBanException
/// Signals that a folder exists but has no .ykanban structure, so it is not /// Signals that a folder exists but has no .ykanban structure, so it is not
/// (yet) a workspace. /// (yet) a workspace.
/// </summary> /// </summary>
public sealed class WorkspaceNotInitializedException : YKanBanException public sealed class WorkspaceNotInitializedException : YKanBanException {
{
/// <summary> /// <summary>
/// Gets the folder path that lacks the .ykanban structure. /// Gets the folder path that lacks the .ykanban structure.
/// </summary> /// </summary>
@@ -55,56 +50,49 @@ public sealed class WorkspaceNotInitializedException : YKanBanException
/// </summary> /// </summary>
/// <param name="folderPath">The uninitialized folder path.</param> /// <param name="folderPath">The uninitialized folder path.</param>
public WorkspaceNotInitializedException(string folderPath) public WorkspaceNotInitializedException(string folderPath)
: base($"The folder is not a YKanBan workspace (missing .ykanban): {folderPath}") : base($"The folder is not a YKanBan workspace (missing .ykanban): {folderPath}") {
{
FolderPath = folderPath; FolderPath = folderPath;
} }
} }
/// <summary>
/// Signals that .ykanban exists but its database file does not, so the
/// workspace data is missing; a new empty database is never created silently.
/// </summary>
public sealed class WorkspaceDatabaseMissingException : YKanBanException {
/// <summary>
/// Gets the database file that was expected to exist.
/// </summary>
public string DatabasePath { get; }
/// <summary>
/// Initializes the exception for a missing workspace database.
/// </summary>
/// <param name="databasePath">The missing database file path.</param>
public WorkspaceDatabaseMissingException(string databasePath)
: base($"The workspace database is missing: {databasePath}") {
DatabasePath = databasePath;
}
}
/// <summary> /// <summary>
/// Signals that another instance already holds the workspace lock, so this /// Signals that another instance already holds the workspace lock, so this
/// process must not touch the workspace. /// process must not touch the workspace.
/// </summary> /// </summary>
public sealed class WorkspaceLockException : YKanBanException public sealed class WorkspaceLockException : YKanBanException {
{
/// <summary> /// <summary>
/// Gets the lock file that could not be acquired. /// Gets the lock file that could not be acquired.
/// </summary> /// </summary>
public string LockFilePath { get; } public string LockFilePath { get; }
/// <summary>
/// Gets the best-effort holder diagnostics read from the lock file, or
/// <see langword="null"/> when they could not be read.
/// </summary>
public string? HolderDiagnostics { get; }
/// <summary> /// <summary>
/// Initializes the exception for a failed lock acquisition. /// Initializes the exception for a failed lock acquisition.
/// </summary> /// </summary>
/// <param name="lockFilePath">The lock file that is already held.</param> /// <param name="lockFilePath">The lock file that is already held.</param>
/// <param name="holderDiagnostics">Diagnostics of the current holder, when readable.</param>
/// <param name="innerException">The underlying I/O error.</param> /// <param name="innerException">The underlying I/O error.</param>
public WorkspaceLockException(string lockFilePath, string? holderDiagnostics, Exception innerException) public WorkspaceLockException(string lockFilePath, Exception innerException)
: base(BuildMessage(lockFilePath, holderDiagnostics), innerException) : base($"The workspace is locked by another instance: {lockFilePath}", innerException) {
{
LockFilePath = lockFilePath; LockFilePath = lockFilePath;
HolderDiagnostics = holderDiagnostics;
}
/// <summary>
/// Composes the diagnostic message, appending holder details when they were readable.
/// </summary>
/// <param name="lockFilePath">The lock file that is already held.</param>
/// <param name="holderDiagnostics">Diagnostics of the current holder, when readable.</param>
/// <returns>The English diagnostic message.</returns>
private static string BuildMessage(string lockFilePath, string? holderDiagnostics)
{
string message = $"The workspace is locked by another instance: {lockFilePath}";
if (!string.IsNullOrEmpty(holderDiagnostics))
{
message += $" Lock holder: {holderDiagnostics}";
}
return message;
} }
} }
@@ -112,8 +100,7 @@ public sealed class WorkspaceLockException : YKanBanException
/// Signals that the database was written by a newer build than the one /// Signals that the database was written by a newer build than the one
/// currently running, so its schema cannot be safely managed. /// currently running, so its schema cannot be safely managed.
/// </summary> /// </summary>
public sealed class SchemaVersionException : YKanBanException public sealed class SchemaVersionException : YKanBanException {
{
/// <summary> /// <summary>
/// Gets the user_version value found in the database. /// Gets the user_version value found in the database.
/// </summary> /// </summary>
@@ -130,75 +117,8 @@ public sealed class SchemaVersionException : YKanBanException
/// <param name="storedVersion">The user_version read from the database.</param> /// <param name="storedVersion">The user_version read from the database.</param>
/// <param name="supportedVersion">The newest schema version this build supports.</param> /// <param name="supportedVersion">The newest schema version this build supports.</param>
public SchemaVersionException(long storedVersion, int supportedVersion) public SchemaVersionException(long storedVersion, int supportedVersion)
: base($"Database schema version {storedVersion} is newer than the latest supported version {supportedVersion}.") : base($"Database schema version {storedVersion} is newer than the latest supported version {supportedVersion}.") {
{
StoredVersion = storedVersion; StoredVersion = storedVersion;
SupportedVersion = supportedVersion; SupportedVersion = supportedVersion;
} }
} }
/// <summary>
/// The entities whose name/title is constrained by the schema to be non-empty
/// and table-unique.
/// </summary>
public enum NamedEntity
{
/// <summary>A board column (constraint on columns.title).</summary>
Column,
/// <summary>A tag (constraint on tags.name).</summary>
Tag,
}
/// <summary>
/// Signals that a column title or tag name was empty, violating the schema's
/// CHECK constraint. Nothing was written.
/// </summary>
public sealed class NameRequiredException : YKanBanException
{
/// <summary>
/// Gets the entity whose name was empty.
/// </summary>
public NamedEntity Entity { get; }
/// <summary>
/// Initializes the exception for an empty name.
/// </summary>
/// <param name="entity">The entity whose name was empty.</param>
/// <param name="innerException">The underlying constraint violation.</param>
public NameRequiredException(NamedEntity entity, Exception innerException)
: base($"The {entity.ToString().ToLowerInvariant()} name must not be empty.", innerException)
{
Entity = entity;
}
}
/// <summary>
/// Signals that a column title or tag name already exists (compared with ASCII
/// case folding), violating the schema's UNIQUE constraint. Nothing was written.
/// </summary>
public sealed class DuplicateNameException : YKanBanException
{
/// <summary>
/// Gets the entity whose name collided.
/// </summary>
public NamedEntity Entity { get; }
/// <summary>
/// Gets the rejected name.
/// </summary>
public string Name { get; }
/// <summary>
/// Initializes the exception for a name collision.
/// </summary>
/// <param name="entity">The entity whose name collided.</param>
/// <param name="name">The rejected name.</param>
/// <param name="innerException">The underlying constraint violation.</param>
public DuplicateNameException(NamedEntity entity, string name, Exception innerException)
: base($"A {entity.ToString().ToLowerInvariant()} named '{name}' already exists.", innerException)
{
Entity = entity;
Name = name;
}
}
+1 -2
View File
@@ -4,8 +4,7 @@ namespace YKanBan.Storage;
/// Supplies the current Unix timestamp. Every timestamp persisted by YKanBan /// Supplies the current Unix timestamp. Every timestamp persisted by YKanBan
/// is an INTEGER count of Unix seconds. /// is an INTEGER count of Unix seconds.
/// </summary> /// </summary>
public static class UnixTime public static class UnixTime {
{
/// <summary> /// <summary>
/// Gets the current UTC time expressed as Unix seconds. /// Gets the current UTC time expressed as Unix seconds.
/// </summary> /// </summary>
@@ -8,8 +8,7 @@ namespace YKanBan.Storage.Workspace;
/// separate concern handled by <see cref="WorkspacePreset"/>, so the /// separate concern handled by <see cref="WorkspacePreset"/>, so the
/// database can be created without any rows. /// database can be created without any rows.
/// </summary> /// </summary>
public static class WorkspaceInitializer public static class WorkspaceInitializer {
{
/// <summary> /// <summary>
/// Returns whether the folder contains a .ykanban structure. Only the /// Returns whether the folder contains a .ykanban structure. Only the
/// passed folder is checked; parent folders are never searched. /// passed folder is checked; parent folders are never searched.
@@ -25,16 +24,19 @@ public static class WorkspaceInitializer
/// <param name="folderPath">The existing folder to initialize.</param> /// <param name="folderPath">The existing folder to initialize.</param>
/// <exception cref="WorkspaceDirectoryMissingException">The folder does not exist on disk.</exception> /// <exception cref="WorkspaceDirectoryMissingException">The folder does not exist on disk.</exception>
/// <exception cref="InvalidOperationException">The workspace database already exists.</exception> /// <exception cref="InvalidOperationException">The workspace database already exists.</exception>
public static void Initialize(string folderPath) public static void Initialize(string folderPath) {
{ // YYC MARK: this class is deliberately a lock-free, functional unit; it
if (!Directory.Exists(folderPath)) // does not acquire the workspace lock. Ensuring the lock is held before
{ // initialization is the caller's responsibility (see
// WorkspaceSession.Initialize). The schema migration and the later preset
// writes are also not one transaction, so a crash mid-initialization can
// leave a partially built database; that is accepted here.
if (!Directory.Exists(folderPath)) {
throw new WorkspaceDirectoryMissingException(folderPath); throw new WorkspaceDirectoryMissingException(folderPath);
} }
string databasePath = WorkspacePaths.Database(folderPath); string databasePath = WorkspacePaths.Database(folderPath);
if (File.Exists(databasePath)) if (File.Exists(databasePath)) {
{
throw new InvalidOperationException($"The workspace database already exists: {databasePath}"); throw new InvalidOperationException($"The workspace database already exists: {databasePath}");
} }
+14 -49
View File
@@ -1,14 +1,11 @@
using System.Text;
namespace YKanBan.Storage.Workspace; namespace YKanBan.Storage.Workspace;
/// <summary> /// <summary>
/// Exclusive, OS-enforced lock over a workspace's ykanban.lock. The handle is /// Exclusive, OS-enforced lock over a workspace's ykanban.lock. The handle is
/// held until disposal, so crashes and power loss release it automatically. /// held until disposal, so crashes and power loss release it automatically. The
/// The lock file also carries PID / machine name / time for human diagnostics. /// lock file is kept empty; only its exclusive OS handle carries meaning.
/// </summary> /// </summary>
public sealed class WorkspaceLock : IDisposable public sealed class WorkspaceLock : IDisposable {
{
private readonly FileStream _stream; private readonly FileStream _stream;
/// <summary> /// <summary>
@@ -16,8 +13,7 @@ public sealed class WorkspaceLock : IDisposable
/// </summary> /// </summary>
/// <param name="stream">The exclusively opened lock file stream.</param> /// <param name="stream">The exclusively opened lock file stream.</param>
/// <param name="lockFilePath">Path of the lock file being held.</param> /// <param name="lockFilePath">Path of the lock file being held.</param>
private WorkspaceLock(FileStream stream, string lockFilePath) private WorkspaceLock(FileStream stream, string lockFilePath) {
{
_stream = stream; _stream = stream;
LockFilePath = lockFilePath; LockFilePath = lockFilePath;
} }
@@ -28,61 +24,30 @@ public sealed class WorkspaceLock : IDisposable
public string LockFilePath { get; } public string LockFilePath { get; }
/// <summary> /// <summary>
/// Acquires the workspace lock, writing this process's diagnostics into it. /// Acquires the workspace lock, leaving the lock file empty.
/// </summary> /// </summary>
/// <param name="folderPath">The workspace folder to lock.</param> /// <param name="folderPath">The workspace folder to lock.</param>
/// <returns>The held lock; dispose it to release.</returns> /// <returns>The held lock; dispose it to release.</returns>
/// <exception cref="WorkspaceNotInitializedException">The folder has no .ykanban structure.</exception> /// <exception cref="WorkspaceNotInitializedException">The folder has no .ykanban structure.</exception>
/// <exception cref="WorkspaceLockException">Another instance already holds the lock.</exception> /// <exception cref="WorkspaceLockException">Another instance already holds the lock.</exception>
public static WorkspaceLock Acquire(string folderPath) public static WorkspaceLock Acquire(string folderPath) {
{
string lockFilePath = WorkspacePaths.LockFile(folderPath); string lockFilePath = WorkspacePaths.LockFile(folderPath);
FileStream stream; FileStream stream;
try try {
{ // FileShare.None gives the exclusive semantics; FileMode.Create empties any stale file.
// FileShare.None gives the exclusive semantics; FileMode.Create truncates stale content. // SAFETY: FileMode.Create truncates a pre-existing file, but the lock
// file is empty by design and the path always comes from
// WorkspacePaths.LockFile, so no user data is ever affected.
stream = new FileStream(lockFilePath, FileMode.Create, FileAccess.Write, FileShare.None); stream = new FileStream(lockFilePath, FileMode.Create, FileAccess.Write, FileShare.None);
} } catch (DirectoryNotFoundException) {
catch (DirectoryNotFoundException)
{
throw new WorkspaceNotInitializedException(folderPath); throw new WorkspaceNotInitializedException(folderPath);
} } catch (IOException ex) {
catch (IOException ex) throw new WorkspaceLockException(lockFilePath, ex);
{
throw new WorkspaceLockException(lockFilePath, ReadDiagnosticsBestEffort(lockFilePath), ex);
} }
// Write holder diagnostics so humans can identify the owning instance from the file alone.
string diagnostics = $"pid={Environment.ProcessId};machine={Environment.MachineName};time={DateTimeOffset.UtcNow:O}";
byte[] payload = Encoding.UTF8.GetBytes(diagnostics);
stream.Write(payload, 0, payload.Length);
stream.Flush();
return new WorkspaceLock(stream, lockFilePath); return new WorkspaceLock(stream, lockFilePath);
} }
/// <summary>
/// Attempts to read holder diagnostics from a lock file we failed to
/// acquire. The read is best-effort: a live FileShare.None holder makes the
/// file unreadable, in which case <see langword="null"/> is returned.
/// </summary>
/// <param name="lockFilePath">The lock file to read.</param>
/// <returns>The diagnostics text, or <see langword="null"/> when unreadable.</returns>
private static string? ReadDiagnosticsBestEffort(string lockFilePath)
{
try
{
return File.ReadAllText(lockFilePath);
}
catch (IOException)
{
return null;
}
catch (UnauthorizedAccessException)
{
return null;
}
}
/// <summary> /// <summary>
/// Releases the exclusive handle. The lock file itself is intentionally /// Releases the exclusive handle. The lock file itself is intentionally
/// left on disk; the OS releases the handle even on a crash. /// left on disk; the OS releases the handle even on a crash.
+1 -2
View File
@@ -4,8 +4,7 @@ namespace YKanBan.Storage.Workspace;
/// Well-known file and folder names inside a workspace's .ykanban structure, /// Well-known file and folder names inside a workspace's .ykanban structure,
/// plus helpers that combine them with a workspace folder path. /// plus helpers that combine them with a workspace folder path.
/// </summary> /// </summary>
public static class WorkspacePaths public static class WorkspacePaths {
{
/// <summary> /// <summary>
/// Name of the workspace root folder created inside a managed project. /// Name of the workspace root folder created inside a managed project.
/// </summary> /// </summary>
+54 -17
View File
@@ -3,48 +3,85 @@ using Microsoft.Data.Sqlite;
namespace YKanBan.Storage.Workspace; namespace YKanBan.Storage.Workspace;
/// <summary> /// <summary>
/// Adds the initial workspace content. The three preset column titles are read /// Adds the initial workspace content. The preset column titles/descriptions and
/// straight from the ResX resources in the UI language active when they are /// tag names/descriptions are read straight from the ResX resources in the UI
/// added; they then become ordinary data that no longer follows language /// language active when they are added; they then become ordinary data that no
/// switches. /// longer follows language switches.
/// </summary> /// </summary>
public static class WorkspacePreset public static class WorkspacePreset {
{
/// <summary> /// <summary>
/// Inserts the three preset columns (the current language's equivalents of /// Inserts the three preset columns (the current language's equivalents of
/// To Do / In Progress / Done) in a single transaction. /// To Do / In Progress / Done) with their descriptions in a single transaction.
/// </summary> /// </summary>
/// <param name="folderPath">The initialized workspace folder.</param> /// <param name="folderPath">The initialized workspace folder.</param>
/// <exception cref="SqliteException">The workspace database does not exist or a title collides with an existing column.</exception> /// <exception cref="SqliteException">The workspace database does not exist or a title collides with an existing column.</exception>
public static void AddPresetColumns(string folderPath) public static void AddPresetColumns(string folderPath) {
{
using SqliteConnection connection = SqliteDatabase.Open( using SqliteConnection connection = SqliteDatabase.Open(
WorkspacePaths.Database(folderPath), WorkspaceSchema.Migrations); WorkspacePaths.Database(folderPath), WorkspaceSchema.Migrations);
long now = UnixTime.Now; long now = UnixTime.Now;
// Preset titles are data at creation time: whatever the current language says gets stored. // Preset titles and descriptions are data at creation time: whatever the current language says gets stored.
string[] titles = (string Title, string Description)[] columns =
[ [
Resources.PresetColumn_Todo, (Resources.PresetColumn_Todo, Resources.PresetColumn_Todo_Description),
Resources.PresetColumn_InProgress, (Resources.PresetColumn_InProgress, Resources.PresetColumn_InProgress_Description),
Resources.PresetColumn_Done, (Resources.PresetColumn_Done, Resources.PresetColumn_Done_Description),
]; ];
// Insert all three atomically so a partially populated workspace can never exist. // Insert all three atomically so a partially populated workspace can never exist.
using var transaction = connection.BeginTransaction(); using var transaction = connection.BeginTransaction();
foreach (string title in titles) foreach ((string title, string description) in columns) {
{
using var command = connection.CreateCommand(); using var command = connection.CreateCommand();
command.Transaction = transaction; command.Transaction = transaction;
command.CommandText = """ command.CommandText = """
INSERT INTO columns (title, description, created_at, updated_at) INSERT INTO columns (title, description, created_at, updated_at)
VALUES ($title, '', $now, $now); VALUES ($title, $description, $now, $now);
"""; """;
command.Parameters.AddWithValue("$title", title); command.Parameters.AddWithValue("$title", title);
command.Parameters.AddWithValue("$description", description);
command.Parameters.AddWithValue("$now", now); command.Parameters.AddWithValue("$now", now);
command.ExecuteNonQuery(); command.ExecuteNonQuery();
} }
transaction.Commit(); transaction.Commit();
} }
/// <summary>
/// Inserts the preset tag set (names, colors and descriptions in the current
/// language) in a single transaction.
/// </summary>
/// <param name="folderPath">The initialized workspace folder.</param>
/// <exception cref="SqliteException">The workspace database does not exist or a tag name collides.</exception>
public static void AddPresetTags(string folderPath) {
using SqliteConnection connection = SqliteDatabase.Open(
WorkspacePaths.Database(folderPath), WorkspaceSchema.Migrations);
// Colors are stored in the canonical lowercase #rrggbb form.
(string Name, string Color, string Description)[] tags =
[
(Resources.PresetTag_Bug_Name, "#d73a4a", Resources.PresetTag_Bug_Description),
(Resources.PresetTag_Documentation_Name, "#0075ca", Resources.PresetTag_Documentation_Description),
(Resources.PresetTag_Duplicate_Name, "#cfd3d7", Resources.PresetTag_Duplicate_Description),
(Resources.PresetTag_Enhancement_Name, "#a2eeef", Resources.PresetTag_Enhancement_Description),
(Resources.PresetTag_HelpWanted_Name, "#008672", Resources.PresetTag_HelpWanted_Description),
(Resources.PresetTag_Invalid_Name, "#e4e669", Resources.PresetTag_Invalid_Description),
(Resources.PresetTag_Question_Name, "#d876e3", Resources.PresetTag_Question_Description),
(Resources.PresetTag_Wontfix_Name, "#ffffff", Resources.PresetTag_Wontfix_Description),
];
using var transaction = connection.BeginTransaction();
foreach ((string name, string color, string description) in tags) {
using var command = connection.CreateCommand();
command.Transaction = transaction;
command.CommandText = """
INSERT INTO tags (name, color, description)
VALUES ($name, $color, $description);
""";
command.Parameters.AddWithValue("$name", name);
command.Parameters.AddWithValue("$color", color);
command.Parameters.AddWithValue("$description", description);
command.ExecuteNonQuery();
}
transaction.Commit();
}
} }
+69 -153
View File
@@ -1,4 +1,5 @@
using Microsoft.Data.Sqlite; using Microsoft.Data.Sqlite;
using YKanBan.Models; using YKanBan.Models;
using YKanBan.Search; using YKanBan.Search;
@@ -14,16 +15,14 @@ namespace YKanBan.Storage.Workspace;
/// - columns.updated_at refreshes only when title or description changes; /// - columns.updated_at refreshes only when title or description changes;
/// - a confirmation with no effective change performs no write at all. /// - a confirmation with no effective change performs no write at all.
/// </summary> /// </summary>
public sealed class WorkspaceRepository : IDisposable public sealed class WorkspaceRepository : IDisposable {
{
private readonly SqliteConnection _connection; private readonly SqliteConnection _connection;
/// <summary> /// <summary>
/// Opens the repository over an initialized workspace database. /// Opens the repository over an initialized workspace database.
/// </summary> /// </summary>
/// <param name="folderPath">The workspace folder.</param> /// <param name="folderPath">The workspace folder.</param>
public WorkspaceRepository(string folderPath) public WorkspaceRepository(string folderPath) {
{
_connection = SqliteDatabase.Open(WorkspacePaths.Database(folderPath), WorkspaceSchema.Migrations); _connection = SqliteDatabase.Open(WorkspacePaths.Database(folderPath), WorkspaceSchema.Migrations);
} }
@@ -38,15 +37,13 @@ public sealed class WorkspaceRepository : IDisposable
/// Returns all columns ordered by id ascending. /// Returns all columns ordered by id ascending.
/// </summary> /// </summary>
/// <returns>All columns in id order.</returns> /// <returns>All columns in id order.</returns>
public IReadOnlyList<ColumnModel> GetColumns() public IReadOnlyList<ColumnModel> GetColumns() {
{
using var command = CreateCommand( using var command = CreateCommand(
"SELECT id, title, description, created_at, updated_at FROM columns ORDER BY id ASC;"); "SELECT id, title, description, created_at, updated_at FROM columns ORDER BY id ASC;");
using var reader = command.ExecuteReader(); using var reader = command.ExecuteReader();
var columns = new List<ColumnModel>(); var columns = new List<ColumnModel>();
while (reader.Read()) while (reader.Read()) {
{
columns.Add(ReadColumn(reader)); columns.Add(ReadColumn(reader));
} }
return columns; return columns;
@@ -57,8 +54,7 @@ public sealed class WorkspaceRepository : IDisposable
/// </summary> /// </summary>
/// <param name="columnId">The column id.</param> /// <param name="columnId">The column id.</param>
/// <returns>The column, or <see langword="null"/> when it does not exist.</returns> /// <returns>The column, or <see langword="null"/> when it does not exist.</returns>
public ColumnModel? GetColumn(long columnId) public ColumnModel? GetColumn(long columnId) {
{
using var command = CreateCommand( using var command = CreateCommand(
"SELECT id, title, description, created_at, updated_at FROM columns WHERE id = $id;"); "SELECT id, title, description, created_at, updated_at FROM columns WHERE id = $id;");
command.Parameters.AddWithValue("$id", columnId); command.Parameters.AddWithValue("$id", columnId);
@@ -72,15 +68,13 @@ public sealed class WorkspaceRepository : IDisposable
/// <param name="title">The non-empty, table-unique title.</param> /// <param name="title">The non-empty, table-unique title.</param>
/// <param name="description">The optional description.</param> /// <param name="description">The optional description.</param>
/// <returns>The created column.</returns> /// <returns>The created column.</returns>
/// <exception cref="NameRequiredException">The title is empty.</exception> /// <exception cref="SqliteException">The title is empty or not unique.</exception>
/// <exception cref="DuplicateNameException">The title is not unique.</exception> public ColumnModel AddColumn(string title, string description) {
public ColumnModel AddColumn(string title, string description)
{
long now = UnixTime.Now; long now = UnixTime.Now;
using var transaction = _connection.BeginTransaction(); using var transaction = _connection.BeginTransaction();
long id = MapNameConstraint(NamedEntity.Column, title, () => ExecuteInsert(transaction, long id = ExecuteInsert(transaction,
"INSERT INTO columns (title, description, created_at, updated_at) VALUES ($title, $description, $now, $now);", "INSERT INTO columns (title, description, created_at, updated_at) VALUES ($title, $description, $now, $now);",
("$title", title), ("$description", description), ("$now", now))); ("$title", title), ("$description", description), ("$now", now));
transaction.Commit(); transaction.Commit();
return new ColumnModel(id, title, description, now, now); return new ColumnModel(id, title, description, now, now);
@@ -95,16 +89,13 @@ public sealed class WorkspaceRepository : IDisposable
/// <param name="description">The new description.</param> /// <param name="description">The new description.</param>
/// <returns>The updated column, or the unchanged one for a no-op.</returns> /// <returns>The updated column, or the unchanged one for a no-op.</returns>
/// <exception cref="InvalidOperationException">The column does not exist.</exception> /// <exception cref="InvalidOperationException">The column does not exist.</exception>
/// <exception cref="NameRequiredException">The new title is empty.</exception> /// <exception cref="SqliteException">The new title is empty or not unique.</exception>
/// <exception cref="DuplicateNameException">The new title is not unique.</exception> public ColumnModel UpdateColumn(long columnId, string title, string description) {
public ColumnModel UpdateColumn(long columnId, string title, string description)
{
ColumnModel existing = GetColumn(columnId) ColumnModel existing = GetColumn(columnId)
?? throw new InvalidOperationException($"Column {columnId} does not exist."); ?? throw new InvalidOperationException($"Column {columnId} does not exist.");
// Unchanged title and description: no write, no timestamp refresh. // Unchanged title and description: no write, no timestamp refresh.
if (existing.Title == title && existing.Description == description) if (existing.Title == title && existing.Description == description) {
{
return existing; return existing;
} }
@@ -115,7 +106,7 @@ public sealed class WorkspaceRepository : IDisposable
command.Parameters.AddWithValue("$description", description); command.Parameters.AddWithValue("$description", description);
command.Parameters.AddWithValue("$now", now); command.Parameters.AddWithValue("$now", now);
command.Parameters.AddWithValue("$id", columnId); command.Parameters.AddWithValue("$id", columnId);
MapNameConstraint(NamedEntity.Column, title, command.ExecuteNonQuery); command.ExecuteNonQuery();
return new ColumnModel(columnId, title, description, existing.CreatedAt, now); return new ColumnModel(columnId, title, description, existing.CreatedAt, now);
} }
@@ -135,44 +126,23 @@ public sealed class WorkspaceRepository : IDisposable
/// Returns all cards with their assigned tags loaded, ordered by id ascending. /// Returns all cards with their assigned tags loaded, ordered by id ascending.
/// </summary> /// </summary>
/// <returns>All cards in id order.</returns> /// <returns>All cards in id order.</returns>
public IReadOnlyList<CardModel> GetCards() => GetCards(null); public IReadOnlyList<CardModel> GetCards() {
using var command = CreateCommand("""
/// <summary>
/// Returns the cards matching a compiled search, with all of their assigned
/// tags loaded (the filter selects cards, it never trims their tag lists),
/// ordered by id ascending.
/// </summary>
/// <param name="filter">The compiled search, or <see langword="null"/> for every card.</param>
/// <returns>The matching cards in id order.</returns>
public IReadOnlyList<CardModel> GetCards(CompiledSearch? filter)
{
string where = filter is null ? "" : $"WHERE {filter.Predicate}";
using var command = CreateCommand($"""
SELECT c.id, c.column_id, c.title, c.content, c.created_at, c.updated_at, SELECT c.id, c.column_id, c.title, c.content, c.created_at, c.updated_at,
t.id, t.name, t.color, t.description t.id, t.name, t.color, t.description
FROM cards c FROM cards c
LEFT JOIN card_tags ct ON ct.card_id = c.id LEFT JOIN card_tags ct ON ct.card_id = c.id
LEFT JOIN tags t ON t.id = ct.tag_id LEFT JOIN tags t ON t.id = ct.tag_id
{where} ORDER BY c.id ASC;
ORDER BY c.id ASC, t.id ASC;
"""); """);
if (filter is not null)
{
foreach ((string name, object value) in filter.Parameters)
{
command.Parameters.AddWithValue(name, value);
}
}
using var reader = command.ExecuteReader(); using var reader = command.ExecuteReader();
// Single grouped pass: one output card per distinct card id, with its tags accumulated alongside. // Single grouped pass: one output card per distinct card id, with its tags accumulated alongside.
var cards = new List<CardModel>(); var cards = new List<CardModel>();
var tagsByCard = new Dictionary<long, List<TagModel>>(); var tagsByCard = new Dictionary<long, List<TagModel>>();
while (reader.Read()) while (reader.Read()) {
{
long cardId = reader.GetInt64(0); long cardId = reader.GetInt64(0);
if (!tagsByCard.TryGetValue(cardId, out List<TagModel>? tags)) if (!tagsByCard.TryGetValue(cardId, out List<TagModel>? tags)) {
{
tags = new List<TagModel>(); tags = new List<TagModel>();
tagsByCard[cardId] = tags; tagsByCard[cardId] = tags;
cards.Add(new CardModel( cards.Add(new CardModel(
@@ -185,21 +155,38 @@ public sealed class WorkspaceRepository : IDisposable
tags)); tags));
} }
if (!reader.IsDBNull(6)) if (!reader.IsDBNull(6)) {
{
tags.Add(ReadTag(reader, 6)); tags.Add(ReadTag(reader, 6));
} }
} }
return cards; return cards;
} }
/// <summary>
/// Returns the ids of the cards matching a compiled search predicate.
/// </summary>
/// <param name="search">The compiled search predicate and its parameters.</param>
/// <returns>The matching card ids.</returns>
public IReadOnlyCollection<long> GetCardIdsMatching(CompiledSearch search) {
using var command = CreateCommand($"SELECT c.id FROM cards c WHERE {search.Predicate};");
foreach ((string name, object value) in search.Parameters) {
command.Parameters.AddWithValue(name, value);
}
using var reader = command.ExecuteReader();
var ids = new HashSet<long>();
while (reader.Read()) {
ids.Add(reader.GetInt64(0));
}
return ids;
}
/// <summary> /// <summary>
/// Returns the card with the given id, with its tags loaded. /// Returns the card with the given id, with its tags loaded.
/// </summary> /// </summary>
/// <param name="cardId">The card id.</param> /// <param name="cardId">The card id.</param>
/// <returns>The card, or <see langword="null"/> when it does not exist.</returns> /// <returns>The card, or <see langword="null"/> when it does not exist.</returns>
public CardModel? GetCard(long cardId) public CardModel? GetCard(long cardId) {
{
using var command = CreateCommand(""" using var command = CreateCommand("""
SELECT c.id, c.column_id, c.title, c.content, c.created_at, c.updated_at, SELECT c.id, c.column_id, c.title, c.content, c.created_at, c.updated_at,
t.id, t.name, t.color, t.description t.id, t.name, t.color, t.description
@@ -207,7 +194,7 @@ public sealed class WorkspaceRepository : IDisposable
LEFT JOIN card_tags ct ON ct.card_id = c.id LEFT JOIN card_tags ct ON ct.card_id = c.id
LEFT JOIN tags t ON t.id = ct.tag_id LEFT JOIN tags t ON t.id = ct.tag_id
WHERE c.id = $id WHERE c.id = $id
ORDER BY t.id ASC; ORDER BY c.id ASC;
"""); """);
command.Parameters.AddWithValue("$id", cardId); command.Parameters.AddWithValue("$id", cardId);
using var reader = command.ExecuteReader(); using var reader = command.ExecuteReader();
@@ -215,8 +202,7 @@ public sealed class WorkspaceRepository : IDisposable
// The LEFT JOIN may repeat the card row once per tag; build it on the first row only. // The LEFT JOIN may repeat the card row once per tag; build it on the first row only.
CardModel? card = null; CardModel? card = null;
var tags = new List<TagModel>(); var tags = new List<TagModel>();
while (reader.Read()) while (reader.Read()) {
{
card ??= new CardModel( card ??= new CardModel(
reader.GetInt64(0), reader.GetInt64(0),
reader.GetInt64(1), reader.GetInt64(1),
@@ -226,8 +212,7 @@ public sealed class WorkspaceRepository : IDisposable
reader.GetInt64(5), reader.GetInt64(5),
tags); tags);
if (!reader.IsDBNull(6)) if (!reader.IsDBNull(6)) {
{
tags.Add(ReadTag(reader, 6)); tags.Add(ReadTag(reader, 6));
} }
} }
@@ -243,15 +228,13 @@ public sealed class WorkspaceRepository : IDisposable
/// <param name="tagIds">The tags to assign initially.</param> /// <param name="tagIds">The tags to assign initially.</param>
/// <returns>The created card with tags loaded.</returns> /// <returns>The created card with tags loaded.</returns>
/// <exception cref="SqliteException">The column or a tag id does not exist.</exception> /// <exception cref="SqliteException">The column or a tag id does not exist.</exception>
public CardModel AddCard(long columnId, string title, string content, IReadOnlyCollection<long> tagIds) public CardModel AddCard(long columnId, string title, string content, IReadOnlyCollection<long> tagIds) {
{
long now = UnixTime.Now; long now = UnixTime.Now;
using var transaction = _connection.BeginTransaction(); using var transaction = _connection.BeginTransaction();
long id = ExecuteInsert(transaction, long id = ExecuteInsert(transaction,
"INSERT INTO cards (column_id, title, content, created_at, updated_at) VALUES ($columnId, $title, $content, $now, $now);", "INSERT INTO cards (column_id, title, content, created_at, updated_at) VALUES ($columnId, $title, $content, $now, $now);",
("$columnId", columnId), ("$title", title), ("$content", content), ("$now", now)); ("$columnId", columnId), ("$title", title), ("$content", content), ("$now", now));
foreach (long tagId in tagIds.Distinct()) foreach (long tagId in tagIds.Distinct()) {
{
ExecuteNonQuery(transaction, ExecuteNonQuery(transaction,
"INSERT INTO card_tags (card_id, tag_id) VALUES ($cardId, $tagId);", "INSERT INTO card_tags (card_id, tag_id) VALUES ($cardId, $tagId);",
("$cardId", id), ("$tagId", tagId)); ("$cardId", id), ("$tagId", tagId));
@@ -274,15 +257,13 @@ public sealed class WorkspaceRepository : IDisposable
/// <returns>The updated card with tags loaded, or the unchanged one for a no-op.</returns> /// <returns>The updated card with tags loaded, or the unchanged one for a no-op.</returns>
/// <exception cref="InvalidOperationException">The card does not exist.</exception> /// <exception cref="InvalidOperationException">The card does not exist.</exception>
/// <exception cref="SqliteException">A tag id does not exist; nothing is written.</exception> /// <exception cref="SqliteException">A tag id does not exist; nothing is written.</exception>
public CardModel UpdateCard(long cardId, string title, string content, IReadOnlyCollection<long> tagIds) public CardModel UpdateCard(long cardId, string title, string content, IReadOnlyCollection<long> tagIds) {
{
CardModel existing = GetCard(cardId) CardModel existing = GetCard(cardId)
?? throw new InvalidOperationException($"Card {cardId} does not exist."); ?? throw new InvalidOperationException($"Card {cardId} does not exist.");
// No effective change in title, content or tag set: no write, no timestamp refresh. // No effective change in title, content or tag set: no write, no timestamp refresh.
bool tagsChanged = !tagIds.Distinct().ToHashSet().SetEquals(existing.Tags.Select(tag => tag.Id)); bool tagsChanged = !tagIds.Distinct().ToHashSet().SetEquals(existing.Tags.Select(tag => tag.Id));
if (existing.Title == title && existing.Content == content && !tagsChanged) if (existing.Title == title && existing.Content == content && !tagsChanged) {
{
return existing; return existing;
} }
@@ -295,8 +276,7 @@ public sealed class WorkspaceRepository : IDisposable
// Tag assignment is rewritten wholesale; card_tags carries nothing beyond the pair. // Tag assignment is rewritten wholesale; card_tags carries nothing beyond the pair.
ExecuteNonQuery(transaction, "DELETE FROM card_tags WHERE card_id = $id;", ("$id", cardId)); ExecuteNonQuery(transaction, "DELETE FROM card_tags WHERE card_id = $id;", ("$id", cardId));
foreach (long tagId in tagIds.Distinct()) foreach (long tagId in tagIds.Distinct()) {
{
ExecuteNonQuery(transaction, ExecuteNonQuery(transaction,
"INSERT INTO card_tags (card_id, tag_id) VALUES ($cardId, $tagId);", "INSERT INTO card_tags (card_id, tag_id) VALUES ($cardId, $tagId);",
("$cardId", cardId), ("$tagId", tagId)); ("$cardId", cardId), ("$tagId", tagId));
@@ -314,8 +294,7 @@ public sealed class WorkspaceRepository : IDisposable
/// <param name="cardId">The card to move.</param> /// <param name="cardId">The card to move.</param>
/// <param name="targetColumnId">The destination column.</param> /// <param name="targetColumnId">The destination column.</param>
/// <returns><see langword="true"/> when the card actually moved.</returns> /// <returns><see langword="true"/> when the card actually moved.</returns>
public bool MoveCard(long cardId, long targetColumnId) public bool MoveCard(long cardId, long targetColumnId) {
{
using var command = CreateCommand( using var command = CreateCommand(
"UPDATE cards SET column_id = $columnId WHERE id = $id AND column_id <> $columnId;"); "UPDATE cards SET column_id = $columnId WHERE id = $id AND column_id <> $columnId;");
command.Parameters.AddWithValue("$columnId", targetColumnId); command.Parameters.AddWithValue("$columnId", targetColumnId);
@@ -323,18 +302,6 @@ public sealed class WorkspaceRepository : IDisposable
return command.ExecuteNonQuery() > 0; return command.ExecuteNonQuery() > 0;
} }
/// <summary>
/// Counts the cards of a column, regardless of any search filter.
/// </summary>
/// <param name="columnId">The column id.</param>
/// <returns>The number of cards in the column.</returns>
public long CountCards(long columnId)
{
using var command = CreateCommand("SELECT COUNT(*) FROM cards WHERE column_id = $id;");
command.Parameters.AddWithValue("$id", columnId);
return (long)command.ExecuteScalar()!;
}
/// <summary> /// <summary>
/// Deletes a card; the DDL cascade removes its tag links. /// Deletes a card; the DDL cascade removes its tag links.
/// </summary> /// </summary>
@@ -350,15 +317,13 @@ public sealed class WorkspaceRepository : IDisposable
/// Returns all tags ordered by id ascending; unreferenced tags are included. /// Returns all tags ordered by id ascending; unreferenced tags are included.
/// </summary> /// </summary>
/// <returns>All tags in id order.</returns> /// <returns>All tags in id order.</returns>
public IReadOnlyList<TagModel> GetTags() public IReadOnlyList<TagModel> GetTags() {
{
using var command = CreateCommand( using var command = CreateCommand(
"SELECT id, name, color, description FROM tags ORDER BY id ASC;"); "SELECT id, name, color, description FROM tags ORDER BY id ASC;");
using var reader = command.ExecuteReader(); using var reader = command.ExecuteReader();
var tags = new List<TagModel>(); var tags = new List<TagModel>();
while (reader.Read()) while (reader.Read()) {
{
tags.Add(ReadTag(reader, 0)); tags.Add(ReadTag(reader, 0));
} }
return tags; return tags;
@@ -368,8 +333,7 @@ public sealed class WorkspaceRepository : IDisposable
/// Returns every tag together with the number of cards using it, ordered by tag id. /// Returns every tag together with the number of cards using it, ordered by tag id.
/// </summary> /// </summary>
/// <returns>The tag/usage pairs in tag id order.</returns> /// <returns>The tag/usage pairs in tag id order.</returns>
public IReadOnlyList<(TagModel Tag, long UsageCount)> GetTagsWithUsage() public IReadOnlyList<(TagModel Tag, long UsageCount)> GetTagsWithUsage() {
{
using var command = CreateCommand(""" using var command = CreateCommand("""
SELECT t.id, t.name, t.color, t.description, COUNT(ct.card_id) SELECT t.id, t.name, t.color, t.description, COUNT(ct.card_id)
FROM tags t FROM tags t
@@ -380,8 +344,7 @@ public sealed class WorkspaceRepository : IDisposable
using var reader = command.ExecuteReader(); using var reader = command.ExecuteReader();
var tags = new List<(TagModel Tag, long UsageCount)>(); var tags = new List<(TagModel Tag, long UsageCount)>();
while (reader.Read()) while (reader.Read()) {
{
tags.Add((ReadTag(reader, 0), reader.GetInt64(4))); tags.Add((ReadTag(reader, 0), reader.GetInt64(4)));
} }
return tags; return tags;
@@ -394,14 +357,12 @@ public sealed class WorkspaceRepository : IDisposable
/// <param name="color">The tag color.</param> /// <param name="color">The tag color.</param>
/// <param name="description">The optional description.</param> /// <param name="description">The optional description.</param>
/// <returns>The created tag.</returns> /// <returns>The created tag.</returns>
/// <exception cref="NameRequiredException">The name is empty.</exception> /// <exception cref="SqliteException">The name is empty or not unique.</exception>
/// <exception cref="DuplicateNameException">The name is not unique.</exception> public TagModel AddTag(string name, RgbColor color, string description) {
public TagModel AddTag(string name, RgbColor color, string description)
{
using var transaction = _connection.BeginTransaction(); using var transaction = _connection.BeginTransaction();
long id = MapNameConstraint(NamedEntity.Tag, name, () => ExecuteInsert(transaction, long id = ExecuteInsert(transaction,
"INSERT INTO tags (name, color, description) VALUES ($name, $color, $description);", "INSERT INTO tags (name, color, description) VALUES ($name, $color, $description);",
("$name", name), ("$color", color.ToString()), ("$description", description))); ("$name", name), ("$color", color.ToString()), ("$description", description));
transaction.Commit(); transaction.Commit();
return new TagModel(id, name, color, description); return new TagModel(id, name, color, description);
@@ -416,16 +377,13 @@ public sealed class WorkspaceRepository : IDisposable
/// <param name="description">The new description.</param> /// <param name="description">The new description.</param>
/// <returns>The updated tag, or the unchanged one for a no-op.</returns> /// <returns>The updated tag, or the unchanged one for a no-op.</returns>
/// <exception cref="InvalidOperationException">The tag does not exist.</exception> /// <exception cref="InvalidOperationException">The tag does not exist.</exception>
/// <exception cref="NameRequiredException">The new name is empty.</exception> /// <exception cref="SqliteException">The new name is empty or not unique.</exception>
/// <exception cref="DuplicateNameException">The new name is not unique.</exception> public TagModel UpdateTag(long tagId, string name, RgbColor color, string description) {
public TagModel UpdateTag(long tagId, string name, RgbColor color, string description)
{
TagModel existing = GetTag(tagId) TagModel existing = GetTag(tagId)
?? throw new InvalidOperationException($"Tag {tagId} does not exist."); ?? throw new InvalidOperationException($"Tag {tagId} does not exist.");
// Unchanged name, color and description: no write. // Unchanged name, color and description: no write.
if (existing.Name == name && existing.Color == color && existing.Description == description) if (existing.Name == name && existing.Color == color && existing.Description == description) {
{
return existing; return existing;
} }
@@ -435,7 +393,7 @@ public sealed class WorkspaceRepository : IDisposable
command.Parameters.AddWithValue("$color", color.ToString()); command.Parameters.AddWithValue("$color", color.ToString());
command.Parameters.AddWithValue("$description", description); command.Parameters.AddWithValue("$description", description);
command.Parameters.AddWithValue("$id", tagId); command.Parameters.AddWithValue("$id", tagId);
MapNameConstraint(NamedEntity.Tag, name, command.ExecuteNonQuery); command.ExecuteNonQuery();
return new TagModel(tagId, name, color, description); return new TagModel(tagId, name, color, description);
} }
@@ -451,47 +409,12 @@ public sealed class WorkspaceRepository : IDisposable
#region Helpers #region Helpers
/// <summary>SQLite extended result code of a failed CHECK constraint.</summary>
private const int SqliteConstraintCheck = 275;
/// <summary>SQLite extended result code of a failed UNIQUE constraint.</summary>
private const int SqliteConstraintUnique = 2067;
/// <summary>
/// Runs a write against columns.title or tags.name and translates the
/// schema's non-empty (CHECK) and uniqueness (UNIQUE) violations into typed
/// exceptions that the UI maps to localized messages.
/// </summary>
/// <typeparam name="T">The write's result type.</typeparam>
/// <param name="entity">The entity being written.</param>
/// <param name="name">The name or title being written.</param>
/// <param name="write">The write to run.</param>
/// <returns>The write's result.</returns>
/// <exception cref="NameRequiredException">The name is empty.</exception>
/// <exception cref="DuplicateNameException">The name is not unique.</exception>
private static T MapNameConstraint<T>(NamedEntity entity, string name, Func<T> write)
{
try
{
return write();
}
catch (SqliteException exception) when (exception.SqliteExtendedErrorCode == SqliteConstraintCheck)
{
throw new NameRequiredException(entity, exception);
}
catch (SqliteException exception) when (exception.SqliteExtendedErrorCode == SqliteConstraintUnique)
{
throw new DuplicateNameException(entity, name, exception);
}
}
/// <summary> /// <summary>
/// Returns the tag with the given id. /// Returns the tag with the given id.
/// </summary> /// </summary>
/// <param name="tagId">The tag id.</param> /// <param name="tagId">The tag id.</param>
/// <returns>The tag, or <see langword="null"/> when it does not exist.</returns> /// <returns>The tag, or <see langword="null"/> when it does not exist.</returns>
private TagModel? GetTag(long tagId) private TagModel? GetTag(long tagId) {
{
using var command = CreateCommand( using var command = CreateCommand(
"SELECT id, name, color, description FROM tags WHERE id = $id;"); "SELECT id, name, color, description FROM tags WHERE id = $id;");
command.Parameters.AddWithValue("$id", tagId); command.Parameters.AddWithValue("$id", tagId);
@@ -504,8 +427,7 @@ public sealed class WorkspaceRepository : IDisposable
/// </summary> /// </summary>
/// <param name="cardId">The card id.</param> /// <param name="cardId">The card id.</param>
/// <returns>The assigned tags in id order.</returns> /// <returns>The assigned tags in id order.</returns>
private IReadOnlyList<TagModel> LoadTags(long cardId) private IReadOnlyList<TagModel> LoadTags(long cardId) {
{
using var command = CreateCommand(""" using var command = CreateCommand("""
SELECT t.id, t.name, t.color, t.description SELECT t.id, t.name, t.color, t.description
FROM tags t FROM tags t
@@ -517,8 +439,7 @@ public sealed class WorkspaceRepository : IDisposable
using var reader = command.ExecuteReader(); using var reader = command.ExecuteReader();
var tags = new List<TagModel>(); var tags = new List<TagModel>();
while (reader.Read()) while (reader.Read()) {
{
tags.Add(ReadTag(reader, 0)); tags.Add(ReadTag(reader, 0));
} }
return tags; return tags;
@@ -548,8 +469,7 @@ public sealed class WorkspaceRepository : IDisposable
/// <param name="sql">The command text.</param> /// <param name="sql">The command text.</param>
/// <param name="transaction">The transaction to enlist in, when any.</param> /// <param name="transaction">The transaction to enlist in, when any.</param>
/// <returns>The prepared command.</returns> /// <returns>The prepared command.</returns>
private SqliteCommand CreateCommand(string sql, SqliteTransaction? transaction = null) private SqliteCommand CreateCommand(string sql, SqliteTransaction? transaction = null) {
{
SqliteCommand command = _connection.CreateCommand(); SqliteCommand command = _connection.CreateCommand();
command.Transaction = transaction; command.Transaction = transaction;
command.CommandText = sql; command.CommandText = sql;
@@ -562,11 +482,9 @@ public sealed class WorkspaceRepository : IDisposable
/// <param name="transaction">The transaction to enlist in.</param> /// <param name="transaction">The transaction to enlist in.</param>
/// <param name="sql">The statement to execute.</param> /// <param name="sql">The statement to execute.</param>
/// <param name="parameters">Name/value pairs bound as SQL parameters.</param> /// <param name="parameters">Name/value pairs bound as SQL parameters.</param>
private void ExecuteNonQuery(SqliteTransaction transaction, string sql, params (string Name, object? Value)[] parameters) private void ExecuteNonQuery(SqliteTransaction transaction, string sql, params (string Name, object? Value)[] parameters) {
{
using SqliteCommand command = CreateCommand(sql, transaction); using SqliteCommand command = CreateCommand(sql, transaction);
foreach ((string name, object? value) in parameters) foreach ((string name, object? value) in parameters) {
{
command.Parameters.AddWithValue(name, value); command.Parameters.AddWithValue(name, value);
} }
command.ExecuteNonQuery(); command.ExecuteNonQuery();
@@ -579,8 +497,7 @@ public sealed class WorkspaceRepository : IDisposable
/// <param name="sql">The INSERT statement.</param> /// <param name="sql">The INSERT statement.</param>
/// <param name="parameters">Name/value pairs bound as SQL parameters.</param> /// <param name="parameters">Name/value pairs bound as SQL parameters.</param>
/// <returns>The rowid assigned to the inserted row.</returns> /// <returns>The rowid assigned to the inserted row.</returns>
private long ExecuteInsert(SqliteTransaction transaction, string sql, params (string Name, object? Value)[] parameters) private long ExecuteInsert(SqliteTransaction transaction, string sql, params (string Name, object? Value)[] parameters) {
{
ExecuteNonQuery(transaction, sql, parameters); ExecuteNonQuery(transaction, sql, parameters);
using SqliteCommand rowId = CreateCommand("SELECT last_insert_rowid();", transaction); using SqliteCommand rowId = CreateCommand("SELECT last_insert_rowid();", transaction);
return (long)rowId.ExecuteScalar()!; return (long)rowId.ExecuteScalar()!;
@@ -592,8 +509,7 @@ public sealed class WorkspaceRepository : IDisposable
/// <param name="sql">The DELETE statement with an <c>$id</c> parameter.</param> /// <param name="sql">The DELETE statement with an <c>$id</c> parameter.</param>
/// <param name="id">The id to delete.</param> /// <param name="id">The id to delete.</param>
/// <returns><see langword="true"/> when a row was deleted.</returns> /// <returns><see langword="true"/> when a row was deleted.</returns>
private bool ExecuteDelete(string sql, long id) private bool ExecuteDelete(string sql, long id) {
{
using SqliteCommand command = CreateCommand(sql); using SqliteCommand command = CreateCommand(sql);
command.Parameters.AddWithValue("$id", id); command.Parameters.AddWithValue("$id", id);
return command.ExecuteNonQuery() > 0; return command.ExecuteNonQuery() > 0;
+5 -13
View File
@@ -6,14 +6,8 @@ namespace YKanBan.Storage.Workspace;
/// assignments. Data validity is expressed in DDL (CHECK / UNIQUE / FOREIGN /// assignments. Data validity is expressed in DDL (CHECK / UNIQUE / FOREIGN
/// KEY) so every stored row is valid by construction, and cascading deletes /// KEY) so every stored row is valid by construction, and cascading deletes
/// are covered by the same DDL. /// are covered by the same DDL.
///
/// Title and name uniqueness is NOCASE (ASCII case folding) while the columns
/// themselves keep the default BINARY collation, so ordering by title stays
/// code-point based. Until the first release the v1 script may be edited in
/// place; after it, every schema change must be appended as a new migration.
/// </summary> /// </summary>
public static class WorkspaceSchema public static class WorkspaceSchema {
{
/// <summary> /// <summary>
/// Newest workspace schema version this build understands. /// Newest workspace schema version this build understands.
/// </summary> /// </summary>
@@ -27,11 +21,10 @@ public static class WorkspaceSchema
new SchemaMigration(CurrentVersion, "initial schema", """ new SchemaMigration(CurrentVersion, "initial schema", """
CREATE TABLE columns ( CREATE TABLE columns (
id INTEGER PRIMARY KEY AUTOINCREMENT, id INTEGER PRIMARY KEY AUTOINCREMENT,
title TEXT NOT NULL CHECK (length(title) > 0), title TEXT NOT NULL UNIQUE CHECK (length(title) > 0),
description TEXT NOT NULL DEFAULT '', description TEXT NOT NULL DEFAULT '',
created_at INTEGER NOT NULL, created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL, updated_at INTEGER NOT NULL
UNIQUE (title COLLATE NOCASE)
); );
CREATE TABLE cards ( CREATE TABLE cards (
@@ -45,10 +38,9 @@ public static class WorkspaceSchema
CREATE TABLE tags ( CREATE TABLE tags (
id INTEGER PRIMARY KEY AUTOINCREMENT, id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL CHECK (length(name) > 0), name TEXT NOT NULL UNIQUE CHECK (length(name) > 0),
color TEXT NOT NULL CHECK (color GLOB '#[0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f]'), color TEXT NOT NULL CHECK (color GLOB '#[0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f]'),
description TEXT NOT NULL DEFAULT '', description TEXT NOT NULL DEFAULT ''
UNIQUE (name COLLATE NOCASE)
); );
CREATE TABLE card_tags ( CREATE TABLE card_tags (
+52 -13
View File
@@ -7,8 +7,7 @@ namespace YKanBan.Storage.Workspace;
/// any database work happens. Disposing releases the repository and then the /// any database work happens. Disposing releases the repository and then the
/// lock. /// lock.
/// </summary> /// </summary>
public sealed class WorkspaceSession : IDisposable public sealed class WorkspaceSession : IDisposable {
{
private readonly WorkspaceLock _workspaceLock; private readonly WorkspaceLock _workspaceLock;
/// <summary> /// <summary>
@@ -17,8 +16,7 @@ public sealed class WorkspaceSession : IDisposable
/// <param name="folderPath">The canonical workspace folder path.</param> /// <param name="folderPath">The canonical workspace folder path.</param>
/// <param name="workspaceLock">The exclusive lock held while this session is open.</param> /// <param name="workspaceLock">The exclusive lock held while this session is open.</param>
/// <param name="repository">The data access object for this workspace.</param> /// <param name="repository">The data access object for this workspace.</param>
private WorkspaceSession(string folderPath, WorkspaceLock workspaceLock, WorkspaceRepository repository) private WorkspaceSession(string folderPath, WorkspaceLock workspaceLock, WorkspaceRepository repository) {
{
FolderPath = folderPath; FolderPath = folderPath;
_workspaceLock = workspaceLock; _workspaceLock = workspaceLock;
Repository = repository; Repository = repository;
@@ -40,17 +38,59 @@ public sealed class WorkspaceSession : IDisposable
/// <param name="folderPath">The workspace folder to open.</param> /// <param name="folderPath">The workspace folder to open.</param>
/// <returns>The opened session; dispose it to release the lock and connection.</returns> /// <returns>The opened session; dispose it to release the lock and connection.</returns>
/// <exception cref="WorkspaceNotInitializedException">The folder has no .ykanban structure.</exception> /// <exception cref="WorkspaceNotInitializedException">The folder has no .ykanban structure.</exception>
/// <exception cref="WorkspaceDatabaseMissingException">.ykanban exists but its database file does not.</exception>
/// <exception cref="WorkspaceLockException">Another instance already holds the lock.</exception> /// <exception cref="WorkspaceLockException">Another instance already holds the lock.</exception>
public static WorkspaceSession Open(string folderPath) public static WorkspaceSession Open(string folderPath) {
{
WorkspaceLock workspaceLock = WorkspaceLock.Acquire(folderPath); WorkspaceLock workspaceLock = WorkspaceLock.Acquire(folderPath);
try
{ // Opening would otherwise create an empty database and show an empty board as if nothing was lost.
string databasePath = WorkspacePaths.Database(folderPath);
if (!File.Exists(databasePath)) {
workspaceLock.Dispose();
throw new WorkspaceDatabaseMissingException(databasePath);
}
return OpenLocked(folderPath, workspaceLock);
}
/// <summary>
/// Initializes a workspace with its preset columns and tags, then opens it.
/// The lock is taken right after .ykanban is created and is never released in
/// between, so no other instance can interleave with the initialization.
/// </summary>
/// <param name="folderPath">The existing folder to initialize.</param>
/// <returns>The opened session; dispose it to release the lock and connection.</returns>
/// <exception cref="WorkspaceDirectoryMissingException">The folder does not exist on disk.</exception>
/// <exception cref="WorkspaceLockException">Another instance holds the workspace lock.</exception>
/// <exception cref="InvalidOperationException">The workspace database already exists.</exception>
public static WorkspaceSession Initialize(string folderPath) {
// .ykanban first: the lock file lives inside it. Taking the lock here,
// before any database work, keeps two instances from initializing the same
// folder at once; WorkspaceInitializer stays a lock-free functional class.
Directory.CreateDirectory(WorkspacePaths.Root(folderPath));
WorkspaceLock workspaceLock = WorkspaceLock.Acquire(folderPath);
try {
WorkspaceInitializer.Initialize(folderPath);
WorkspacePreset.AddPresetColumns(folderPath);
WorkspacePreset.AddPresetTags(folderPath);
return OpenLocked(folderPath, workspaceLock);
} catch {
workspaceLock.Dispose();
throw;
}
}
/// <summary>
/// Opens the repository under an already held lock; the lock is released if that fails.
/// </summary>
/// <param name="folderPath">The workspace folder.</param>
/// <param name="workspaceLock">The held workspace lock.</param>
/// <returns>The opened session.</returns>
private static WorkspaceSession OpenLocked(string folderPath, WorkspaceLock workspaceLock) {
try {
var repository = new WorkspaceRepository(folderPath); var repository = new WorkspaceRepository(folderPath);
return new WorkspaceSession(folderPath, workspaceLock, repository); return new WorkspaceSession(folderPath, workspaceLock, repository);
} } catch {
catch
{
workspaceLock.Dispose(); workspaceLock.Dispose();
throw; throw;
} }
@@ -59,8 +99,7 @@ public sealed class WorkspaceSession : IDisposable
/// <summary> /// <summary>
/// Releases the repository connection, then the exclusive lock. /// Releases the repository connection, then the exclusive lock.
/// </summary> /// </summary>
public void Dispose() public void Dispose() {
{
Repository.Dispose(); Repository.Dispose();
_workspaceLock.Dispose(); _workspaceLock.Dispose();
} }
+10 -8
View File
@@ -1,31 +1,33 @@
using System; using System;
using Avalonia.Controls; using Avalonia.Controls;
using Avalonia.Controls.Templates; using Avalonia.Controls.Templates;
using YKanBan.ViewModels; using YKanBan.ViewModels;
namespace YKanBan; namespace YKanBan;
public class ViewLocator : IDataTemplate public class ViewLocator : IDataTemplate {
{
public Control? Build(object? param) public Control? Build(object? param) {
{
if (param is null) if (param is null)
return null; return null;
var name = param.GetType().FullName!.Replace("ViewModel", "View", StringComparison.Ordinal); var name = param.GetType().FullName!.Replace("ViewModel", "View", StringComparison.Ordinal);
var type = Type.GetType(name); var type = Type.GetType(name);
if (type != null) if (type != null) {
{
return (Control)Activator.CreateInstance(type)!; return (Control)Activator.CreateInstance(type)!;
} }
// YYC MARK: the missing-view placeholder is a programmer error (a view
// model without its matching view), not a user-facing message. It must be
// caught by the code-behind convention test before release, so it is kept
// as a hard-coded English diagnostic and is deliberately not localized.
return new TextBlock { Text = "Not Found: " + name }; return new TextBlock { Text = "Not Found: " + name };
} }
public bool Match(object? data) public bool Match(object? data) {
{
return data is ViewModelBase; return data is ViewModelBase;
} }
} }
+264 -259
View File
@@ -1,338 +1,343 @@
using System.Collections.ObjectModel; using System.Collections.ObjectModel;
using System.Diagnostics;
using CommunityToolkit.Mvvm.ComponentModel; using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input; using CommunityToolkit.Mvvm.Input;
using YKanBan.Models; using YKanBan.Models;
using YKanBan.Search; using YKanBan.Search;
using YKanBan.Services;
using YKanBan.Storage.AppData; using YKanBan.Storage.AppData;
using YKanBan.Storage.Workspace; using YKanBan.Storage.Workspace;
using YKanBan.ViewModels.Dialogs;
namespace YKanBan.ViewModels.Board; namespace YKanBan.ViewModels.Board;
/// <summary> /// <summary>
/// The board tab: the toolbar (search bar, new column, column width, card sort) /// The board tab: a toolbar (search box, add-column and the Display button)
/// and the columns laid out left to right, each listing its cards top to bottom. /// over horizontally arranged columns of vertically stacked cards. All
/// /// persistence goes through the workspace repository; the board reloads from it
/// The search runs only on an explicit search (button or Enter), never while /// after each change.
/// typing. An invalid expression is reported in a message dialog and changes
/// nothing: the box keeps its text and the board keeps the previous result.
///
/// Every write is followed by <see cref="Refresh"/>, which re-queries with the
/// most recently successful search expression (<see cref="ActiveFilter"/>), not
/// with whatever the search box currently holds: cards that no longer match
/// disappear, new cards that do not match are not shown, and empty columns stay.
/// </summary> /// </summary>
public sealed partial class BoardViewModel : ViewModelBase public sealed partial class BoardViewModel : ViewModelBase {
{ private readonly AppServices _services;
private readonly WorkspaceRepository _repository; private readonly WorkspaceRepository _repository;
private readonly AppConfig _config;
private readonly IDialogService _dialogs; // The active search result filter, or null when the whole board is shown.
private IReadOnlyCollection<long>? _matchedCardIds;
/// <summary> /// <summary>
/// Initializes the board and loads it. /// Initializes the board, loading its current content.
/// </summary> /// </summary>
/// <param name="repository">The workspace repository.</param> /// <param name="services">The process composition root (configuration access).</param>
/// <param name="config">The live application configuration (sort, column width, confirmations).</param> /// <param name="session">The open workspace session.</param>
/// <param name="dialogs">The modal dialog service.</param> public BoardViewModel(AppServices services, WorkspaceSession session) {
public BoardViewModel(WorkspaceRepository repository, AppConfig config, IDialogService dialogs) _services = services;
{ _repository = session.Repository;
_repository = repository; Display = new DisplaySettingsViewModel(_services.Config, Reload);
_config = config;
_dialogs = dialogs;
SortOptions = Reload();
[
new OptionItem(CardSortOption.Id, Resources.Sort_Id),
new OptionItem(CardSortOption.UpdatedAt, Resources.Sort_UpdatedAt),
new OptionItem(CardSortOption.Title, Resources.Sort_Title),
];
selectedSort = SortOptions.FirstOrDefault(option => (CardSortOption)option.Value == config.Sort.Card)
?? SortOptions[0];
columnWidth = ColumnWidths.Resolve(config.ColumnWidth);
Refresh();
} }
/// <summary> /// <summary>
/// Raised after every board write (the refresh included), so the tags tab /// Gets the workspace repository used for all board data access.
/// can update its usage counts.
/// </summary> /// </summary>
public event EventHandler? DataWritten; public WorkspaceRepository Repository => _repository;
/// <summary> /// <summary>
/// Gets the columns in id order. /// Gets the live application configuration.
/// </summary>
public AppConfig Config => _services.Config;
/// <summary>
/// Gets the display options (column width, card sort, column sort).
/// </summary>
public DisplaySettingsViewModel Display { get; }
/// <summary>
/// Gets the columns shown by the board, in display order.
/// </summary> /// </summary>
public ObservableCollection<ColumnViewModel> Columns { get; } = []; public ObservableCollection<ColumnViewModel> Columns { get; } = [];
/// <summary> /// <summary>
/// Gets the card sort options shown in the combobox. /// Gets or sets the search box text. The board does not filter on change;
/// </summary> /// the search runs only when the search button is used.
public IReadOnlyList<OptionItem> SortOptions { get; }
/// <summary>
/// Gets the column models in id order, as of the last refresh.
/// </summary>
public IReadOnlyList<ColumnModel> ColumnModels { get; private set; } = [];
/// <summary>
/// Gets or sets the most recently successful search; <see langword="null"/> shows every card.
/// </summary>
public CompiledSearch? ActiveFilter { get; set; }
/// <summary>
/// Gets or sets the search box text; it only takes effect on <see cref="SearchCommand"/>.
/// </summary> /// </summary>
[ObservableProperty] [ObservableProperty]
[NotifyPropertyChangedFor(nameof(HasSearchText))] private string searchText = string.Empty;
private string searchText = "";
/// <summary> /// <summary>
/// Gets whether the search box holds text (shows the clear button). /// Gets the rendered column width in pixels, applied globally.
/// </summary>
public bool HasSearchText => SearchText.Length > 0;
/// <summary>
/// Gets or sets the selected card sort option; changing it is persisted and re-sorts the board.
/// </summary> /// </summary>
[ObservableProperty] [ObservableProperty]
private OptionItem selectedSort; private double columnWidth;
/// <summary> /// <summary>
/// Gets the effective column width in pixels. /// Gets a value indicating whether a search filter is currently applied.
/// </summary> /// </summary>
[ObservableProperty] public bool IsFiltering => _matchedCardIds is not null;
private int columnWidth;
/// <summary> /// <summary>
/// Reloads the columns and the cards matching <see cref="ActiveFilter"/>. /// Gets the localized filter status text shown as the status icon tooltip.
/// </summary> /// </summary>
public void Refresh() public string FilterStatusText => IsFiltering ? Resources.Board_FilterActive : Resources.Board_FilterInactive;
{
IReadOnlyList<ColumnModel> columns = _repository.GetColumns();
ILookup<long, CardModel> cardsByColumn = _repository.GetCards(ActiveFilter).ToLookup(card => card.ColumnId);
var sort = (CardSortOption)SelectedSort.Value;
ColumnModels = columns;
Columns.Clear();
foreach (ColumnModel column in columns)
{
Columns.Add(new ColumnViewModel(this, column, CardOrdering.Sort(cardsByColumn[column.Id], sort)));
}
}
/// <summary> /// <summary>
/// Parses and runs the search box text; blank text shows every card. An /// Gets the status icon opacity: full while filtering, dimmed otherwise.
/// invalid expression only shows the error dialog. /// </summary>
public double FilterIconOpacity => IsFiltering ? 1.0 : 0.4;
/// <summary>
/// Gets a value indicating whether the board has any columns.
/// </summary>
public bool HasColumns => Columns.Count > 0;
/// <summary>
/// Gets a value indicating whether the board is empty.
/// </summary>
public bool HasNoColumns => Columns.Count == 0;
#region Interactions
/// <summary>
/// Gets the interaction that opens the new-column editor.
/// </summary>
public Interaction<Unit> AddColumn { get; } = new();
/// <summary>
/// Gets the interaction that opens the column editor.
/// </summary>
public Interaction<ColumnViewModel> EditColumn { get; } = new();
/// <summary>
/// Gets the interaction that confirms and deletes a column.
/// </summary>
public Interaction<ColumnViewModel> DeleteColumn { get; } = new();
/// <summary>
/// Gets the interaction that opens the new-card editor.
/// </summary>
public Interaction<ColumnViewModel> AddCard { get; } = new();
/// <summary>
/// Gets the interaction that opens the card editor.
/// </summary>
public Interaction<CardViewModel> EditCard { get; } = new();
/// <summary>
/// Gets the interaction that confirms and deletes a card.
/// </summary>
public Interaction<CardViewModel> DeleteCard { get; } = new();
/// <summary>
/// Gets the interaction that opens the move-card dialog.
/// </summary>
public Interaction<CardViewModel> MoveCard { get; } = new();
/// <summary>
/// Gets the interaction that shows the search error dialog, carrying the English parser detail.
/// </summary>
public Interaction<string> ShowSearchError { get; } = new();
#endregion
#region Commands
/// <summary>
/// Opens the new-column editor.
/// </summary> /// </summary>
/// <returns>A task completing after the refresh or the error dialog.</returns>
[RelayCommand] [RelayCommand]
private async Task SearchAsync() private Task AddNewColumnAsync() => AddColumn.Handle(Unit.Value);
{
CompiledSearch? filter; /// <summary>
try /// Runs the current search. A blank query shows everything; an invalid
{ /// expression opens the error dialog and keeps the previous results and text.
/// </summary>
[RelayCommand]
private async Task SearchAsync() {
if (string.IsNullOrWhiteSpace(SearchText)) {
ApplyFilter(null);
return;
}
try {
SearchNode? query = SearchQueryParser.Parse(SearchText); SearchNode? query = SearchQueryParser.Parse(SearchText);
filter = query is null ? null : SearchSqlCompiler.Compile(query); if (query is null) {
} ApplyFilter(null);
catch (SearchSyntaxException exception)
{
await _dialogs.ShowMessageAsync(
Resources.Search_Error_Title,
string.Format(Resources.Culture, Resources.Search_Error_Message, exception.Message));
return; return;
} }
ActiveFilter = filter; CompiledSearch compiled = SearchSqlCompiler.Compile(query);
Refresh(); ApplyFilter(_repository.GetCardIdsMatching(compiled));
} catch (SearchSyntaxException exception) {
// The error dialog carries the parser's non-localized English detail.
await ShowSearchError.Handle(exception.Message);
}
} }
/// <summary> /// <summary>
/// Empties the search box and shows every card again. /// Clears the search box and restores the unfiltered board.
/// </summary> /// </summary>
[RelayCommand] [RelayCommand]
private void ClearSearch() private void ClearSearch() {
{ SearchText = string.Empty;
SearchText = ""; ApplyFilter(null);
ActiveFilter = null;
Refresh();
} }
/// <summary> /// <summary>
/// Opens the new-column dialog. /// Applies a new result filter (null clears it) and rebuilds the board when it changed.
/// </summary> /// </summary>
/// <returns>A task completing when the dialog closes.</returns> /// <param name="matchedIds">The new filter, or <see langword="null"/> for no filter.</param>
[RelayCommand] private void ApplyFilter(IReadOnlyCollection<long>? matchedIds) {
private async Task AddColumnAsync() if (_matchedCardIds is null && matchedIds is null) {
{
var dialog = new ColumnEditorDialogViewModel(null, (title, description) => _repository.AddColumn(title, description));
if (await _dialogs.ShowAsync(dialog))
{
RefreshAfterWrite();
}
}
/// <summary>
/// Opens the column width dialog and applies the choice.
/// </summary>
/// <returns>A task completing when the dialog closes.</returns>
[RelayCommand]
private async Task AdjustColumnWidthAsync()
{
if (await _dialogs.ShowAsync(new ColumnWidthDialogViewModel(_config.ColumnWidth)))
{
ColumnWidth = ColumnWidths.Resolve(_config.ColumnWidth);
}
}
/// <summary>
/// Opens the edit-column dialog.
/// </summary>
/// <param name="column">The column to edit.</param>
/// <returns>A task completing when the dialog closes.</returns>
internal async Task EditColumnAsync(ColumnModel column)
{
var dialog = new ColumnEditorDialogViewModel(
column, (title, description) => _repository.UpdateColumn(column.Id, title, description));
if (await _dialogs.ShowAsync(dialog))
{
RefreshAfterWrite();
}
}
/// <summary>
/// Deletes a column with its cards, asking first when that confirmation is enabled.
/// </summary>
/// <param name="column">The column to delete.</param>
/// <returns>A task completing when the column is deleted or the deletion was declined.</returns>
internal async Task DeleteColumnAsync(ColumnModel column)
{
await RunWriteAsync(async () =>
{
if (_config.Confirmations.DeleteColumn)
{
long count = _repository.CountCards(column.Id);
string message = string.Format(Resources.Culture, Resources.Confirm_DeleteColumn, column.Title, count);
if (!await _dialogs.ConfirmAsync(message, Resources.Common_Delete))
{
return false;
}
}
_repository.DeleteColumn(column.Id);
return true;
});
}
/// <summary>
/// Opens the card editor for a new card in a column.
/// </summary>
/// <param name="columnId">The column receiving the card.</param>
/// <returns>A task completing when the editor closes.</returns>
internal async Task AddCardAsync(long columnId)
{
var editor = CardEditorDialogViewModel.ForNewCard(
_repository, _dialogs, columnId, _config.Confirmations.DiscardEdit);
await _dialogs.ShowAsync(editor);
// Refresh even after a cancel: the nested picker may have created tags.
RefreshAfterWrite();
}
/// <summary>
/// Opens the card editor for an existing card, reloaded from the database.
/// </summary>
/// <param name="cardId">The card to edit.</param>
/// <returns>A task completing when the editor closes.</returns>
internal async Task EditCardAsync(long cardId)
{
CardModel? card = _repository.GetCard(cardId);
if (card is null)
{
Refresh();
return; return;
} }
var editor = CardEditorDialogViewModel.ForExistingCard( _matchedCardIds = matchedIds;
_repository, _dialogs, card, _config.Confirmations.DiscardEdit); OnPropertyChanged(nameof(IsFiltering));
await _dialogs.ShowAsync(editor); OnPropertyChanged(nameof(FilterStatusText));
RefreshAfterWrite(); OnPropertyChanged(nameof(FilterIconOpacity));
Reload();
} }
#endregion
#region Requests from columns and cards
/// <summary> /// <summary>
/// Deletes a card, asking first when that confirmation is enabled. /// Requests the new-card editor for the given column.
/// </summary>
/// <param name="column">The target column.</param>
/// <returns>A task completing after the editor closes.</returns>
public Task RequestAddCardAsync(ColumnViewModel column) => AddCard.Handle(column);
/// <summary>
/// Requests the editor for the given card.
/// </summary>
/// <param name="card">The card to edit.</param>
/// <returns>A task completing after the editor closes.</returns>
public Task RequestEditCardAsync(CardViewModel card) => EditCard.Handle(card);
/// <summary>
/// Requests deletion of the given card.
/// </summary> /// </summary>
/// <param name="card">The card to delete.</param> /// <param name="card">The card to delete.</param>
/// <returns>A task completing when the card is deleted or the deletion was declined.</returns> /// <returns>A task completing after confirmation.</returns>
internal async Task DeleteCardAsync(CardModel card) public Task RequestDeleteCardAsync(CardViewModel card) => DeleteCard.Handle(card);
{
await RunWriteAsync(async () => /// <summary>
{ /// Requests moving the given card to another column.
if (_config.Confirmations.DeleteCard) /// </summary>
{ /// <param name="card">The card to move.</param>
string message = string.Format(Resources.Culture, Resources.Confirm_DeleteCard, CardViewModel.FormatHeader(card)); /// <returns>A task completing after the move.</returns>
if (!await _dialogs.ConfirmAsync(message, Resources.Common_Delete)) public Task RequestMoveCardAsync(CardViewModel card) => MoveCard.Handle(card);
{
return false; /// <summary>
/// Requests the editor for the given column.
/// </summary>
/// <param name="column">The column to edit.</param>
/// <returns>A task completing after the editor closes.</returns>
public Task RequestEditColumnAsync(ColumnViewModel column) => EditColumn.Handle(column);
/// <summary>
/// Requests deletion of the given column.
/// </summary>
/// <param name="column">The column to delete.</param>
/// <returns>A task completing after confirmation.</returns>
public Task RequestDeleteColumnAsync(ColumnViewModel column) => DeleteColumn.Handle(column);
#endregion
#region Loading and ordering
/// <summary>
/// Reloads all columns and cards from the repository and rebuilds the board.
/// </summary>
public void Reload() {
IReadOnlyList<ColumnModel> columns = _repository.GetColumns();
IReadOnlyList<CardModel> cards = _repository.GetCards();
// An active search hides non-matching cards while every column stays visible.
if (_matchedCardIds is not null) {
cards = cards.Where(card => _matchedCardIds.Contains(card.Id)).ToList();
} }
// Group cards by column once so each column can be built independently.
Dictionary<long, List<CardModel>> cardsByColumn = cards
.GroupBy(card => card.ColumnId)
.ToDictionary(group => group.Key, group => group.ToList());
IEnumerable<ColumnModel> orderedColumns = SortColumns(columns, _services.Config.Display.ColumnSort);
Columns.Clear();
foreach (ColumnModel column in orderedColumns) {
// Cards are sorted within their column by the selected card order.
IEnumerable<CardModel> columnCards = cardsByColumn.TryGetValue(column.Id, out List<CardModel>? list)
? SortCards(list, _services.Config.Display.CardSort)
: [];
Columns.Add(new ColumnViewModel(this, column, columnCards.Select(card => new CardViewModel(this, card))));
} }
_repository.DeleteCard(card.Id);
return true; ApplyColumnWidth();
}); OnPropertyChanged(nameof(HasColumns));
OnPropertyChanged(nameof(HasNoColumns));
} }
/// <summary> /// <summary>
/// Moves a card to another column. /// Recomputes the global column width and pushes it to every column.
/// </summary> /// </summary>
/// <param name="cardId">The card to move.</param> public void ApplyColumnWidth() {
/// <param name="columnId">The target column.</param> ColumnWidth = ColumnWidthPixels(_services.Config.Display.ColumnWidth);
/// <returns>A task completing when the card is moved.</returns> foreach (ColumnViewModel column in Columns) {
internal Task MoveCardAsync(long cardId, long columnId) => column.Width = ColumnWidth;
RunWriteAsync(() =>
{
_repository.MoveCard(cardId, columnId);
return Task.FromResult(true);
});
/// <summary>
/// Runs an immediate write and refreshes after it; an unexpected failure is
/// reported in a message dialog and the board is refreshed to the stored state.
/// </summary>
/// <param name="write">The write; returns <see langword="false"/> when the user declined it.</param>
/// <returns>A task completing after the refresh.</returns>
private async Task RunWriteAsync(Func<Task<bool>> write)
{
try
{
if (!await write())
{
return;
} }
} }
catch (Exception exception)
{
Debug.WriteLine(exception);
await _dialogs.ShowMessageAsync(
Resources.Error_Operation_Title, Resources.Error_Operation_Message, exception.Message);
}
RefreshAfterWrite();
}
/// <summary> /// <summary>
/// Refreshes after a write and announces it. /// Resolves a column width setting to its pixel value.
/// </summary> /// </summary>
private void RefreshAfterWrite() /// <param name="settings">The configured column width.</param>
{ /// <returns>The width in pixels.</returns>
Refresh(); public static double ColumnWidthPixels(ColumnWidthSettings settings) => settings.Preset switch {
DataWritten?.Invoke(this, EventArgs.Empty); ColumnWidthPreset.Narrow => 240,
} ColumnWidthPreset.Wide => 480,
ColumnWidthPreset.Custom => settings.CustomPixels,
_ => 320,
};
/// <summary> /// <summary>
/// Persists the sort option and re-sorts the board. /// Orders cards by the selected option, tie-breaking by id ascending.
/// </summary> /// </summary>
/// <param name="value">The new sort option.</param> /// <param name="cards">The cards to order.</param>
partial void OnSelectedSortChanged(OptionItem value) /// <param name="option">The selected order.</param>
{ /// <returns>The ordered cards.</returns>
_config.Sort.Card = (CardSortOption)value.Value; private static IEnumerable<CardModel> SortCards(IEnumerable<CardModel> cards, SortOption option) => option switch {
Refresh(); SortOption.IdAscending => cards.OrderBy(card => card.Id),
} SortOption.IdDescending => cards.OrderByDescending(card => card.Id),
SortOption.CreatedAscending => cards.OrderBy(card => card.CreatedAt).ThenBy(card => card.Id),
SortOption.CreatedDescending => cards.OrderByDescending(card => card.CreatedAt).ThenBy(card => card.Id),
SortOption.UpdatedAscending => cards.OrderBy(card => card.UpdatedAt).ThenBy(card => card.Id),
SortOption.UpdatedDescending => cards.OrderByDescending(card => card.UpdatedAt).ThenBy(card => card.Id),
SortOption.TitleAscending => cards.OrderBy(card => card.Title, StringComparer.Ordinal).ThenBy(card => card.Id),
SortOption.TitleDescending => cards.OrderByDescending(card => card.Title, StringComparer.Ordinal).ThenBy(card => card.Id),
_ => cards.OrderBy(card => card.Id),
};
/// <summary>
/// Orders columns by the selected option, tie-breaking by id ascending.
/// </summary>
/// <param name="columns">The columns to order.</param>
/// <param name="option">The selected order.</param>
/// <returns>The ordered columns.</returns>
private static IEnumerable<ColumnModel> SortColumns(IEnumerable<ColumnModel> columns, SortOption option) => option switch {
SortOption.IdAscending => columns.OrderBy(column => column.Id),
SortOption.IdDescending => columns.OrderByDescending(column => column.Id),
SortOption.CreatedAscending => columns.OrderBy(column => column.CreatedAt).ThenBy(column => column.Id),
SortOption.CreatedDescending => columns.OrderByDescending(column => column.CreatedAt).ThenBy(column => column.Id),
SortOption.UpdatedAscending => columns.OrderBy(column => column.UpdatedAt).ThenBy(column => column.Id),
SortOption.UpdatedDescending => columns.OrderByDescending(column => column.UpdatedAt).ThenBy(column => column.Id),
SortOption.TitleAscending => columns.OrderBy(column => column.Title, StringComparer.Ordinal).ThenBy(column => column.Id),
SortOption.TitleDescending => columns.OrderByDescending(column => column.Title, StringComparer.Ordinal).ThenBy(column => column.Id),
_ => columns.OrderBy(column => column.Id),
};
#endregion
} }
+67 -82
View File
@@ -1,141 +1,126 @@
using System.Globalization;
using CommunityToolkit.Mvvm.Input; using CommunityToolkit.Mvvm.Input;
using YKanBan.Models; using YKanBan.Models;
namespace YKanBan.ViewModels.Board; namespace YKanBan.ViewModels.Board;
/// <summary> /// <summary>
/// One card in a column list: "#id" in bold on the same line as the title, the /// One card on the board. Clicking the card body opens the editor; the corner
/// content cut to a fixed length, and the tag badges below. No timestamps. /// menu offers delete and move. The shown text is the "#id title" heading, a
/// Clicking the card opens the editor; its menu deletes or moves it. /// truncated content preview and the colored tag badges; timestamps are not
/// shown on the board.
/// </summary> /// </summary>
public sealed partial class CardViewModel : ViewModelBase public sealed partial class CardViewModel : ViewModelBase {
{
/// <summary> /// <summary>
/// The number of text elements of content shown on the card. /// Maximum number of content characters shown in the card preview.
/// </summary> /// </summary>
public const int ExcerptLength = 200; private const int PreviewLength = 200;
/// <summary>
/// Maximum number of explicit content lines shown in the card preview.
/// </summary>
private const int PreviewMaxLines = 10;
private readonly BoardViewModel _board; private readonly BoardViewModel _board;
/// <summary> /// <summary>
/// Initializes the card. /// Initializes the card view from its model.
/// </summary> /// </summary>
/// <param name="board">The owning board.</param> /// <param name="board">The owning board view model.</param>
/// <param name="card">The card shown.</param> /// <param name="card">The card model to display.</param>
public CardViewModel(BoardViewModel board, CardModel card) public CardViewModel(BoardViewModel board, CardModel card) {
{
_board = board; _board = board;
Card = card; Model = card;
IdText = $"#{card.Id.ToString(CultureInfo.InvariantCulture)}"; TagBadges = card.Tags.Select(tag => new TagBadgeViewModel(tag)).ToList();
Excerpt = MakeExcerpt(card.Content);
Tags = card.Tags.Select(tag => new TagBadgeViewModel(tag)).ToList();
} }
/// <summary> /// <summary>
/// Gets the card shown. /// Gets the underlying card model.
/// </summary> /// </summary>
public CardModel Card { get; } public CardModel Model { get; }
/// <summary> /// <summary>
/// Gets the "#id" text. /// Gets the card id.
/// </summary> /// </summary>
public string IdText { get; } public long Id => Model.Id;
/// <summary> /// <summary>
/// Gets the title; empty when the card has none. /// Gets the owning column id.
/// </summary> /// </summary>
public string Title => Card.Title; public long ColumnId => Model.ColumnId;
/// <summary> /// <summary>
/// Gets the title as it follows "#id" on the header line: a space and the /// Gets the tag badges shown under the content.
/// title, or nothing when the card has no title.
/// </summary> /// </summary>
public string TitleSuffix => Card.Title.Length == 0 ? "" : " " + Card.Title; public IReadOnlyList<TagBadgeViewModel> TagBadges { get; }
/// <summary> /// <summary>
/// Gets the truncated content. /// Gets the bold id marker, for example "#61".
/// </summary> /// </summary>
public string Excerpt { get; } public string IdText => $"#{Model.Id}";
/// <summary> /// <summary>
/// Gets whether there is content to show. /// Gets the card title, empty when the card has no title.
/// </summary> /// </summary>
public bool HasExcerpt => Excerpt.Length > 0; public string TitleText => Model.Title;
/// <summary> /// <summary>
/// Gets the tag badges. /// Gets a value indicating whether the card has a title to show.
/// </summary> /// </summary>
public IReadOnlyList<TagBadgeViewModel> Tags { get; } public bool HasTitle => Model.Title.Length > 0;
/// <summary> /// <summary>
/// Gets whether the card has tags. /// Gets a value indicating whether the card has content to preview.
/// </summary> /// </summary>
public bool HasTags => Tags.Count > 0; public bool HasContent => Model.Content.Length > 0;
/// <summary> /// <summary>
/// Gets the "move to column" targets; built when the menu asks for them. /// Gets the content preview, truncated to at most 200 characters and
/// The card's current column is listed but disabled. /// 10 explicit lines, with an ellipsis when anything was cut.
/// </summary> /// </summary>
public IReadOnlyList<MoveTargetViewModel> MoveTargets => // YYC MARK: the preview is truncated here instead of in the view because
_board.ColumnModels // both a character cap and an explicit-line cap are needed, and because
.Select(column => new MoveTargetViewModel(column.Title, column.Id != Card.ColumnId, MoveToCommand, column.Id)) // Avalonia 11.3.x renders no ellipsis when MaxLines clips wrapped text
.ToList(); // (fixed upstream in 12.1.2, PR #22017, never backported). Revisit after
// upgrading Avalonia.
public string PreviewContent {
get {
string content = Model.Content;
/// <summary> // Cut at whichever boundary comes first: 200 characters or the 10th line break.
/// Formats the "#id title" header text of a card ("#id" alone without a title). int limit = content.Length;
/// </summary> int breaks = 0;
/// <param name="card">The card.</param> for (int i = 0; i < content.Length; i++) {
/// <returns>The header text.</returns> if (i == PreviewLength || (content[i] == '\n' && ++breaks == PreviewMaxLines)) {
public static string FormatHeader(CardModel card) => limit = i;
card.Title.Length == 0 break;
? $"#{card.Id.ToString(CultureInfo.InvariantCulture)}"
: $"#{card.Id.ToString(CultureInfo.InvariantCulture)} {card.Title}";
/// <summary>
/// Cuts content to <see cref="ExcerptLength"/> text elements, appending an
/// ellipsis when something was cut. Surrogate pairs and combining sequences
/// are never split.
/// </summary>
/// <param name="content">The card content.</param>
/// <returns>The excerpt.</returns>
public static string MakeExcerpt(string content)
{
string trimmed = content.Trim();
var info = new StringInfo(trimmed);
return info.LengthInTextElements <= ExcerptLength
? trimmed
: info.SubstringByTextElements(0, ExcerptLength).TrimEnd() + "…";
} }
}
return limit < content.Length ? content[..limit] + "…" : content;
}
}
/// <summary>
/// Gets a value indicating whether the card has any tags.
/// </summary>
public bool HasTags => TagBadges.Count > 0;
/// <summary> /// <summary>
/// Opens the card editor. /// Opens the card editor.
/// </summary> /// </summary>
/// <returns>A task completing when the editor closes.</returns>
[RelayCommand] [RelayCommand]
private Task EditAsync() => _board.EditCardAsync(Card.Id); private void Edit() => _ = _board.RequestEditCardAsync(this);
/// <summary> /// <summary>
/// Deletes the card. /// Asks the board to delete this card.
/// </summary> /// </summary>
/// <returns>A task completing when the card is deleted or the deletion was declined.</returns>
[RelayCommand] [RelayCommand]
private Task DeleteAsync() => _board.DeleteCardAsync(Card); private void Delete() => _ = _board.RequestDeleteCardAsync(this);
/// <summary> /// <summary>
/// Moves the card to another column. /// Asks the board to move this card to another column.
/// </summary> /// </summary>
/// <param name="columnId">The target column.</param>
/// <returns>A task completing when the card is moved.</returns>
[RelayCommand] [RelayCommand]
private Task MoveToAsync(long columnId) => _board.MoveCardAsync(Card.Id, columnId); private void Move() => _ = _board.RequestMoveCardAsync(this);
} }
/// <summary>
/// An entry of a card's "move to column" submenu.
/// </summary>
/// <param name="Title">The column title.</param>
/// <param name="IsEnabled">Whether the entry can be picked (false for the card's own column).</param>
/// <param name="Command">The move command.</param>
/// <param name="ColumnId">The target column, passed to <paramref name="Command"/>.</param>
public sealed record MoveTargetViewModel(string Title, bool IsEnabled, IAsyncRelayCommand<long> Command, long ColumnId);
+43 -31
View File
@@ -1,77 +1,89 @@
using System.Collections.ObjectModel;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input; using CommunityToolkit.Mvvm.Input;
using YKanBan.Models; using YKanBan.Models;
namespace YKanBan.ViewModels.Board; namespace YKanBan.ViewModels.Board;
/// <summary> /// <summary>
/// One board column: its header (title, card count, description, the new-card /// One board column: a header with its title, card count and actions, plus the
/// button and the edit/delete menu) and its virtualized card list. /// vertically stacked cards.
/// </summary> /// </summary>
public sealed partial class ColumnViewModel : ViewModelBase public sealed partial class ColumnViewModel : ViewModelBase {
{
private readonly BoardViewModel _board; private readonly BoardViewModel _board;
/// <summary> /// <summary>
/// Initializes the column. /// Initializes the column view from its model and cards.
/// </summary> /// </summary>
/// <param name="board">The owning board.</param> /// <param name="board">The owning board view model.</param>
/// <param name="column">The column shown.</param> /// <param name="column">The column model.</param>
/// <param name="cards">The column's visible cards, in display order.</param> /// <param name="cards">The already sorted cards belonging to this column.</param>
public ColumnViewModel(BoardViewModel board, ColumnModel column, IReadOnlyList<CardModel> cards) public ColumnViewModel(BoardViewModel board, ColumnModel column, IEnumerable<CardViewModel> cards) {
{
_board = board; _board = board;
Column = column; Model = column;
Cards = cards.Select(card => new CardViewModel(board, card)).ToList(); Cards = new ObservableCollection<CardViewModel>(cards);
width = board.ColumnWidth;
} }
/// <summary> /// <summary>
/// Gets the column shown. /// Gets the underlying column model.
/// </summary> /// </summary>
public ColumnModel Column { get; } public ColumnModel Model { get; }
/// <summary>
/// Gets the column id.
/// </summary>
public long Id => Model.Id;
/// <summary> /// <summary>
/// Gets the column title. /// Gets the column title.
/// </summary> /// </summary>
public string Title => Column.Title; public string Title => Model.Title;
/// <summary> /// <summary>
/// Gets the column description. /// Gets the column description.
/// </summary> /// </summary>
public string Description => Column.Description; public string Description => Model.Description;
/// <summary> /// <summary>
/// Gets whether the column has a description to show. /// Gets the cards in this column, already in display order.
/// </summary> /// </summary>
public bool HasDescription => Column.Description.Length > 0; public ObservableCollection<CardViewModel> Cards { get; }
/// <summary> /// <summary>
/// Gets the number of visible cards. /// Gets the number of cards in this column.
/// </summary> /// </summary>
public int CardCount => Cards.Count; public int CardCount => Cards.Count;
/// <summary> /// <summary>
/// Gets the visible cards in display order. /// Gets the tooltip text: the column description when present, otherwise
/// <see langword="null"/> so no tooltip is shown.
/// </summary> /// </summary>
public IReadOnlyList<CardViewModel> Cards { get; } public string? ToolTipText => Model.Description.Length > 0 ? Model.Description : null;
/// <summary> /// <summary>
/// Opens the card editor for a new card in this column. /// Gets or sets the rendered column width in pixels, applied globally.
/// </summary> /// </summary>
/// <returns>A task completing when the editor closes.</returns> [ObservableProperty]
[RelayCommand] private double width;
private Task AddCardAsync() => _board.AddCardAsync(Column.Id);
/// <summary> /// <summary>
/// Opens the edit-column dialog. /// Opens the editor for a new card in this column.
/// </summary> /// </summary>
/// <returns>A task completing when the dialog closes.</returns>
[RelayCommand] [RelayCommand]
private Task EditAsync() => _board.EditColumnAsync(Column); private void AddCard() => _ = _board.RequestAddCardAsync(this);
/// <summary> /// <summary>
/// Deletes the column with its cards. /// Opens the editor for this column.
/// </summary> /// </summary>
/// <returns>A task completing when the column is deleted or the deletion was declined.</returns>
[RelayCommand] [RelayCommand]
private Task DeleteAsync() => _board.DeleteColumnAsync(Column); private void Edit() => _ = _board.RequestEditColumnAsync(this);
/// <summary>
/// Asks the board to delete this column.
/// </summary>
[RelayCommand]
private void Delete() => _ = _board.RequestDeleteColumnAsync(this);
} }
@@ -0,0 +1,164 @@
using CommunityToolkit.Mvvm.ComponentModel;
using YKanBan.Storage.AppData;
namespace YKanBan.ViewModels.Board;
/// <summary>
/// The board display options shown in the Display flyout: the global column
/// width and the separate card and column orderings. Every change writes to
/// the configuration and asks the board to refresh immediately.
/// </summary>
public sealed partial class DisplaySettingsViewModel : ViewModelBase {
/// <summary>
/// Smallest accepted manual width.
/// </summary>
public const int MinimumPixels = 160;
/// <summary>
/// Largest accepted manual width.
/// </summary>
public const int MaximumPixels = 720;
private readonly AppConfig _config;
private readonly Action _refresh;
/// <summary>
/// Initializes the display options from the configuration.
/// </summary>
/// <param name="config">The live application configuration.</param>
/// <param name="refresh">Invoked after every change to refresh the board.</param>
public DisplaySettingsViewModel(AppConfig config, Action refresh) {
_config = config;
_refresh = refresh;
Presets =
[
new OptionItem(ColumnWidthPreset.Narrow, Resources.WidthPreset_Narrow),
new OptionItem(ColumnWidthPreset.Standard, Resources.WidthPreset_Standard),
new OptionItem(ColumnWidthPreset.Wide, Resources.WidthPreset_Wide),
new OptionItem(ColumnWidthPreset.Custom, Resources.WidthPreset_Custom),
];
SortOptions = BuildSortOptions();
selectedPreset = Presets.FirstOrDefault(option => (ColumnWidthPreset)option.Value == config.Display.ColumnWidth.Preset)
?? Presets[1];
customPixels = config.Display.ColumnWidth.CustomPixels;
selectedCardSort = FindSort(SortOptions, config.Display.CardSort);
selectedColumnSort = FindSort(SortOptions, config.Display.ColumnSort);
}
/// <summary>
/// Gets the width preset choices.
/// </summary>
public IReadOnlyList<OptionItem> Presets { get; }
/// <summary>
/// Gets the ordering choices (shared by cards and columns).
/// </summary>
public IReadOnlyList<OptionItem> SortOptions { get; }
/// <summary>
/// Gets or sets the selected width preset.
/// </summary>
[ObservableProperty]
private OptionItem? selectedPreset;
/// <summary>
/// Gets or sets the manual pixel width used by the custom preset.
/// </summary>
[ObservableProperty]
private decimal? customPixels;
/// <summary>
/// Gets or sets the selected card order.
/// </summary>
[ObservableProperty]
private OptionItem? selectedCardSort;
/// <summary>
/// Gets or sets the selected column order.
/// </summary>
[ObservableProperty]
private OptionItem? selectedColumnSort;
/// <summary>
/// Gets a value indicating whether the custom preset is selected.
/// </summary>
public bool IsCustom => SelectedPreset is not null && (ColumnWidthPreset)SelectedPreset.Value == ColumnWidthPreset.Custom;
/// <summary>
/// Stores the width preset and refreshes the board.
/// </summary>
/// <param name="value">The new selection.</param>
partial void OnSelectedPresetChanged(OptionItem? value) {
OnPropertyChanged(nameof(IsCustom));
if (value is not null) {
_config.Display.ColumnWidth.Preset = (ColumnWidthPreset)value.Value;
_refresh();
}
}
/// <summary>
/// Stores the manual width and refreshes the board when the custom preset is active.
/// </summary>
/// <param name="value">The new pixel count.</param>
partial void OnCustomPixelsChanged(decimal? value) {
if (value is null) {
return;
}
int pixels = (int)value.Value;
_config.Display.ColumnWidth.CustomPixels = pixels;
if (IsCustom) {
_refresh();
}
}
/// <summary>
/// Stores the card order and refreshes the board.
/// </summary>
/// <param name="value">The new selection.</param>
partial void OnSelectedCardSortChanged(OptionItem? value) {
if (value is not null) {
_config.Display.CardSort = (SortOption)value.Value;
_refresh();
}
}
/// <summary>
/// Stores the column order and refreshes the board.
/// </summary>
/// <param name="value">The new selection.</param>
partial void OnSelectedColumnSortChanged(OptionItem? value) {
if (value is not null) {
_config.Display.ColumnSort = (SortOption)value.Value;
_refresh();
}
}
/// <summary>
/// Builds the localized eight-way ordering option list.
/// </summary>
/// <returns>The ordering options.</returns>
private static IReadOnlyList<OptionItem> BuildSortOptions() =>
[
new OptionItem(SortOption.IdAscending, Resources.Sort_IdAsc),
new OptionItem(SortOption.IdDescending, Resources.Sort_IdDesc),
new OptionItem(SortOption.CreatedAscending, Resources.Sort_CreatedAsc),
new OptionItem(SortOption.CreatedDescending, Resources.Sort_CreatedDesc),
new OptionItem(SortOption.UpdatedAscending, Resources.Sort_UpdatedAsc),
new OptionItem(SortOption.UpdatedDescending, Resources.Sort_UpdatedDesc),
new OptionItem(SortOption.TitleAscending, Resources.Sort_TitleAsc),
new OptionItem(SortOption.TitleDescending, Resources.Sort_TitleDesc),
];
/// <summary>
/// Finds the option matching a stored sort value.
/// </summary>
/// <param name="options">The option list.</param>
/// <param name="value">The stored value.</param>
/// <returns>The matching option, or the first option.</returns>
private static OptionItem FindSort(IReadOnlyList<OptionItem> options, SortOption value) =>
options.FirstOrDefault(option => (SortOption)option.Value == value) ?? options[0];
}
+26 -23
View File
@@ -1,57 +1,60 @@
using Avalonia.Media; using Avalonia.Media;
using Avalonia.Media.Immutable;
using YKanBan.Models; using YKanBan.Models;
namespace YKanBan.ViewModels.Board; namespace YKanBan.ViewModels.Board;
/// <summary> /// <summary>
/// A colored tag badge (color + name). Tag colors are user data: they are shown /// A read-only colored tag badge shown on a card: the tag name over a
/// as the literal #RRGGBB value in both themes, with a black or white text color /// background taken directly from the tag color (user data, never themed) and
/// chosen for contrast. /// an automatically contrasting text color.
/// </summary> /// </summary>
public sealed class TagBadgeViewModel : ViewModelBase public sealed class TagBadgeViewModel {
{
/// <summary> /// <summary>
/// Initializes the badge. /// Initializes a badge from a tag.
/// </summary> /// </summary>
/// <param name="tag">The tag shown.</param> /// <param name="tag">The tag to render.</param>
public TagBadgeViewModel(TagModel tag) public TagBadgeViewModel(TagModel tag) {
{
Tag = tag; Tag = tag;
Background = new ImmutableSolidColorBrush(Color.FromRgb(tag.Color.R, tag.Color.G, tag.Color.B)); Name = tag.Name;
Foreground = IsLight(tag.Color) ? Brushes.Black : Brushes.White; Color background = Color.FromRgb(tag.Color.R, tag.Color.G, tag.Color.B);
Background = new SolidColorBrush(background);
Foreground = new SolidColorBrush(ContrastingTextColor(background));
} }
/// <summary> /// <summary>
/// Gets the tag shown. /// Gets the underlying tag model.
/// </summary> /// </summary>
public TagModel Tag { get; } public TagModel Tag { get; }
/// <summary> /// <summary>
/// Gets the tag name. /// Gets the tag name.
/// </summary> /// </summary>
public string Name => Tag.Name; public string Name { get; }
/// <summary> /// <summary>
/// Gets the tag description. /// Gets the tooltip text: the tag description when present, otherwise
/// <see langword="null"/> so no tooltip is shown.
/// </summary> /// </summary>
public string Description => Tag.Description; public string? ToolTipText => Tag.Description.Length > 0 ? Tag.Description : null;
/// <summary> /// <summary>
/// Gets the badge fill: the tag's own color. /// Gets the badge background brush.
/// </summary> /// </summary>
public IBrush Background { get; } public IBrush Background { get; }
/// <summary> /// <summary>
/// Gets the text color contrasting with <see cref="Background"/>. /// Gets the badge text brush.
/// </summary> /// </summary>
public IBrush Foreground { get; } public IBrush Foreground { get; }
/// <summary> /// <summary>
/// Decides whether dark text reads better on a color, by its relative luminance. /// Picks black or white text for readability against the given background.
/// </summary> /// </summary>
/// <param name="color">The background color.</param> /// <param name="background">The badge background color.</param>
/// <returns><see langword="true"/> for light colors.</returns> /// <returns>The contrasting text color.</returns>
public static bool IsLight(RgbColor color) => private static Color ContrastingTextColor(Color background) {
(0.299 * color.R) + (0.587 * color.G) + (0.114 * color.B) > 150; double luminance = (0.299 * background.R + 0.587 * background.G + 0.114 * background.B) / 255.0;
return luminance > 0.6 ? Colors.Black : Colors.White;
}
} }
@@ -5,13 +5,11 @@ namespace YKanBan.ViewModels.Dialogs;
/// <summary> /// <summary>
/// The about dialog: application name, version, repository link and license. /// The about dialog: application name, version, repository link and license.
/// </summary> /// </summary>
public sealed class AboutDialogViewModel : ViewModelBase public sealed class AboutDialogViewModel : ViewModelBase {
{
/// <summary> /// <summary>
/// Initializes the view model, reading the version from the assembly. /// Initializes the view model, reading the version from the assembly.
/// </summary> /// </summary>
public AboutDialogViewModel() public AboutDialogViewModel() {
{
string version = typeof(AboutDialogViewModel).Assembly.GetName().Version?.ToString(3) ?? "0.0.0"; string version = typeof(AboutDialogViewModel).Assembly.GetName().Version?.ToString(3) ?? "0.0.0";
Version = string.Format( Version = string.Format(
Resources.Culture ?? CultureInfo.CurrentCulture, Resources.About_Version, version); Resources.Culture ?? CultureInfo.CurrentCulture, Resources.About_Version, version);
@@ -30,7 +28,7 @@ public sealed class AboutDialogViewModel : ViewModelBase
/// <summary> /// <summary>
/// Gets the repository URL. /// Gets the repository URL.
/// </summary> /// </summary>
public string RepositoryUrl => "https://code.blumia.cn/yyc12345/YKanBan"; public string RepositoryUrl => "https://github.com/yyc12345/YKanBan";
/// <summary> /// <summary>
/// Gets the license name. /// Gets the license name.
@@ -0,0 +1,55 @@
using Avalonia.Media;
using CommunityToolkit.Mvvm.Input;
using YKanBan.Models;
using YKanBan.ViewModels.Board;
namespace YKanBan.ViewModels.Dialogs;
/// <summary>
/// One tag assigned to the card being edited, shown with a colored badge and a
/// remove action that only changes the in-memory assignment (the actual write
/// happens on confirm).
/// </summary>
public sealed partial class AssignedTagViewModel {
private readonly CardEditorViewModel _editor;
private readonly TagBadgeViewModel _badge;
/// <summary>
/// Initializes the assigned-tag row.
/// </summary>
/// <param name="editor">The owning card editor.</param>
/// <param name="tag">The assigned tag.</param>
public AssignedTagViewModel(CardEditorViewModel editor, TagModel tag) {
_editor = editor;
Tag = tag;
_badge = new TagBadgeViewModel(tag);
}
/// <summary>
/// Gets the assigned tag model.
/// </summary>
public TagModel Tag { get; }
/// <summary>
/// Gets the tag name.
/// </summary>
public string Name => _badge.Name;
/// <summary>
/// Gets the badge background brush.
/// </summary>
public IBrush Background => _badge.Background;
/// <summary>
/// Gets the badge text brush.
/// </summary>
public IBrush Foreground => _badge.Foreground;
/// <summary>
/// Removes this tag from the in-memory assignment.
/// </summary>
[RelayCommand]
private void Remove() => _editor.RemoveTag(Tag);
}
@@ -1,228 +0,0 @@
using System.Collections.ObjectModel;
using System.Globalization;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using YKanBan.Models;
using YKanBan.Storage.Workspace;
using YKanBan.ViewModels.Board;
namespace YKanBan.ViewModels.Dialogs;
/// <summary>
/// The card editor — one unit of work. Title, content and the tag assignment
/// are edited in memory and written together in a single transaction on
/// confirmation; cancelling writes nothing about the card or its assignment.
/// Confirming an existing card without effective changes writes nothing and
/// keeps its timestamps. The only immediate write is the creation of a new tag
/// in the nested tag picker (see <see cref="TagPickerDialogViewModel"/>).
/// </summary>
public sealed partial class CardEditorDialogViewModel : DialogViewModelBase
{
private readonly WorkspaceRepository _repository;
private readonly IDialogService _dialogs;
private readonly CardModel? _existing;
private readonly long _columnId;
private readonly bool _confirmDiscard;
private readonly string _initialTitle;
private readonly string _initialContent;
private readonly HashSet<long> _initialTagIds;
/// <summary>
/// Initializes the editor for a new card in a column.
/// </summary>
/// <param name="repository">The workspace repository.</param>
/// <param name="dialogs">The dialog service, for the nested tag picker and the discard confirmation.</param>
/// <param name="columnId">The column receiving the new card.</param>
/// <param name="confirmDiscard">Whether discarding changes asks for confirmation.</param>
/// <returns>The editor.</returns>
public static CardEditorDialogViewModel ForNewCard(
WorkspaceRepository repository, IDialogService dialogs, long columnId, bool confirmDiscard) =>
new(repository, dialogs, null, columnId, confirmDiscard);
/// <summary>
/// Initializes the editor for an existing card.
/// </summary>
/// <param name="repository">The workspace repository.</param>
/// <param name="dialogs">The dialog service, for the nested tag picker and the discard confirmation.</param>
/// <param name="card">The card to edit.</param>
/// <param name="confirmDiscard">Whether discarding changes asks for confirmation.</param>
/// <returns>The editor.</returns>
public static CardEditorDialogViewModel ForExistingCard(
WorkspaceRepository repository, IDialogService dialogs, CardModel card, bool confirmDiscard) =>
new(repository, dialogs, card, card.ColumnId, confirmDiscard);
private CardEditorDialogViewModel(
WorkspaceRepository repository, IDialogService dialogs, CardModel? existing, long columnId, bool confirmDiscard)
{
_repository = repository;
_dialogs = dialogs;
_existing = existing;
_columnId = columnId;
_confirmDiscard = confirmDiscard;
_initialTitle = existing?.Title ?? "";
_initialContent = existing?.Content ?? "";
_initialTagIds = existing?.Tags.Select(tag => tag.Id).ToHashSet() ?? [];
cardTitle = _initialTitle;
content = _initialContent;
Tags = new ObservableCollection<TagBadgeViewModel>(
existing?.Tags.Select(tag => new TagBadgeViewModel(tag)) ?? []);
if (existing is null)
{
Title = Resources.CardEditor_TitleNew;
}
else
{
CultureInfo? culture = Resources.Culture;
Title = Resources.CardEditor_TitleEdit;
IdText = $"#{existing.Id.ToString(CultureInfo.InvariantCulture)}";
CreatedText = string.Format(culture, Resources.CardEditor_Created, FormatTime(existing.CreatedAt));
ModifiedText = string.Format(culture, Resources.CardEditor_Modified, FormatTime(existing.UpdatedAt));
}
}
/// <summary>
/// Gets the localized window title.
/// </summary>
public string Title { get; }
/// <summary>
/// Gets whether the card already exists (and thus has an id and timestamps to show).
/// </summary>
public bool IsExisting => _existing is not null;
/// <summary>
/// Gets the read-only "#id" text of an existing card.
/// </summary>
public string? IdText { get; }
/// <summary>
/// Gets the read-only creation time line of an existing card.
/// </summary>
public string? CreatedText { get; }
/// <summary>
/// Gets the read-only modification time line of an existing card.
/// </summary>
public string? ModifiedText { get; }
/// <summary>
/// Gets the tags assigned in this edit session, in assignment order.
/// </summary>
public ObservableCollection<TagBadgeViewModel> Tags { get; }
/// <summary>
/// Gets the card written on confirmation; <see langword="null"/> until then.
/// </summary>
public CardModel? SavedCard { get; private set; }
/// <summary>
/// Gets or sets the card title; the empty string means "no title".
/// </summary>
[ObservableProperty]
private string cardTitle;
/// <summary>
/// Gets or sets the multiline card content.
/// </summary>
[ObservableProperty]
private string content;
/// <summary>
/// Gets the localized error of the last confirmation, or <see langword="null"/>.
/// </summary>
[ObservableProperty]
[NotifyPropertyChangedFor(nameof(HasError))]
private string? errorMessage;
/// <summary>
/// Gets whether an error is shown.
/// </summary>
public bool HasError => ErrorMessage is not null;
/// <summary>
/// Gets whether the in-memory state differs from the state the editor opened with.
/// </summary>
public bool IsDirty =>
CardTitle != _initialTitle
|| Content != _initialContent
|| !_initialTagIds.SetEquals(Tags.Select(tag => tag.Tag.Id));
/// <summary>
/// Opens the nested tag picker and assigns the picked (or newly created) tag.
/// </summary>
/// <returns>A task completing when the picker closes.</returns>
[RelayCommand]
private async Task AddTagAsync()
{
var picker = new TagPickerDialogViewModel(_repository, Tags.Select(tag => tag.Tag.Id).ToHashSet());
if (await _dialogs.ShowAsync(picker) && picker.PickedTag is { } picked)
{
Tags.Add(new TagBadgeViewModel(picked));
}
}
/// <summary>
/// Removes a tag from the in-memory assignment.
/// </summary>
/// <param name="tag">The tag to remove.</param>
[RelayCommand]
private void RemoveTag(TagBadgeViewModel tag) => Tags.Remove(tag);
/// <summary>
/// Writes the card in one transaction and closes; an unchanged existing card
/// is not written at all.
/// </summary>
[RelayCommand]
private void Confirm()
{
if (_existing is not null && !IsDirty)
{
SavedCard = _existing;
Close(true);
return;
}
long[] tagIds = Tags.Select(tag => tag.Tag.Id).ToArray();
try
{
SavedCard = _existing is null
? _repository.AddCard(_columnId, CardTitle, Content, tagIds)
: _repository.UpdateCard(_existing.Id, CardTitle, Content, tagIds);
}
catch (Exception exception)
{
ErrorMessage = WriteErrorMessages.Describe(exception);
return;
}
Close(true);
}
/// <summary>
/// Closes without writing the card, asking first when there are unsaved
/// changes and the discard confirmation is enabled.
/// </summary>
[RelayCommand]
private Task CancelAsync() => RequestCancelAsync();
/// <inheritdoc/>
public override async Task RequestCancelAsync()
{
if (_confirmDiscard && IsDirty
&& !await _dialogs.ConfirmAsync(Resources.Confirm_DiscardEdit, Resources.Common_Discard))
{
return;
}
Close(false);
}
/// <summary>
/// Formats a Unix-seconds timestamp in local time with the language's pattern.
/// </summary>
/// <param name="unixSeconds">The timestamp.</param>
/// <returns>The formatted time.</returns>
private static string FormatTime(long unixSeconds) =>
DateTimeOffset.FromUnixTimeSeconds(unixSeconds).ToLocalTime()
.ToString(Resources.Common_TimePattern, Resources.Culture);
}
@@ -0,0 +1,181 @@
using System.Collections.ObjectModel;
using System.Globalization;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using Microsoft.Data.Sqlite;
using YKanBan.Models;
using YKanBan.Storage.Workspace;
namespace YKanBan.ViewModels.Dialogs;
/// <summary>
/// The add/edit card dialog: title, content and the assigned-tag area, plus
/// read-only id and timestamps for an existing card. The confirm writes the
/// card and its tag assignment as one unit; a confirm with no effective change
/// writes nothing; cancelling never writes.
/// </summary>
public sealed partial class CardEditorViewModel : ViewModelBase {
private readonly WorkspaceRepository _repository;
private readonly long _columnId;
private readonly CardModel? _existing;
/// <summary>
/// Initializes the dialog for a new or existing card.
/// </summary>
/// <param name="repository">The workspace repository.</param>
/// <param name="columnId">The owning column (used when adding).</param>
/// <param name="existing">The card to edit, or <see langword="null"/> to add one.</param>
public CardEditorViewModel(WorkspaceRepository repository, long columnId, CardModel? existing) {
_repository = repository;
_columnId = columnId;
_existing = existing;
title = existing?.Title ?? string.Empty;
content = existing?.Content ?? string.Empty;
AssignedTags = new ObservableCollection<AssignedTagViewModel>(
(existing?.Tags ?? []).Select(tag => new AssignedTagViewModel(this, tag)));
if (existing is not null) {
IdLine = string.Format(Culture, Resources.CardDialog_Id, $"#{existing.Id}");
CreatedLine = string.Format(Culture, Resources.CardDialog_Created, FormatTime(existing.CreatedAt));
ModifiedLine = string.Format(Culture, Resources.CardDialog_Modified, FormatTime(existing.UpdatedAt));
}
}
/// <summary>
/// Gets the interaction that opens the nested tag picker.
/// </summary>
public Interaction<Unit, TagModel?> ShowTagPicker { get; } = new();
/// <summary>
/// Gets the workspace repository (used by the tag picker).
/// </summary>
public WorkspaceRepository Repository => _repository;
/// <summary>
/// Gets a value indicating whether this dialog creates a new card.
/// </summary>
public bool IsNew => _existing is null;
/// <summary>
/// Gets the localized window title.
/// </summary>
public string WindowTitle => IsNew ? Resources.CardDialog_AddTitle : Resources.CardDialog_EditTitle;
/// <summary>
/// Gets the read-only id line, empty for a new card.
/// </summary>
public string IdLine { get; } = string.Empty;
/// <summary>
/// Gets the read-only created line, empty for a new card.
/// </summary>
public string CreatedLine { get; } = string.Empty;
/// <summary>
/// Gets the read-only modified line, empty for a new card.
/// </summary>
public string ModifiedLine { get; } = string.Empty;
/// <summary>
/// Gets the tags currently assigned to the card (in memory until confirmed).
/// </summary>
public ObservableCollection<AssignedTagViewModel> AssignedTags { get; }
/// <summary>
/// Gets or sets the card title.
/// </summary>
[ObservableProperty]
private string title;
/// <summary>
/// Gets or sets the card content.
/// </summary>
[ObservableProperty]
private string content;
/// <summary>
/// Gets or sets the inline error shown when the write fails.
/// </summary>
[ObservableProperty]
private string? errorMessage;
/// <summary>
/// Gets a value indicating whether there are unsaved effective changes.
/// </summary>
public bool HasChanges {
get {
if (_existing is null) {
return Title.Length > 0 || Content.Length > 0 || AssignedTags.Count > 0;
}
bool tagsChanged = !AssignedTags.Select(row => row.Tag.Id).ToHashSet()
.SetEquals(_existing.Tags.Select(tag => tag.Id));
return _existing.Title != Title || _existing.Content != Content || tagsChanged;
}
}
/// <summary>
/// Opens the nested tag picker and adds the chosen tag when it is new to the card.
/// </summary>
[RelayCommand]
private async Task AddTagAsync() {
TagModel? tag = await ShowTagPicker.Handle(Unit.Value);
if (tag is not null && AssignedTags.All(row => row.Tag.Id != tag.Id)) {
AssignedTags.Add(new AssignedTagViewModel(this, tag));
}
}
/// <summary>
/// Removes a tag from the in-memory assignment.
/// </summary>
/// <param name="tag">The tag to remove.</param>
public void RemoveTag(TagModel tag) {
AssignedTagViewModel? row = AssignedTags.FirstOrDefault(item => item.Tag.Id == tag.Id);
if (row is not null) {
AssignedTags.Remove(row);
}
}
/// <summary>
/// Writes the card and its tags when there is an effective change.
/// </summary>
/// <returns><see langword="true"/> when the dialog may close.</returns>
public bool TryAccept() {
ErrorMessage = null;
// A confirm with no effective change writes nothing and just closes.
if (!HasChanges) {
return true;
}
try {
IReadOnlyCollection<long> tagIds = AssignedTags.Select(row => row.Tag.Id).ToList();
if (_existing is null) {
_repository.AddCard(_columnId, Title, Content, tagIds);
} else {
_repository.UpdateCard(_existing.Id, Title, Content, tagIds);
}
return true;
} catch (SqliteException) {
ErrorMessage = Resources.CardDialog_Error;
return false;
}
}
/// <summary>
/// Gets the culture used for formatted read-only lines.
/// </summary>
private static CultureInfo Culture => Resources.Culture ?? CultureInfo.CurrentCulture;
/// <summary>
/// Formats a stored timestamp as a local time using the UI language pattern.
/// </summary>
/// <param name="unixSeconds">The stored timestamp.</param>
/// <returns>The formatted local time.</returns>
private static string FormatTime(long unixSeconds) =>
DateTimeOffset.FromUnixTimeSeconds(unixSeconds).ToLocalTime().ToString(Resources.CardDialog_TimePattern, Culture);
}
@@ -1,82 +0,0 @@
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using YKanBan.Models;
namespace YKanBan.ViewModels.Dialogs;
/// <summary>
/// The new-column / edit-column dialog: a required title and an optional
/// description. Confirming writes through the supplied save callback; a
/// schema-constraint violation (empty or duplicate title) is shown inside the
/// dialog, which stays open with the user's input intact.
/// </summary>
public sealed partial class ColumnEditorDialogViewModel : DialogViewModelBase
{
private readonly Action<string, string> _save;
/// <summary>
/// Initializes the dialog.
/// </summary>
/// <param name="existing">The column being edited, or <see langword="null"/> for a new column.</param>
/// <param name="save">Writes the title and description; throws the repository's typed exceptions.</param>
public ColumnEditorDialogViewModel(ColumnModel? existing, Action<string, string> save)
{
_save = save;
Title = existing is null ? Resources.ColumnEditor_TitleNew : Resources.ColumnEditor_TitleEdit;
columnTitle = existing?.Title ?? "";
description = existing?.Description ?? "";
}
/// <summary>
/// Gets the localized window title.
/// </summary>
public string Title { get; }
/// <summary>
/// Gets or sets the column title being edited (not trimmed).
/// </summary>
[ObservableProperty]
private string columnTitle;
/// <summary>
/// Gets or sets the column description being edited.
/// </summary>
[ObservableProperty]
private string description;
/// <summary>
/// Gets the localized constraint error of the last confirmation, or <see langword="null"/>.
/// </summary>
[ObservableProperty]
[NotifyPropertyChangedFor(nameof(HasError))]
private string? errorMessage;
/// <summary>
/// Gets whether an error is shown.
/// </summary>
public bool HasError => ErrorMessage is not null;
/// <summary>
/// Writes the column; closes on success, otherwise shows the constraint error.
/// </summary>
[RelayCommand]
private void Confirm()
{
try
{
_save(ColumnTitle, Description);
}
catch (Exception exception)
{
ErrorMessage = WriteErrorMessages.Describe(exception);
return;
}
Close(true);
}
/// <summary>
/// Closes without writing.
/// </summary>
[RelayCommand]
private Task CancelAsync() => RequestCancelAsync();
}
@@ -0,0 +1,78 @@
using CommunityToolkit.Mvvm.ComponentModel;
using Microsoft.Data.Sqlite;
using YKanBan.Models;
using YKanBan.Storage.Workspace;
namespace YKanBan.ViewModels.Dialogs;
/// <summary>
/// The add/edit column dialog: a required title and an optional description.
/// The write happens when the dialog is accepted; a duplicate or empty title
/// keeps the dialog open with an inline error.
/// </summary>
public sealed partial class ColumnEditorViewModel : ViewModelBase {
private readonly WorkspaceRepository _repository;
private readonly ColumnModel? _existing;
/// <summary>
/// Initializes the dialog for a new or existing column.
/// </summary>
/// <param name="repository">The workspace repository.</param>
/// <param name="existing">The column to edit, or <see langword="null"/> to add one.</param>
public ColumnEditorViewModel(WorkspaceRepository repository, ColumnModel? existing) {
_repository = repository;
_existing = existing;
title = existing?.Title ?? string.Empty;
description = existing?.Description ?? string.Empty;
}
/// <summary>
/// Gets a value indicating whether this dialog creates a new column.
/// </summary>
public bool IsNew => _existing is null;
/// <summary>
/// Gets the localized window title.
/// </summary>
public string WindowTitle => IsNew ? Resources.ColumnDialog_AddTitle : Resources.ColumnDialog_EditTitle;
/// <summary>
/// Gets or sets the column title.
/// </summary>
[ObservableProperty]
private string title;
/// <summary>
/// Gets or sets the column description.
/// </summary>
[ObservableProperty]
private string description;
/// <summary>
/// Gets or sets the inline error shown when the title is rejected.
/// </summary>
[ObservableProperty]
private string? errorMessage;
/// <summary>
/// Writes the column when accepted.
/// </summary>
/// <returns><see langword="true"/> when the dialog may close.</returns>
public bool TryAccept() {
ErrorMessage = null;
try {
if (_existing is null) {
_repository.AddColumn(Title, Description);
} else {
_repository.UpdateColumn(_existing.Id, Title, Description);
}
return true;
} catch (SqliteException) {
ErrorMessage = Resources.ColumnDialog_InvalidTitle;
return false;
}
}
}
@@ -1,129 +0,0 @@
using System.Globalization;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using YKanBan.Storage.AppData;
namespace YKanBan.ViewModels.Dialogs;
/// <summary>
/// The column width dialog: one of the narrow / standard / wide presets or a
/// manual pixel width (160–720). The choice is global and is committed to the
/// live configuration on confirmation only.
/// </summary>
public sealed partial class ColumnWidthDialogViewModel : DialogViewModelBase
{
private readonly ColumnWidthSettings _settings;
/// <summary>
/// Initializes the dialog from the live settings.
/// </summary>
/// <param name="settings">The live column width settings.</param>
public ColumnWidthDialogViewModel(ColumnWidthSettings settings)
{
_settings = settings;
CultureInfo? culture = Resources.Culture;
NarrowLabel = string.Format(culture, Resources.ColumnWidth_Narrow, ColumnWidths.Narrow);
StandardLabel = string.Format(culture, Resources.ColumnWidth_Standard, ColumnWidths.Standard);
WideLabel = string.Format(culture, Resources.ColumnWidth_Wide, ColumnWidths.Wide);
RangeLabel = string.Format(culture, Resources.ColumnWidth_Range, AppConfig.MinColumnPixels, AppConfig.MaxColumnPixels);
isNarrow = settings.Preset == ColumnWidthPreset.Narrow;
isStandard = settings.Preset == ColumnWidthPreset.Standard;
isWide = settings.Preset == ColumnWidthPreset.Wide;
isCustom = settings.Preset == ColumnWidthPreset.Custom;
customPixels = settings.CustomPixels;
}
/// <summary>Gets the localized narrow preset label.</summary>
public string NarrowLabel { get; }
/// <summary>Gets the localized standard preset label.</summary>
public string StandardLabel { get; }
/// <summary>Gets the localized wide preset label.</summary>
public string WideLabel { get; }
/// <summary>Gets the localized accepted pixel range.</summary>
public string RangeLabel { get; }
/// <summary>Gets the smallest accepted custom width.</summary>
public int MinPixels => AppConfig.MinColumnPixels;
/// <summary>Gets the largest accepted custom width.</summary>
public int MaxPixels => AppConfig.MaxColumnPixels;
/// <summary>Gets or sets whether the narrow preset is selected.</summary>
[ObservableProperty]
private bool isNarrow;
/// <summary>Gets or sets whether the standard preset is selected.</summary>
[ObservableProperty]
private bool isStandard;
/// <summary>Gets or sets whether the wide preset is selected.</summary>
[ObservableProperty]
private bool isWide;
/// <summary>Gets or sets whether the manual width is selected.</summary>
[ObservableProperty]
private bool isCustom;
/// <summary>Gets or sets the manual width in pixels; <see langword="null"/> while the box is empty.</summary>
[ObservableProperty]
private decimal? customPixels;
/// <summary>
/// Commits the selection to the live settings and closes.
/// </summary>
[RelayCommand]
private void Confirm()
{
if (IsCustom)
{
int pixels = (int)Math.Clamp(CustomPixels ?? _settings.CustomPixels, AppConfig.MinColumnPixels, AppConfig.MaxColumnPixels);
_settings.Preset = ColumnWidthPreset.Custom;
_settings.CustomPixels = pixels;
}
else
{
_settings.Preset = IsNarrow ? ColumnWidthPreset.Narrow
: IsWide ? ColumnWidthPreset.Wide
: ColumnWidthPreset.Standard;
}
Close(true);
}
/// <summary>
/// Closes without changing anything.
/// </summary>
[RelayCommand]
private Task CancelAsync() => RequestCancelAsync();
}
/// <summary>
/// Pixel widths of the column width presets.
/// </summary>
public static class ColumnWidths
{
/// <summary>The narrow preset width.</summary>
public const int Narrow = 240;
/// <summary>The standard (default) preset width.</summary>
public const int Standard = 320;
/// <summary>The wide preset width.</summary>
public const int Wide = 480;
/// <summary>
/// Resolves the effective column width of the settings.
/// </summary>
/// <param name="settings">The column width settings.</param>
/// <returns>The width in pixels.</returns>
public static int Resolve(ColumnWidthSettings settings) => settings.Preset switch
{
ColumnWidthPreset.Narrow => Narrow,
ColumnWidthPreset.Wide => Wide,
ColumnWidthPreset.Custom => Math.Clamp(settings.CustomPixels, AppConfig.MinColumnPixels, AppConfig.MaxColumnPixels),
_ => Standard,
};
}
@@ -1,43 +0,0 @@
using CommunityToolkit.Mvvm.Input;
namespace YKanBan.ViewModels.Dialogs;
/// <summary>
/// A yes/no confirmation: a message, a confirming button with an action
/// specific label (for example "Delete") and a cancel button.
/// </summary>
public sealed partial class ConfirmDialogViewModel : DialogViewModelBase
{
/// <summary>
/// Initializes the confirmation.
/// </summary>
/// <param name="message">The localized question.</param>
/// <param name="confirmLabel">The localized label of the confirming button.</param>
public ConfirmDialogViewModel(string message, string confirmLabel)
{
Message = message;
ConfirmLabel = confirmLabel;
}
/// <summary>
/// Gets the localized question.
/// </summary>
public string Message { get; }
/// <summary>
/// Gets the localized label of the confirming button.
/// </summary>
public string ConfirmLabel { get; }
/// <summary>
/// Closes with a positive result.
/// </summary>
[RelayCommand]
private void Confirm() => Close(true);
/// <summary>
/// Closes with a negative result.
/// </summary>
[RelayCommand]
private Task CancelAsync() => RequestCancelAsync();
}
@@ -0,0 +1,24 @@
using System.Globalization;
namespace YKanBan.ViewModels.Dialogs;
/// <summary>
/// The confirmation shown before deleting a card, naming the card id.
/// </summary>
public sealed class DeleteCardConfirmViewModel : ViewModelBase {
/// <summary>
/// Initializes the confirmation.
/// </summary>
/// <param name="cardId">The id of the card to delete.</param>
public DeleteCardConfirmViewModel(long cardId) {
Message = string.Format(
Resources.Culture ?? CultureInfo.CurrentCulture,
Resources.Confirm_DeleteCard_Message,
cardId);
}
/// <summary>
/// Gets the localized confirmation message.
/// </summary>
public string Message { get; }
}
@@ -0,0 +1,27 @@
using System.Globalization;
namespace YKanBan.ViewModels.Dialogs;
/// <summary>
/// The confirmation shown before deleting a column, naming the column and how
/// many cards it will cascade-delete.
/// </summary>
public sealed class DeleteColumnConfirmViewModel : ViewModelBase {
/// <summary>
/// Initializes the confirmation.
/// </summary>
/// <param name="columnTitle">The title of the column to delete.</param>
/// <param name="cardCount">The number of cards in the column.</param>
public DeleteColumnConfirmViewModel(string columnTitle, int cardCount) {
Message = string.Format(
Resources.Culture ?? CultureInfo.CurrentCulture,
Resources.Confirm_DeleteColumn_Message,
columnTitle,
cardCount);
}
/// <summary>
/// Gets the localized confirmation message.
/// </summary>
public string Message { get; }
}
@@ -0,0 +1,27 @@
using System.Globalization;
namespace YKanBan.ViewModels.Dialogs;
/// <summary>
/// The confirmation shown before deleting a tag, naming the tag and how many
/// cards it will be removed from.
/// </summary>
public sealed class DeleteTagConfirmViewModel : ViewModelBase {
/// <summary>
/// Initializes the confirmation.
/// </summary>
/// <param name="tagName">The name of the tag to delete.</param>
/// <param name="usageCount">The number of cards using the tag.</param>
public DeleteTagConfirmViewModel(string tagName, long usageCount) {
Message = string.Format(
Resources.Culture ?? CultureInfo.CurrentCulture,
Resources.DeleteTag_Confirm_Message,
tagName,
usageCount);
}
/// <summary>
/// Gets the localized confirmation message.
/// </summary>
public string Message { get; }
}
@@ -1,33 +0,0 @@
namespace YKanBan.ViewModels.Dialogs;
/// <summary>
/// Base class for modal dialog view models shown through <see cref="IDialogService"/>.
/// The dialog decides when it closes: it raises <see cref="CloseRequested"/>
/// with its result, and a close attempted by the window itself (title-bar close
/// button, Escape) is routed to <see cref="RequestCancelAsync"/> so that the
/// dialog can veto it, for example to ask before discarding edits.
/// </summary>
public abstract class DialogViewModelBase : ViewModelBase
{
/// <summary>
/// Raised when the dialog wants to close; the argument is the dialog result.
/// </summary>
public event EventHandler<bool>? CloseRequested;
/// <summary>
/// Handles a cancel request coming from the window (or a cancel button).
/// The default closes immediately with a negative result.
/// </summary>
/// <returns>A task completing once the request has been handled.</returns>
public virtual Task RequestCancelAsync()
{
Close(false);
return Task.CompletedTask;
}
/// <summary>
/// Asks the hosting window to close with the given result.
/// </summary>
/// <param name="result">The dialog result.</param>
protected void Close(bool result) => CloseRequested?.Invoke(this, result);
}
@@ -0,0 +1,11 @@
namespace YKanBan.ViewModels.Dialogs;
/// <summary>
/// The confirmation shown before closing an editor with unsaved changes.
/// </summary>
public sealed class DiscardEditConfirmViewModel : ViewModelBase {
/// <summary>
/// Gets the localized confirmation message.
/// </summary>
public string Message => Resources.Confirm_Discard_Message;
}
@@ -0,0 +1,23 @@
using System.Globalization;
namespace YKanBan.ViewModels.Dialogs;
/// <summary>
/// The confirmation dialog shown after a successful Markdown export, naming the
/// written file.
/// </summary>
public sealed class ExportDoneViewModel : ViewModelBase {
/// <summary>
/// Initializes the dialog with the exported file path.
/// </summary>
/// <param name="filePath">The path the export was written to.</param>
public ExportDoneViewModel(string filePath) {
Message = string.Format(
Resources.Culture ?? CultureInfo.CurrentCulture, Resources.Export_Done_Message, filePath);
}
/// <summary>
/// Gets the localized confirmation message.
/// </summary>
public string Message { get; }
}
@@ -1,50 +0,0 @@
namespace YKanBan.ViewModels.Dialogs;
/// <summary>
/// Opens modal dialogs on behalf of view models, which never reference views.
/// Every dialog is owned by the top-most open window, so a dialog opened from
/// inside another dialog (nested modal) is centered on and blocks that dialog.
/// </summary>
public interface IDialogService
{
/// <summary>
/// Shows a dialog modally and waits until it closes.
/// </summary>
/// <param name="dialog">The dialog view model; its window is resolved by naming convention.</param>
/// <returns>The dialog result: <see langword="true"/> when it was accepted.</returns>
Task<bool> ShowAsync(DialogViewModelBase dialog);
/// <summary>
/// Shows the system save-file dialog for a Markdown file.
/// </summary>
/// <param name="suggestedFileName">The proposed file name.</param>
/// <returns>The chosen local path, or <see langword="null"/> when the user cancelled.</returns>
Task<string?> PickSaveFilePathAsync(string suggestedFileName);
}
/// <summary>
/// Convenience wrappers for the plain confirmation and message dialogs.
/// </summary>
public static class DialogServiceExtensions
{
/// <summary>
/// Asks a yes/no question.
/// </summary>
/// <param name="dialogs">The dialog service.</param>
/// <param name="message">The localized question.</param>
/// <param name="confirmLabel">The localized label of the confirming button.</param>
/// <returns><see langword="true"/> when the user confirmed.</returns>
public static Task<bool> ConfirmAsync(this IDialogService dialogs, string message, string confirmLabel) =>
dialogs.ShowAsync(new ConfirmDialogViewModel(message, confirmLabel));
/// <summary>
/// Shows an informational message with an optional read-only details block.
/// </summary>
/// <param name="dialogs">The dialog service.</param>
/// <param name="title">The localized window title.</param>
/// <param name="message">The localized message.</param>
/// <param name="details">Untranslated diagnostic details, or <see langword="null"/>.</param>
/// <returns>A task completing when the dialog closes.</returns>
public static Task ShowMessageAsync(this IDialogService dialogs, string title, string message, string? details = null) =>
dialogs.ShowAsync(new MessageDialogViewModel(title, message, details));
}
@@ -1,49 +0,0 @@
using CommunityToolkit.Mvvm.Input;
namespace YKanBan.ViewModels.Dialogs;
/// <summary>
/// A purely informational dialog with a single OK button: a localized message
/// plus optional untranslated, copyable diagnostic details.
/// </summary>
public sealed partial class MessageDialogViewModel : DialogViewModelBase
{
/// <summary>
/// Initializes the message.
/// </summary>
/// <param name="title">The localized window title.</param>
/// <param name="message">The localized message.</param>
/// <param name="details">Untranslated diagnostic details, or <see langword="null"/>.</param>
public MessageDialogViewModel(string title, string message, string? details)
{
Title = title;
Message = message;
Details = details;
}
/// <summary>
/// Gets the localized window title.
/// </summary>
public string Title { get; }
/// <summary>
/// Gets the localized message.
/// </summary>
public string Message { get; }
/// <summary>
/// Gets the diagnostic details, or <see langword="null"/> when there are none.
/// </summary>
public string? Details { get; }
/// <summary>
/// Gets whether a details block is shown.
/// </summary>
public bool HasDetails => !string.IsNullOrEmpty(Details);
/// <summary>
/// Closes the dialog.
/// </summary>
[RelayCommand]
private void Ok() => Close(true);
}
@@ -0,0 +1,39 @@
using CommunityToolkit.Mvvm.ComponentModel;
using YKanBan.Models;
namespace YKanBan.ViewModels.Dialogs;
/// <summary>
/// The move-card dialog: choose one of the other columns as the destination.
/// </summary>
public sealed partial class MoveCardViewModel : ViewModelBase {
/// <summary>
/// Initializes the dialog with the candidate destination columns.
/// </summary>
/// <param name="columns">All columns; the card's current column is excluded.</param>
/// <param name="currentColumnId">The card's current column id.</param>
public MoveCardViewModel(IReadOnlyList<ColumnModel> columns, long currentColumnId) {
Targets = columns
.Where(column => column.Id != currentColumnId)
.Select(column => new OptionItem(column.Id, column.Title))
.ToList();
selectedTarget = Targets.FirstOrDefault();
}
/// <summary>
/// Gets the candidate destination columns.
/// </summary>
public IReadOnlyList<OptionItem> Targets { get; }
/// <summary>
/// Gets or sets the selected destination column.
/// </summary>
[ObservableProperty]
private OptionItem? selectedTarget;
/// <summary>
/// Gets a value indicating whether there is anywhere to move the card.
/// </summary>
public bool CanMove => Targets.Count > 0;
}
@@ -0,0 +1,25 @@
using System.Globalization;
namespace YKanBan.ViewModels.Dialogs;
/// <summary>
/// The pure-information dialog shown when the search expression is invalid. It
/// wraps the parser's non-localized English detail in the localized message.
/// </summary>
public sealed class SearchErrorViewModel : ViewModelBase {
/// <summary>
/// Initializes the dialog with the parser's English detail.
/// </summary>
/// <param name="detail">The non-localized parser error description.</param>
public SearchErrorViewModel(string detail) {
Message = string.Format(
Resources.Culture ?? CultureInfo.CurrentCulture,
Resources.Search_Error_Message,
detail);
}
/// <summary>
/// Gets the localized error message.
/// </summary>
public string Message { get; }
}
@@ -1,4 +1,7 @@
using System.Globalization;
using CommunityToolkit.Mvvm.ComponentModel; using CommunityToolkit.Mvvm.ComponentModel;
using YKanBan.Storage.AppData; using YKanBan.Storage.AppData;
namespace YKanBan.ViewModels.Dialogs; namespace YKanBan.ViewModels.Dialogs;
@@ -8,8 +11,7 @@ namespace YKanBan.ViewModels.Dialogs;
/// confirmation-dialog toggles. Nothing is applied until the user accepts; /// confirmation-dialog toggles. Nothing is applied until the user accepts;
/// cancelling or closing the window discards the changes. /// cancelling or closing the window discards the changes.
/// </summary> /// </summary>
public sealed partial class SettingsDialogViewModel : ViewModelBase public sealed partial class SettingsDialogViewModel : ViewModelBase {
{
private readonly AppConfig _config; private readonly AppConfig _config;
private readonly string _startupLanguage; private readonly string _startupLanguage;
@@ -18,15 +20,15 @@ public sealed partial class SettingsDialogViewModel : ViewModelBase
/// </summary> /// </summary>
/// <param name="config">The live application configuration.</param> /// <param name="config">The live application configuration.</param>
/// <param name="startupLanguage">The language applied at startup, for the restart notice.</param> /// <param name="startupLanguage">The language applied at startup, for the restart notice.</param>
public SettingsDialogViewModel(AppConfig config, string startupLanguage) public SettingsDialogViewModel(AppConfig config, string startupLanguage) {
{
_config = config; _config = config;
_startupLanguage = startupLanguage; _startupLanguage = startupLanguage;
Languages = Languages =
[ [
new OptionItem(AppConfig.DefaultLanguage, Resources.Settings_LanguageEnglish), LanguageOption(AppConfig.DefaultLanguage),
new OptionItem(AppConfig.SimplifiedChineseLanguage, Resources.Settings_LanguageChinese), LanguageOption("zh-Hans"),
LanguageOption("ja"),
]; ];
selectedLanguage = Languages.FirstOrDefault(option => (string)option.Value == _config.Language) selectedLanguage = Languages.FirstOrDefault(option => (string)option.Value == _config.Language)
?? Languages[0]; ?? Languages[0];
@@ -101,14 +103,11 @@ public sealed partial class SettingsDialogViewModel : ViewModelBase
/// <summary> /// <summary>
/// Commits the working values into the live configuration. /// Commits the working values into the live configuration.
/// </summary> /// </summary>
public void Accept() public void Accept() {
{ if (SelectedLanguage is not null) {
if (SelectedLanguage is not null)
{
_config.Language = (string)SelectedLanguage.Value; _config.Language = (string)SelectedLanguage.Value;
} }
if (SelectedTheme is not null) if (SelectedTheme is not null) {
{
_config.Theme = (ThemeOption)SelectedTheme.Value; _config.Theme = (ThemeOption)SelectedTheme.Value;
App.ApplyTheme(_config.Theme); App.ApplyTheme(_config.Theme);
} }
@@ -130,4 +129,11 @@ public sealed partial class SettingsDialogViewModel : ViewModelBase
/// </summary> /// </summary>
private void RefreshRestartNotice() => private void RefreshRestartNotice() =>
RestartNoticeVisible = SelectedLanguage is not null && (string)SelectedLanguage.Value != _startupLanguage; RestartNoticeVisible = SelectedLanguage is not null && (string)SelectedLanguage.Value != _startupLanguage;
/// <summary>
/// Builds a language option whose label is the culture's native name, so the
/// language designates itself identically under every UI culture.
/// </summary>
/// <param name="code">The language code stored in app.json.</param>
private static OptionItem LanguageOption(string code) => new(code, new CultureInfo(code).NativeName);
} }
-26
View File
@@ -1,26 +0,0 @@
using YKanBan.Models;
namespace YKanBan.ViewModels.Dialogs;
/// <summary>
/// The default colors proposed for new tags, shared by the tag picker and the
/// tag editor.
/// </summary>
public static class TagColors
{
/// <summary>
/// Gets the palette, offered as swatches and cycled for new-tag defaults.
/// </summary>
public static IReadOnlyList<RgbColor> Palette { get; } =
[
new(0xd7, 0x3a, 0x4a), new(0x00, 0x75, 0xca), new(0x0e, 0x8a, 0x16), new(0xfb, 0xca, 0x04),
new(0x7c, 0x3a, 0xed), new(0xe9, 0x9b, 0x3c), new(0x00, 0x8b, 0x8b), new(0xcf, 0xd3, 0xd7),
];
/// <summary>
/// Returns the default color of a new tag, cycled by the number of existing tags.
/// </summary>
/// <param name="existingCount">The number of tags already in the workspace.</param>
/// <returns>The proposed color.</returns>
public static RgbColor DefaultFor(int existingCount) => Palette[existingCount % Palette.Count];
}
@@ -1,146 +0,0 @@
using Avalonia.Media;
using Avalonia.Media.Immutable;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using YKanBan.Models;
namespace YKanBan.ViewModels.Dialogs;
/// <summary>
/// The new-tag / edit-tag dialog of the tags tab: name (required, not trimmed),
/// #RRGGBB color with palette swatches and a live preview, and an optional
/// description. Confirming writes through the supplied save callback; an invalid
/// color or a schema-constraint violation (empty or duplicate name) is shown
/// inside the dialog, which stays open with the user's input intact.
/// </summary>
public sealed partial class TagEditorDialogViewModel : DialogViewModelBase
{
private readonly Action<string, RgbColor, string> _save;
/// <summary>
/// Initializes the dialog.
/// </summary>
/// <param name="existing">The tag being edited, or <see langword="null"/> for a new tag.</param>
/// <param name="defaultColor">The color proposed for a new tag.</param>
/// <param name="save">Writes the name, color and description; throws the repository's typed exceptions.</param>
public TagEditorDialogViewModel(TagModel? existing, RgbColor defaultColor, Action<string, RgbColor, string> save)
{
_save = save;
Title = existing is null ? Resources.TagEditor_TitleNew : Resources.TagEditor_TitleEdit;
name = existing?.Name ?? "";
color = (existing?.Color ?? defaultColor).ToString();
description = existing?.Description ?? "";
Swatches = TagColors.Palette.Select(swatch => new ColorSwatch(swatch.ToString(), ToBrush(swatch))).ToList();
UpdateColorPreview();
}
/// <summary>
/// Gets the localized window title.
/// </summary>
public string Title { get; }
/// <summary>
/// Gets the palette swatches; clicking one sets <see cref="Color"/>.
/// </summary>
public IReadOnlyList<ColorSwatch> Swatches { get; }
/// <summary>
/// Gets or sets the tag name being edited (not trimmed).
/// </summary>
[ObservableProperty]
private string name;
/// <summary>
/// Gets or sets the #RRGGBB color text being edited.
/// </summary>
[ObservableProperty]
private string color;
/// <summary>
/// Gets or sets the tag description being edited.
/// </summary>
[ObservableProperty]
private string description;
/// <summary>
/// Gets the preview of <see cref="Color"/>, transparent while it is not valid.
/// </summary>
[ObservableProperty]
private IBrush colorPreview = Brushes.Transparent;
/// <summary>
/// Gets the localized error of the last confirmation, or <see langword="null"/>.
/// </summary>
[ObservableProperty]
[NotifyPropertyChangedFor(nameof(HasError))]
private string? errorMessage;
/// <summary>
/// Gets whether an error is shown.
/// </summary>
public bool HasError => ErrorMessage is not null;
/// <summary>
/// Takes a swatch color.
/// </summary>
/// <param name="hex">The swatch's #RRGGBB text.</param>
[RelayCommand]
private void PickSwatch(string hex) => Color = hex;
/// <summary>
/// Writes the tag; closes on success, otherwise shows the error.
/// </summary>
[RelayCommand]
private void Confirm()
{
if (!RgbColor.TryParse(Color, out RgbColor parsed))
{
ErrorMessage = Resources.Error_Tag_InvalidColor;
return;
}
try
{
_save(Name, parsed, Description);
}
catch (Exception exception)
{
ErrorMessage = WriteErrorMessages.Describe(exception);
return;
}
Close(true);
}
/// <summary>
/// Closes without writing.
/// </summary>
[RelayCommand]
private Task CancelAsync() => RequestCancelAsync();
/// <summary>
/// Refreshes the color preview.
/// </summary>
/// <param name="value">The new color text.</param>
partial void OnColorChanged(string value) => UpdateColorPreview();
/// <summary>
/// Recomputes <see cref="ColorPreview"/> from <see cref="Color"/>.
/// </summary>
private void UpdateColorPreview() =>
ColorPreview = RgbColor.TryParse(Color, out RgbColor parsed) ? ToBrush(parsed) : Brushes.Transparent;
/// <summary>
/// Creates the thread-agnostic brush of a tag color.
/// </summary>
/// <param name="value">The color.</param>
/// <returns>The brush.</returns>
private static IBrush ToBrush(RgbColor value) =>
new ImmutableSolidColorBrush(Avalonia.Media.Color.FromRgb(value.R, value.G, value.B));
}
/// <summary>
/// A palette swatch of the tag editor.
/// </summary>
/// <param name="Hex">The #RRGGBB text.</param>
/// <param name="Brush">The fill.</param>
public sealed record ColorSwatch(string Hex, IBrush Brush);
@@ -0,0 +1,91 @@
using Avalonia.Media;
using CommunityToolkit.Mvvm.ComponentModel;
using Microsoft.Data.Sqlite;
using YKanBan.Models;
using YKanBan.Storage.Workspace;
namespace YKanBan.ViewModels.Dialogs;
/// <summary>
/// The add/edit tag dialog: a name, a color chosen with a color picker and an
/// optional description. The write happens when the dialog is accepted; a
/// duplicate or empty name keeps the dialog open with an inline error.
/// </summary>
public sealed partial class TagEditorViewModel : ViewModelBase {
private readonly WorkspaceRepository _repository;
private readonly TagModel? _existing;
/// <summary>
/// Initializes the dialog for a new or existing tag.
/// </summary>
/// <param name="repository">The workspace repository.</param>
/// <param name="existing">The tag to edit, or <see langword="null"/> to add one.</param>
public TagEditorViewModel(WorkspaceRepository repository, TagModel? existing) {
_repository = repository;
_existing = existing;
name = existing?.Name ?? string.Empty;
description = existing?.Description ?? string.Empty;
color = existing is not null
? Color.FromRgb(existing.Color.R, existing.Color.G, existing.Color.B)
: Colors.Gray;
}
/// <summary>
/// Gets a value indicating whether this dialog creates a new tag.
/// </summary>
public bool IsNew => _existing is null;
/// <summary>
/// Gets the localized window title.
/// </summary>
public string WindowTitle => IsNew ? Resources.TagEditor_AddTitle : Resources.TagEditor_EditTitle;
/// <summary>
/// Gets or sets the tag name.
/// </summary>
[ObservableProperty]
private string name;
/// <summary>
/// Gets or sets the tag color.
/// </summary>
[ObservableProperty]
private Color color;
/// <summary>
/// Gets or sets the tag description.
/// </summary>
[ObservableProperty]
private string description;
/// <summary>
/// Gets or sets the inline error shown when the name is rejected.
/// </summary>
[ObservableProperty]
private string? errorMessage;
/// <summary>
/// Writes the tag when accepted.
/// </summary>
/// <returns><see langword="true"/> when the dialog may close.</returns>
public bool TryAccept() {
ErrorMessage = null;
var rgb = new RgbColor(Color.R, Color.G, Color.B);
try {
if (_existing is null) {
_repository.AddTag(Name, rgb, Description);
} else {
_repository.UpdateTag(_existing.Id, Name, rgb, Description);
}
return true;
} catch (SqliteException) {
ErrorMessage = Resources.TagEditor_InvalidName;
return false;
}
}
}
@@ -1,176 +0,0 @@
using System.Collections.ObjectModel;
using Avalonia.Media;
using Avalonia.Media.Immutable;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using YKanBan.Models;
using YKanBan.Storage;
using YKanBan.Storage.Workspace;
using YKanBan.ViewModels.Board;
namespace YKanBan.ViewModels.Dialogs;
/// <summary>
/// The nested "add tag" modal of the card editor: a filterable list of the
/// existing tags not yet on the card, plus a new-tag entry. Picking a tag closes
/// the dialog with it as <see cref="PickedTag"/>.
///
/// Exception to the edit-dialog unit of work: a tag created here is written to
/// the tags table immediately (tags are global entities), so it survives even
/// when the outer card edit is cancelled — only the assignment is discarded.
/// </summary>
public sealed partial class TagPickerDialogViewModel : DialogViewModelBase
{
private readonly WorkspaceRepository _repository;
private readonly IReadOnlyList<TagBadgeViewModel> _available;
/// <summary>
/// Initializes the picker.
/// </summary>
/// <param name="repository">The workspace repository; new tags are written through it immediately.</param>
/// <param name="assignedTagIds">The tags already on the card, which are not offered again.</param>
public TagPickerDialogViewModel(WorkspaceRepository repository, IReadOnlyCollection<long> assignedTagIds)
{
_repository = repository;
IReadOnlyList<TagModel> all = repository.GetTags();
_available = all
.Where(tag => !assignedTagIds.Contains(tag.Id))
.Select(tag => new TagBadgeViewModel(tag))
.ToList();
FilteredTags = new ObservableCollection<TagBadgeViewModel>(_available);
newColor = TagColors.DefaultFor(all.Count).ToString();
UpdateColorPreview();
}
/// <summary>
/// Gets the tag the user picked or created, once the dialog closed positively.
/// </summary>
public TagModel? PickedTag { get; private set; }
/// <summary>
/// Gets the available tags matching <see cref="FilterText"/>.
/// </summary>
public ObservableCollection<TagBadgeViewModel> FilteredTags { get; }
/// <summary>
/// Gets whether no available tag matches the filter.
/// </summary>
public bool NoMatches => FilteredTags.Count == 0;
/// <summary>
/// Gets or sets the list filter: a case-insensitive substring of the tag name.
/// </summary>
[ObservableProperty]
private string filterText = "";
/// <summary>
/// Gets or sets the name of the tag to create (not trimmed).
/// </summary>
[ObservableProperty]
private string newName = "";
/// <summary>
/// Gets or sets the #RRGGBB color text of the tag to create.
/// </summary>
[ObservableProperty]
private string newColor;
/// <summary>
/// Gets or sets the description of the tag to create.
/// </summary>
[ObservableProperty]
private string newDescription = "";
/// <summary>
/// Gets the preview of <see cref="NewColor"/>, transparent while it is not valid.
/// </summary>
[ObservableProperty]
private IBrush newColorPreview = Brushes.Transparent;
/// <summary>
/// Gets the localized error of the last create attempt, or <see langword="null"/>.
/// </summary>
[ObservableProperty]
[NotifyPropertyChangedFor(nameof(HasError))]
private string? errorMessage;
/// <summary>
/// Gets whether an error is shown.
/// </summary>
public bool HasError => ErrorMessage is not null;
/// <summary>
/// Picks an existing tag and closes.
/// </summary>
/// <param name="tag">The picked tag.</param>
[RelayCommand]
private void Pick(TagBadgeViewModel tag)
{
PickedTag = tag.Tag;
Close(true);
}
/// <summary>
/// Creates the new tag right away and closes with it picked; constraint
/// violations and an invalid color keep the dialog open with an error.
/// </summary>
[RelayCommand]
private void Create()
{
if (!RgbColor.TryParse(NewColor, out RgbColor color))
{
ErrorMessage = Resources.Error_Tag_InvalidColor;
return;
}
try
{
PickedTag = _repository.AddTag(NewName, color, NewDescription);
}
catch (Exception exception)
{
ErrorMessage = WriteErrorMessages.Describe(exception);
return;
}
Close(true);
}
/// <summary>
/// Closes without picking anything.
/// </summary>
[RelayCommand]
private Task CancelAsync() => RequestCancelAsync();
/// <summary>
/// Re-filters the list.
/// </summary>
/// <param name="value">The new filter text.</param>
partial void OnFilterTextChanged(string value)
{
string folded = SqliteDatabase.Fold(value);
FilteredTags.Clear();
foreach (TagBadgeViewModel tag in _available)
{
if (SqliteDatabase.Fold(tag.Name).Contains(folded, StringComparison.Ordinal))
{
FilteredTags.Add(tag);
}
}
OnPropertyChanged(nameof(NoMatches));
}
/// <summary>
/// Refreshes the color preview.
/// </summary>
/// <param name="value">The new color text.</param>
partial void OnNewColorChanged(string value) => UpdateColorPreview();
/// <summary>
/// Recomputes <see cref="NewColorPreview"/> from <see cref="NewColor"/>.
/// </summary>
private void UpdateColorPreview() =>
NewColorPreview = RgbColor.TryParse(NewColor, out RgbColor color)
? new ImmutableSolidColorBrush(Color.FromRgb(color.R, color.G, color.B))
: Brushes.Transparent;
}
@@ -0,0 +1,42 @@
using CommunityToolkit.Mvvm.ComponentModel;
using YKanBan.Storage.Workspace;
using YKanBan.ViewModels.Board;
namespace YKanBan.ViewModels.Dialogs;
/// <summary>
/// The nested tag picker opened from the card editor: choose one tag that is
/// not already assigned to the card. When no candidate remains the picker
/// shows a message and cannot be confirmed.
/// </summary>
public sealed partial class TagPickerViewModel : ViewModelBase {
/// <summary>
/// Initializes the picker with the tags not yet assigned to the card.
/// </summary>
/// <param name="repository">The workspace repository.</param>
/// <param name="assignedTagIds">The tag ids already assigned to the card.</param>
public TagPickerViewModel(WorkspaceRepository repository, IReadOnlyCollection<long> assignedTagIds) {
Targets = repository.GetTags()
.Where(tag => !assignedTagIds.Contains(tag.Id))
.Select(tag => new TagBadgeViewModel(tag))
.ToList();
selectedTarget = Targets.FirstOrDefault();
}
/// <summary>
/// Gets the assignable tags.
/// </summary>
public IReadOnlyList<TagBadgeViewModel> Targets { get; }
/// <summary>
/// Gets or sets the selected tag.
/// </summary>
[ObservableProperty]
private TagBadgeViewModel? selectedTarget;
/// <summary>
/// Gets a value indicating whether there is a tag to add.
/// </summary>
public bool CanAdd => Targets.Count > 0;
}
@@ -1,33 +0,0 @@
using System.Globalization;
using YKanBan.Storage;
namespace YKanBan.ViewModels.Dialogs;
/// <summary>
/// Maps a failed dialog write to the localized message shown inside the dialog
/// that attempted it (the dialog stays open and keeps the user's input). The
/// typed schema-constraint exceptions get dedicated messages; anything else
/// gets a generic one carrying the untranslated exception message.
/// </summary>
public static class WriteErrorMessages
{
/// <summary>
/// Returns the localized message for a failed write.
/// </summary>
/// <param name="exception">The exception thrown by the write.</param>
/// <returns>The localized message.</returns>
public static string Describe(Exception exception)
{
CultureInfo? culture = Resources.Culture;
return exception switch
{
NameRequiredException { Entity: NamedEntity.Column } => Resources.Error_Column_TitleRequired,
NameRequiredException { Entity: NamedEntity.Tag } => Resources.Error_Tag_NameRequired,
DuplicateNameException { Entity: NamedEntity.Column } duplicate =>
string.Format(culture, Resources.Error_Column_Duplicate, duplicate.Name),
DuplicateNameException { Entity: NamedEntity.Tag } duplicate =>
string.Format(culture, Resources.Error_Tag_Duplicate, duplicate.Name),
_ => string.Format(culture, Resources.Error_SaveFailed, exception.Message),
};
}
}
@@ -4,6 +4,5 @@ namespace YKanBan.ViewModels.ErrorPages;
/// The full-window page shown when YKanBan is started without arguments or with /// The full-window page shown when YKanBan is started without arguments or with
/// invalid arguments. It has no operations. /// invalid arguments. It has no operations.
/// </summary> /// </summary>
public sealed class ArgumentErrorPageViewModel : ViewModelBase public sealed class ArgumentErrorPageViewModel : ViewModelBase {
{
} }
@@ -1,31 +0,0 @@
using System.Globalization;
namespace YKanBan.ViewModels.ErrorPages;
/// <summary>
/// The full-window page shown when the folder passed on the command line does
/// not exist. It has no operations.
/// </summary>
public sealed class DirectoryMissingPageViewModel : ViewModelBase
{
/// <summary>
/// Initializes the page for a missing folder.
/// </summary>
/// <param name="folderPath">The folder path that does not exist.</param>
public DirectoryMissingPageViewModel(string folderPath)
{
FolderPath = folderPath;
Message = string.Format(
Resources.Culture ?? CultureInfo.CurrentCulture, Resources.Error_DirectoryMissing_Message, folderPath);
}
/// <summary>
/// Gets the folder path that does not exist.
/// </summary>
public string FolderPath { get; }
/// <summary>
/// Gets the localized explanatory message.
/// </summary>
public string Message { get; }
}
@@ -6,14 +6,12 @@ namespace YKanBan.ViewModels.ErrorPages;
/// The full-window page shown when the workspace is already locked by another /// The full-window page shown when the workspace is already locked by another
/// instance. It has no operations. /// instance. It has no operations.
/// </summary> /// </summary>
public sealed class LockConflictPageViewModel : ViewModelBase public sealed class LockConflictPageViewModel : ViewModelBase {
{
/// <summary> /// <summary>
/// Initializes the page for a locked workspace. /// Initializes the page for a locked workspace.
/// </summary> /// </summary>
/// <param name="folderPath">The locked workspace folder.</param> /// <param name="folderPath">The locked workspace folder.</param>
public LockConflictPageViewModel(string folderPath) public LockConflictPageViewModel(string folderPath) {
{
FolderPath = folderPath; FolderPath = folderPath;
Message = string.Format( Message = string.Format(
Resources.Culture ?? CultureInfo.CurrentCulture, Resources.Error_LockConflict_Message, folderPath); Resources.Culture ?? CultureInfo.CurrentCulture, Resources.Error_LockConflict_Message, folderPath);
@@ -1,4 +1,5 @@
using System.Globalization; using System.Globalization;
using CommunityToolkit.Mvvm.Input; using CommunityToolkit.Mvvm.Input;
namespace YKanBan.ViewModels.ErrorPages; namespace YKanBan.ViewModels.ErrorPages;
@@ -8,8 +9,7 @@ namespace YKanBan.ViewModels.ErrorPages;
/// structure. It is the only error page with an operation: initializing the /// structure. It is the only error page with an operation: initializing the
/// workspace. /// workspace.
/// </summary> /// </summary>
public sealed partial class NotInitializedPageViewModel : ViewModelBase public sealed partial class NotInitializedPageViewModel : ViewModelBase {
{
private readonly Interaction<Unit> _initializeWorkspace; private readonly Interaction<Unit> _initializeWorkspace;
/// <summary> /// <summary>
@@ -17,8 +17,7 @@ public sealed partial class NotInitializedPageViewModel : ViewModelBase
/// </summary> /// </summary>
/// <param name="folderPath">The uninitialized folder path.</param> /// <param name="folderPath">The uninitialized folder path.</param>
/// <param name="initializeWorkspace">The interaction that performs initialization.</param> /// <param name="initializeWorkspace">The interaction that performs initialization.</param>
public NotInitializedPageViewModel(string folderPath, Interaction<Unit> initializeWorkspace) public NotInitializedPageViewModel(string folderPath, Interaction<Unit> initializeWorkspace) {
{
FolderPath = folderPath; FolderPath = folderPath;
_initializeWorkspace = initializeWorkspace; _initializeWorkspace = initializeWorkspace;
Message = string.Format( Message = string.Format(
@@ -1,25 +1,25 @@
using System.Globalization; using System.Globalization;
using Microsoft.Data.Sqlite; using Microsoft.Data.Sqlite;
using YKanBan.Storage; using YKanBan.Storage;
namespace YKanBan.ViewModels.ErrorPages; namespace YKanBan.ViewModels.ErrorPages;
/// <summary> /// <summary>
/// The full-window page shown when a workspace cannot be opened or initialized: /// The full-window page shown when a workspace cannot be opened or initialized:
/// a schema newer than this build, an unopenable or damaged database, an I/O or /// a schema newer than this build, a missing, unopenable or damaged database, an
/// permission error, or any unrecognized failure. It shows a localized message /// I/O or permission error, or any unrecognized failure. It shows a localized
/// chosen by exception type plus the read-only, copyable English exception /// message chosen by exception type plus the read-only, copyable English
/// details, and has no operations. /// exception details, and has no operations.
/// </summary> /// </summary>
public sealed class OpenFailedPageViewModel : ViewModelBase public sealed class OpenFailedPageViewModel : ViewModelBase {
{
/// <summary> /// <summary>
/// Initializes the page for a failed open or initialization. /// Initializes the page for a failed open or initialization.
/// </summary> /// </summary>
/// <param name="folderPath">The workspace folder.</param> /// <param name="folderPath">The workspace folder.</param>
/// <param name="exception">The failure.</param> /// <param name="exception">The failure.</param>
public OpenFailedPageViewModel(string folderPath, Exception exception) public OpenFailedPageViewModel(string folderPath, Exception exception) {
{
FolderPath = folderPath; FolderPath = folderPath;
Message = BuildMessage(folderPath, exception); Message = BuildMessage(folderPath, exception);
@@ -48,13 +48,12 @@ public sealed class OpenFailedPageViewModel : ViewModelBase
/// <param name="folderPath">The workspace folder.</param> /// <param name="folderPath">The workspace folder.</param>
/// <param name="exception">The failure.</param> /// <param name="exception">The failure.</param>
/// <returns>The localized message.</returns> /// <returns>The localized message.</returns>
public static string BuildMessage(string folderPath, Exception exception) public static string BuildMessage(string folderPath, Exception exception) {
{
CultureInfo culture = Resources.Culture ?? CultureInfo.CurrentCulture; CultureInfo culture = Resources.Culture ?? CultureInfo.CurrentCulture;
return exception switch return exception switch {
{
SchemaVersionException schema => string.Format( SchemaVersionException schema => string.Format(
culture, Resources.Error_OpenFailed_SchemaTooNew, folderPath, schema.StoredVersion, schema.SupportedVersion), culture, Resources.Error_OpenFailed_SchemaTooNew, folderPath, schema.StoredVersion, schema.SupportedVersion),
WorkspaceDatabaseMissingException => string.Format(culture, Resources.Error_OpenFailed_DatabaseMissing, folderPath),
SqliteException => string.Format(culture, Resources.Error_OpenFailed_Database, folderPath), SqliteException => string.Format(culture, Resources.Error_OpenFailed_Database, folderPath),
UnauthorizedAccessException => string.Format(culture, Resources.Error_OpenFailed_AccessDenied, folderPath), UnauthorizedAccessException => string.Format(culture, Resources.Error_OpenFailed_AccessDenied, folderPath),
IOException => string.Format(culture, Resources.Error_OpenFailed_Io, folderPath), IOException => string.Format(culture, Resources.Error_OpenFailed_Io, folderPath),
+3 -6
View File
@@ -3,8 +3,7 @@ namespace YKanBan.ViewModels;
/// <summary> /// <summary>
/// Input placeholder for interactions that carry no meaningful payload. /// Input placeholder for interactions that carry no meaningful payload.
/// </summary> /// </summary>
public readonly record struct Unit public readonly record struct Unit {
{
/// <summary> /// <summary>
/// Gets the single unit value. /// Gets the single unit value.
/// </summary> /// </summary>
@@ -18,8 +17,7 @@ public readonly record struct Unit
/// The view model never holds a reference to a view. /// The view model never holds a reference to a view.
/// </summary> /// </summary>
/// <typeparam name="TInput">The request payload.</typeparam> /// <typeparam name="TInput">The request payload.</typeparam>
public sealed class Interaction<TInput> public sealed class Interaction<TInput> {
{
private Func<TInput, Task>? _handler; private Func<TInput, Task>? _handler;
/// <summary> /// <summary>
@@ -46,8 +44,7 @@ public sealed class Interaction<TInput>
/// </summary> /// </summary>
/// <typeparam name="TInput">The request payload.</typeparam> /// <typeparam name="TInput">The request payload.</typeparam>
/// <typeparam name="TOutput">The handler's answer.</typeparam> /// <typeparam name="TOutput">The handler's answer.</typeparam>
public sealed class Interaction<TInput, TOutput> public sealed class Interaction<TInput, TOutput> {
{
private Func<TInput, Task<TOutput>>? _handler; private Func<TInput, Task<TOutput>>? _handler;
/// <summary> /// <summary>
+32 -47
View File
@@ -1,10 +1,11 @@
using System.Diagnostics; using System.Diagnostics;
using CommunityToolkit.Mvvm.ComponentModel; using CommunityToolkit.Mvvm.ComponentModel;
using YKanBan.Launching; using YKanBan.Launching;
using YKanBan.Services; using YKanBan.Services;
using YKanBan.Storage; using YKanBan.Storage;
using YKanBan.Storage.Workspace; using YKanBan.Storage.Workspace;
using YKanBan.ViewModels.Dialogs;
using YKanBan.ViewModels.ErrorPages; using YKanBan.ViewModels.ErrorPages;
namespace YKanBan.ViewModels; namespace YKanBan.ViewModels;
@@ -14,21 +15,16 @@ namespace YKanBan.ViewModels;
/// normal workspace view or one of the full-window error pages, and owns the /// normal workspace view or one of the full-window error pages, and owns the
/// interactions that the view fulfils by opening dialogs. /// interactions that the view fulfils by opening dialogs.
/// </summary> /// </summary>
public sealed partial class MainWindowViewModel : ViewModelBase public sealed partial class MainWindowViewModel : ViewModelBase {
{
private readonly AppServices _services; private readonly AppServices _services;
private readonly IDialogService _dialogs;
/// <summary> /// <summary>
/// Initializes the view model and resolves the workspace state. /// Initializes the view model and resolves the workspace state.
/// </summary> /// </summary>
/// <param name="services">The process composition root.</param> /// <param name="services">The process composition root.</param>
/// <param name="dialogs">The modal dialog service used by the board.</param>
/// <param name="arguments">The command-line arguments (excluding the executable).</param> /// <param name="arguments">The command-line arguments (excluding the executable).</param>
public MainWindowViewModel(AppServices services, IDialogService dialogs, IReadOnlyList<string> arguments) public MainWindowViewModel(AppServices services, IReadOnlyList<string> arguments) {
{
_services = services; _services = services;
_dialogs = dialogs;
ShowSettings = new Interaction<Unit>(); ShowSettings = new Interaction<Unit>();
ShowAbout = new Interaction<Unit>(); ShowAbout = new Interaction<Unit>();
InitializeWorkspace = new Interaction<Unit>(); InitializeWorkspace = new Interaction<Unit>();
@@ -67,34 +63,19 @@ public sealed partial class MainWindowViewModel : ViewModelBase
/// Resolves the launch arguments into a content view model. /// Resolves the launch arguments into a content view model.
/// </summary> /// </summary>
/// <param name="arguments">The command-line arguments.</param> /// <param name="arguments">The command-line arguments.</param>
private void Resolve(IReadOnlyList<string> arguments) private void Resolve(IReadOnlyList<string> arguments) {
{ if (!LaunchArguments.TryParse(arguments, out string? folderPath)) {
if (!LaunchArguments.TryParse(arguments, out string? folderPath))
{
Content = new ArgumentErrorPageViewModel(); Content = new ArgumentErrorPageViewModel();
return; return;
} }
if (!Directory.Exists(folderPath)) try {
{
Content = new DirectoryMissingPageViewModel(folderPath);
return;
}
try
{
OpenWorkspace(folderPath); OpenWorkspace(folderPath);
} } catch (WorkspaceNotInitializedException) {
catch (WorkspaceNotInitializedException)
{
Content = new NotInitializedPageViewModel(folderPath, InitializeWorkspace); Content = new NotInitializedPageViewModel(folderPath, InitializeWorkspace);
} } catch (WorkspaceLockException) {
catch (WorkspaceLockException)
{
Content = new LockConflictPageViewModel(folderPath); Content = new LockConflictPageViewModel(folderPath);
} } catch (Exception exception) {
catch (Exception exception)
{
// Newer schema, damaged database, I/O or permission errors, and anything unrecognized. // Newer schema, damaged database, I/O or permission errors, and anything unrecognized.
Debug.WriteLine(exception); Debug.WriteLine(exception);
Content = new OpenFailedPageViewModel(folderPath, exception); Content = new OpenFailedPageViewModel(folderPath, exception);
@@ -105,10 +86,22 @@ public sealed partial class MainWindowViewModel : ViewModelBase
/// Opens the workspace and switches the content to the normal view. /// Opens the workspace and switches the content to the normal view.
/// </summary> /// </summary>
/// <param name="folderPath">The workspace folder to open.</param> /// <param name="folderPath">The workspace folder to open.</param>
private void OpenWorkspace(string folderPath) private void OpenWorkspace(string folderPath) => OpenWorkspace(folderPath, _services.OpenWorkspace(folderPath));
{
WorkspaceSession session = _services.OpenWorkspace(folderPath); /// <summary>
Content = new WorkspaceViewModel(session, ShowSettings, ShowAbout, _services.Config, _dialogs); /// Switches the content to the normal view of an already opened workspace.
/// </summary>
/// <param name="folderPath">The workspace folder.</param>
/// <param name="session">The opened workspace session.</param>
private void OpenWorkspace(string folderPath, WorkspaceSession session) {
try {
Content = new WorkspaceViewModel(_services, session, ShowSettings, ShowAbout);
} catch {
// The first board read failed: the caller shows an error page, which holds no workspace.
_services.CloseWorkspace();
throw;
}
Title = $"{new DirectoryInfo(folderPath).Name} - {Resources.App_Name}"; Title = $"{new DirectoryInfo(folderPath).Name} - {Resources.App_Name}";
} }
@@ -117,24 +110,16 @@ public sealed partial class MainWindowViewModel : ViewModelBase
/// columns and opens the resulting workspace. /// columns and opens the resulting workspace.
/// </summary> /// </summary>
/// <returns>A completed task once initialization has been attempted.</returns> /// <returns>A completed task once initialization has been attempted.</returns>
private Task InitializeCurrentWorkspaceAsync() private Task InitializeCurrentWorkspaceAsync() {
{ if (Content is not NotInitializedPageViewModel page) {
if (Content is not NotInitializedPageViewModel page)
{
return Task.CompletedTask; return Task.CompletedTask;
} }
try try {
{ OpenWorkspace(page.FolderPath, _services.InitializeWorkspace(page.FolderPath));
WorkspaceInitializer.Initialize(page.FolderPath); } catch (Exception exception) when (exception is YKanBanException or IOException or UnauthorizedAccessException) {
WorkspacePreset.AddPresetColumns(page.FolderPath); // Initialization failed; the page remains so the user can retry.
OpenWorkspace(page.FolderPath);
}
catch (Exception exception)
{
// Initialization failed: switch to the open-failed page, which has no operations.
Debug.WriteLine(exception); Debug.WriteLine(exception);
Content = new OpenFailedPageViewModel(page.FolderPath, exception);
} }
return Task.CompletedTask; return Task.CompletedTask;
@@ -0,0 +1,78 @@
using System.Globalization;
using CommunityToolkit.Mvvm.Input;
using YKanBan.Models;
using YKanBan.ViewModels.Board;
namespace YKanBan.ViewModels.Tags;
/// <summary>
/// One row of the tag manager: a color swatch, the name, the description and the
/// usage count, plus edit and delete actions.
/// </summary>
public sealed partial class TagItemViewModel {
private readonly TagsViewModel _owner;
/// <summary>
/// Initializes the row.
/// </summary>
/// <param name="owner">The owning tag manager.</param>
/// <param name="tag">The tag model.</param>
/// <param name="usageCount">The number of cards using the tag.</param>
public TagItemViewModel(TagsViewModel owner, TagModel tag, long usageCount) {
_owner = owner;
Tag = tag;
Badge = new TagBadgeViewModel(tag);
UsageCount = usageCount;
UsageText = string.Format(
Resources.Culture ?? CultureInfo.CurrentCulture, Resources.Tags_Usage, usageCount);
}
/// <summary>
/// Gets the underlying tag model.
/// </summary>
public TagModel Tag { get; }
/// <summary>
/// Gets the colored badge for the swatch and name.
/// </summary>
public TagBadgeViewModel Badge { get; }
/// <summary>
/// Gets the tag name.
/// </summary>
public string Name => Tag.Name;
/// <summary>
/// Gets the tag description.
/// </summary>
public string Description => Tag.Description;
/// <summary>
/// Gets a value indicating whether the tag has a description.
/// </summary>
public bool HasDescription => Tag.Description.Length > 0;
/// <summary>
/// Gets the number of cards using the tag.
/// </summary>
public long UsageCount { get; }
/// <summary>
/// Gets the localized usage count.
/// </summary>
public string UsageText { get; }
/// <summary>
/// Asks the manager to edit this tag.
/// </summary>
[RelayCommand]
private void Edit() => _ = _owner.RequestEditAsync(this);
/// <summary>
/// Asks the manager to delete this tag.
/// </summary>
[RelayCommand]
private void Delete() => _ = _owner.RequestDeleteAsync(this);
}
@@ -1,77 +0,0 @@
using CommunityToolkit.Mvvm.Input;
using YKanBan.Models;
using YKanBan.ViewModels.Board;
namespace YKanBan.ViewModels.Tags;
/// <summary>
/// One row of the tags tab: the colored badge, the description and the usage
/// count, with edit and delete actions.
/// </summary>
public sealed partial class TagRowViewModel : ViewModelBase
{
private readonly TagsViewModel _owner;
/// <summary>
/// Initializes the row.
/// </summary>
/// <param name="owner">The tags tab performing the actions.</param>
/// <param name="tag">The tag shown.</param>
/// <param name="usageCount">The number of cards carrying the tag.</param>
public TagRowViewModel(TagsViewModel owner, TagModel tag, long usageCount)
{
_owner = owner;
Tag = tag;
Badge = new TagBadgeViewModel(tag);
UsageCount = usageCount;
}
/// <summary>
/// Gets the tag shown.
/// </summary>
public TagModel Tag { get; }
/// <summary>
/// Gets the colored badge (color + name).
/// </summary>
public TagBadgeViewModel Badge { get; }
/// <summary>
/// Gets the tag description.
/// </summary>
public string Description => Tag.Description;
/// <summary>
/// Gets whether the tag has a description.
/// </summary>
public bool HasDescription => Tag.Description.Length > 0;
/// <summary>
/// Gets the #RRGGBB color text.
/// </summary>
public string ColorText => Tag.Color.ToString();
/// <summary>
/// Gets the number of cards carrying the tag.
/// </summary>
public long UsageCount { get; }
/// <summary>
/// Gets the localized usage count, for example "3 cards".
/// </summary>
public string UsageText => string.Format(Resources.Culture, Resources.Tags_UsageCount, UsageCount);
/// <summary>
/// Opens the edit dialog.
/// </summary>
/// <returns>A task completing when the dialog closes.</returns>
[RelayCommand]
private Task EditAsync() => _owner.EditTagAsync(Tag);
/// <summary>
/// Deletes the tag.
/// </summary>
/// <returns>A task completing when the tag is deleted or the deletion was declined.</returns>
[RelayCommand]
private Task DeleteAsync() => _owner.DeleteTagAsync(Tag, UsageCount);
}
+70 -101
View File
@@ -1,144 +1,113 @@
using System.Collections.ObjectModel; using System.Collections.ObjectModel;
using System.Diagnostics; using System.Globalization;
using CommunityToolkit.Mvvm.Input; using CommunityToolkit.Mvvm.Input;
using YKanBan.Models; using YKanBan.Models;
using YKanBan.Storage.AppData;
using YKanBan.Storage.Workspace; using YKanBan.Storage.Workspace;
using YKanBan.ViewModels.Dialogs;
namespace YKanBan.ViewModels.Tags; namespace YKanBan.ViewModels.Tags;
/// <summary> /// <summary>
/// The tags tab, a tag manager in the style of the GitHub issue labels page: /// The tags tab: a manager for the workspace's tags (create, rename, recolor,
/// every tag with its color, name, description and usage count, plus creating, /// re-describe and delete), showing each tag's color, name, description and
/// editing (rename, recolor, describe) and deleting tags. Unreferenced tags are /// usage count. Tag changes also refresh the board.
/// never cleaned up automatically, so this is where they are removed.
/// </summary> /// </summary>
public sealed partial class TagsViewModel : ViewModelBase public sealed partial class TagsViewModel : ViewModelBase {
{
private readonly WorkspaceRepository _repository; private readonly WorkspaceRepository _repository;
private readonly AppConfig _config; private readonly Action _boardChanged;
private readonly IDialogService _dialogs;
/// <summary> /// <summary>
/// Initializes the tab and loads it. /// Initializes the manager, loading the current tags.
/// </summary> /// </summary>
/// <param name="repository">The workspace repository.</param> /// <param name="repository">The workspace repository.</param>
/// <param name="config">The live application configuration (delete confirmation).</param> /// <param name="boardChanged">Invoked after a tag change so the board refreshes.</param>
/// <param name="dialogs">The modal dialog service.</param> public TagsViewModel(WorkspaceRepository repository, Action boardChanged) {
public TagsViewModel(WorkspaceRepository repository, AppConfig config, IDialogService dialogs)
{
_repository = repository; _repository = repository;
_config = config; _boardChanged = boardChanged;
_dialogs = dialogs; Reload();
Refresh();
} }
/// <summary> /// <summary>
/// Raised after every tag write, so the board can show the new names and colors. /// Gets the workspace repository used for tag access.
/// </summary> /// </summary>
public event EventHandler? TagsChanged; public WorkspaceRepository Repository => _repository;
/// <summary> /// <summary>
/// Gets the tags in id order. /// Gets the tags in id order.
/// </summary> /// </summary>
public ObservableCollection<TagRowViewModel> Tags { get; } = []; public ObservableCollection<TagItemViewModel> Tags { get; } = [];
/// <summary> /// <summary>
/// Gets the localized total, for example "3 tags". /// Gets a value indicating whether the workspace has any tags.
/// </summary> /// </summary>
public string Summary => string.Format(Resources.Culture, Resources.Tags_Summary, Tags.Count); public bool HasTags => Tags.Count > 0;
/// <summary> /// <summary>
/// Gets whether the workspace has no tags yet. /// Gets a value indicating whether the workspace has no tags.
/// </summary> /// </summary>
public bool IsEmpty => Tags.Count == 0; public bool HasNoTags => Tags.Count == 0;
/// <summary> /// <summary>
/// Reloads the tags with their usage counts. /// Gets the localized total number of tags shown next to the add button.
/// </summary> /// </summary>
public void Refresh() public string TagCountText => string.Format(
{ Resources.Culture ?? CultureInfo.CurrentCulture, Resources.Tags_Count, Tags.Count);
Tags.Clear();
foreach ((TagModel tag, long usage) in _repository.GetTagsWithUsage())
{
Tags.Add(new TagRowViewModel(this, tag, usage));
}
OnPropertyChanged(nameof(Summary));
OnPropertyChanged(nameof(IsEmpty));
}
/// <summary> /// <summary>
/// Opens the new-tag dialog. /// Gets the interaction that opens the new-tag editor.
/// </summary>
public Interaction<Unit> AddTag { get; } = new();
/// <summary>
/// Gets the interaction that opens the tag editor.
/// </summary>
public Interaction<TagItemViewModel> EditTag { get; } = new();
/// <summary>
/// Gets the interaction that confirms and deletes a tag.
/// </summary>
public Interaction<TagItemViewModel> DeleteTag { get; } = new();
/// <summary>
/// Opens the new-tag editor.
/// </summary> /// </summary>
/// <returns>A task completing when the dialog closes.</returns>
[RelayCommand] [RelayCommand]
private async Task AddTagAsync() private Task AddNewTagAsync() => AddTag.Handle(Unit.Value);
{
var dialog = new TagEditorDialogViewModel( /// <summary>
null, /// Requests the editor for a tag.
TagColors.DefaultFor(Tags.Count), /// </summary>
(name, color, description) => _repository.AddTag(name, color, description)); /// <param name="item">The tag to edit.</param>
if (await _dialogs.ShowAsync(dialog)) /// <returns>A task completing after the editor closes.</returns>
{ public Task RequestEditAsync(TagItemViewModel item) => EditTag.Handle(item);
AfterWrite();
/// <summary>
/// Requests deletion of a tag.
/// </summary>
/// <param name="item">The tag to delete.</param>
/// <returns>A task completing after confirmation.</returns>
public Task RequestDeleteAsync(TagItemViewModel item) => DeleteTag.Handle(item);
/// <summary>
/// Reloads the tag list from the repository.
/// </summary>
public void Reload() {
Tags.Clear();
foreach ((TagModel tag, long usage) in _repository.GetTagsWithUsage()) {
Tags.Add(new TagItemViewModel(this, tag, usage));
} }
OnPropertyChanged(nameof(HasTags));
OnPropertyChanged(nameof(HasNoTags));
OnPropertyChanged(nameof(TagCountText));
} }
/// <summary> /// <summary>
/// Opens the edit-tag dialog. /// Reloads the tags and refreshes the board after a tag change.
/// </summary> /// </summary>
/// <param name="tag">The tag to edit.</param> public void RefreshAfterChange() {
/// <returns>A task completing when the dialog closes.</returns> Reload();
internal async Task EditTagAsync(TagModel tag) _boardChanged();
{
var dialog = new TagEditorDialogViewModel(
tag,
tag.Color,
(name, color, description) => _repository.UpdateTag(tag.Id, name, color, description));
if (await _dialogs.ShowAsync(dialog))
{
AfterWrite();
}
}
/// <summary>
/// Deletes a tag (removing it from its cards), asking first when that
/// confirmation is enabled.
/// </summary>
/// <param name="tag">The tag to delete.</param>
/// <param name="usageCount">The number of cards carrying it.</param>
/// <returns>A task completing when the tag is deleted or the deletion was declined.</returns>
internal async Task DeleteTagAsync(TagModel tag, long usageCount)
{
if (_config.Confirmations.DeleteTag)
{
string message = string.Format(Resources.Culture, Resources.Confirm_DeleteTag, tag.Name, usageCount);
if (!await _dialogs.ConfirmAsync(message, Resources.Common_Delete))
{
return;
}
}
try
{
_repository.DeleteTag(tag.Id);
}
catch (Exception exception)
{
Debug.WriteLine(exception);
await _dialogs.ShowMessageAsync(
Resources.Error_Operation_Title, Resources.Error_Operation_Message, exception.Message);
}
AfterWrite();
}
/// <summary>
/// Reloads the list and tells the board that tags changed.
/// </summary>
private void AfterWrite()
{
Refresh();
TagsChanged?.Invoke(this, EventArgs.Empty);
} }
} }
Loaded 100 of 163 files, more files were not shown because too many files have changed in this diff. Show more