Compare commits
22
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c2b744e742 | ||
|
|
9c47ce6b38 | ||
|
|
704b0ff3cf | ||
|
|
a9e97d9b35 | ||
|
|
da2a73d70f | ||
|
|
68e4ace92b | ||
|
|
e9f39a3a53 | ||
|
|
60619e0290 | ||
|
|
e3265e3c89 | ||
|
|
157f597eed | ||
|
|
1140cd500b | ||
|
|
7f277d1630 | ||
|
|
647232c447 | ||
|
|
78e5faa3c4 | ||
|
|
97f79db3f1 | ||
|
|
90a7531a27 | ||
|
|
8b7e50a955 | ||
|
|
9ea551b600 | ||
|
|
8a7c6fe8d6 | ||
|
|
d8a4dd6190 | ||
|
|
0fdd94d109 | ||
|
|
830f1153fd |
No files matched your search
+1
-1
@@ -18,7 +18,7 @@ indent_size = 4
|
||||
tab_width = 4
|
||||
|
||||
# New line preferences
|
||||
insert_final_newline = false
|
||||
insert_final_newline = true
|
||||
|
||||
#### .NET Coding Conventions ####
|
||||
[*.{cs,vb}]
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
# Shell scripts run under bash on every CI runner, including Windows checkouts with autocrlf.
|
||||
*.sh text eol=lf
|
||||
@@ -0,0 +1,67 @@
|
||||
# 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
|
||||
# skips the rest of that job, so a RID whose tests fail produces no artifact.
|
||||
# No GitHub Release is created.
|
||||
name: Build
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
env:
|
||||
DOTNET_NOLOGO: "true"
|
||||
DOTNET_CLI_TELEMETRY_OPTOUT: "true"
|
||||
|
||||
jobs:
|
||||
build:
|
||||
name: ${{ matrix.rid }}
|
||||
runs-on: ${{ matrix.os }}
|
||||
strategy:
|
||||
# Every RID stands on its own: one failure does not cancel the others.
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- rid: win-x64
|
||||
os: windows-latest
|
||||
- rid: linux-x64
|
||||
os: ubuntu-latest
|
||||
- rid: osx-arm64
|
||||
os: macos-15
|
||||
defaults:
|
||||
run:
|
||||
shell: bash
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Set up .NET
|
||||
uses: actions/setup-dotnet@v4
|
||||
with:
|
||||
dotnet-version: 10.0.x
|
||||
|
||||
- name: Build
|
||||
run: dotnet build YKanBan.slnx -c Release
|
||||
|
||||
- name: Test
|
||||
run: dotnet test YKanBan.slnx -c Release --no-build
|
||||
|
||||
- name: Publish
|
||||
run: >
|
||||
dotnet publish YKanBan/YKanBan.csproj -c Release -r ${{ matrix.rid }}
|
||||
--self-contained -o publish/${{ matrix.rid }}
|
||||
|
||||
- name: Pack
|
||||
id: pack
|
||||
run: |
|
||||
version="$(dotnet msbuild YKanBan/YKanBan.csproj -getProperty:Version)"
|
||||
bash packaging/package.sh ${{ matrix.rid }} publish/${{ matrix.rid }} dist "$version"
|
||||
echo "name=YKanBan-$version-${{ matrix.rid }}" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Upload artifact
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: ${{ steps.pack.outputs.name }}
|
||||
path: dist/*
|
||||
if-no-files-found: error
|
||||
@@ -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.
|
||||
@@ -1,5 +1,28 @@
|
||||
# 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>`.
|
||||
|
||||
WIP.
|
||||
- One board per workspace, with columns, cards and colored tags.
|
||||
- Strict search expressions, for example `tag:bug OR title:login`.
|
||||
- Markdown export of the whole board, and a tag manager.
|
||||
- Multi-language interface; light, dark or system theme.
|
||||
|
||||
See [USAGE.md](USAGE.md) for installing, starting YKanBan, workspaces and backups, the search syntax and the settings file.
|
||||
|
||||
## Building
|
||||
|
||||
Requires the .NET 10 SDK.
|
||||
|
||||
```
|
||||
dotnet build YKanBan.slnx
|
||||
dotnet test YKanBan.slnx
|
||||
dotnet run --project YKanBan -- <path>
|
||||
```
|
||||
|
||||
Packages are pinned in `YKanBan/YKanBan.csproj`.
|
||||
|
||||
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
|
||||
|
||||
MIT — see [LICENSE](LICENSE).
|
||||
@@ -0,0 +1,194 @@
|
||||
# YKanBan Usage
|
||||
|
||||
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.
|
||||
|
||||
## Installing
|
||||
|
||||
Each release build is a self-contained archive; no .NET runtime is needed.
|
||||
|
||||
| Platform | Archive | Executable |
|
||||
|---|---|---|
|
||||
| Windows x64 | `YKanBan-<version>-win-x64.zip` | `YKanBan.exe` |
|
||||
| Linux x64 | `YKanBan-<version>-linux-x64.tar.gz` | `YKanBan` |
|
||||
| macOS Apple silicon | `YKanBan-<version>-osx-arm64.tar.gz` | `YKanBan.app` (see [macOS](#macos)) |
|
||||
|
||||
Only Apple silicon macOS is a release target; there is no Intel Mac build.
|
||||
|
||||
Extract the archive anywhere. To type `ykanban <path>` as shown below, put the executable on your `PATH` under that name, for example:
|
||||
|
||||
```sh
|
||||
# Linux
|
||||
ln -s /opt/YKanBan-<version>-linux-x64/YKanBan ~/.local/bin/ykanban
|
||||
# macOS
|
||||
ln -s /Applications/YKanBan.app/Contents/MacOS/YKanBan /usr/local/bin/ykanban
|
||||
```
|
||||
|
||||
On Windows, add the extracted folder to `PATH`; `ykanban` then finds `YKanBan.exe` because Windows ignores case.
|
||||
|
||||
## Starting YKanBan
|
||||
|
||||
The only way to start YKanBan is with the workspace path:
|
||||
|
||||
```sh
|
||||
ykanban <path>
|
||||
```
|
||||
|
||||
- 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`).
|
||||
- YKanBan looks for `.ykanban` **only in `<path>` itself**; it does not search 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`.
|
||||
|
||||
The path must exist and be a folder. When the board cannot be shown, the whole window shows one of these pages instead:
|
||||
|
||||
| Page | When |
|
||||
|---|---|
|
||||
| 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. |
|
||||
| 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). |
|
||||
| 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. |
|
||||
| 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. |
|
||||
|
||||
The window title is `<workspace name> - YKanBan` while a workspace is open and just `YKanBan` on these pages.
|
||||
|
||||
## macOS
|
||||
|
||||
The app is not notarized. After extracting, remove the download quarantine once, or macOS refuses to open it:
|
||||
|
||||
```sh
|
||||
xattr -dr com.apple.quarantine YKanBan.app
|
||||
```
|
||||
|
||||
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:
|
||||
|
||||
```sh
|
||||
open -n -a YKanBan --args /path/to/project
|
||||
/Applications/YKanBan.app/Contents/MacOS/YKanBan /path/to/project
|
||||
```
|
||||
|
||||
- Keep `-n`: without it, `open` only brings an already running YKanBan to the front and drops the path, instead of starting another window.
|
||||
- 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
|
||||
|
||||
- **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:
|
||||
|
||||
```sh
|
||||
echo ".ykanban/" >> ~/.gitignore_global
|
||||
git config --global core.excludesFile ~/.gitignore_global
|
||||
```
|
||||
|
||||
- **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.
|
||||
- **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. The file itself is kept empty; only the exclusive OS handle it carries has meaning.
|
||||
|
||||
## Search Syntax
|
||||
|
||||
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.
|
||||
|
||||
- Columns are always shown, even when none of their cards match.
|
||||
- An empty or blank expression shows every card.
|
||||
- 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.
|
||||
|
||||
### Examples
|
||||
|
||||
| Expression | Finds cards… |
|
||||
|---|---|
|
||||
| `login` | whose title or content contains "login" |
|
||||
| `login crash` | containing both words (anywhere in title or content) |
|
||||
| `login OR signup` | containing either word |
|
||||
| `tag:bug title:login` | tagged `bug` whose title contains "login" |
|
||||
| `tag:bug OR tag:ui` | tagged `bug` or `ui` |
|
||||
| `(tag:bug OR tag:ui) column:Done` | tagged `bug` or `ui` in the column titled "Done" |
|
||||
| `"dark mode"` | whose title or content contains "dark mode" |
|
||||
| `tag:"needs review"` | tagged `needs review` |
|
||||
| `id:61` or `id:#61` | number 61 |
|
||||
| `"http://example.com"` | containing the URL (a `:` must be quoted) |
|
||||
| `"AND"` | containing the text "AND" |
|
||||
|
||||
### Grammar
|
||||
|
||||
```
|
||||
query := orExpr
|
||||
orExpr := andExpr ( OR andExpr )*
|
||||
andExpr := operand ( (AND)? operand )* -- neighbours are joined by AND
|
||||
operand := atom | '(' orExpr ')'
|
||||
atom := word | phrase | qualifier
|
||||
qualifier := key ':' value
|
||||
key := tag | title | content | id | column
|
||||
value := word | phrase -- tag / title / content / column
|
||||
| '#'? digit+ -- id: a positive decimal integer
|
||||
word := one or more characters, except whitespace and ( ) " : \ ;
|
||||
not equal to AND or OR
|
||||
phrase := '"' one or more characters '"' -- escapes: \" and \\
|
||||
```
|
||||
|
||||
### Operators
|
||||
|
||||
- `AND` and `OR` are operators **only in uppercase**. `and` and `or` are ordinary words.
|
||||
- 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 parentheses to group differently: `(a OR b) c`.
|
||||
- To search for the literal text `AND` or `OR`, quote it: `"AND"`, `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
|
||||
|
||||
| Atom | Matches when |
|
||||
|---|---|
|
||||
| word or phrase | the card title **or** content contains the text |
|
||||
| `title:` value | the card title contains the text |
|
||||
| `content:` value | the card content contains the text |
|
||||
| `tag:` value | the card has a tag whose name **equals** the text |
|
||||
| `column:` value | the card is in a column whose title **equals** the text |
|
||||
| `id:` value | the card number equals the value |
|
||||
|
||||
- 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`.
|
||||
- `id:` takes an unquoted positive integer, optionally prefixed with `#`: `id:61`, `id:#61`.
|
||||
|
||||
### Quoting and Escapes
|
||||
|
||||
- A phrase is text in double quotes. Inside it, `\"` stands for a quote and `\\` 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"`.
|
||||
- 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"`.
|
||||
- A qualifier's phrase value follows the `:` directly: `tag:"needs review"`, not `tag: "needs review"`.
|
||||
|
||||
### Case
|
||||
|
||||
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.
|
||||
|
||||
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.
|
||||
|
||||
### Invalid Expressions
|
||||
|
||||
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.
|
||||
|
||||
These are invalid:
|
||||
|
||||
| Problem | Example |
|
||||
|---|---|
|
||||
| Unbalanced parentheses | `(tag:bug`, `tag:bug)` |
|
||||
| An operator with a missing side | `bug AND`, `OR bug` |
|
||||
| Consecutive operators | `a AND OR b` |
|
||||
| A qualifier without a value | `tag:` |
|
||||
| `AND` / `OR` as an unquoted qualifier value | `tag:AND` (write `tag:"AND"`) |
|
||||
| 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"` |
|
||||
| A backslash outside a phrase | `C:\temp` |
|
||||
| An unknown qualifier key | `label:bug`, `Tag:bug`, `http://x` |
|
||||
| An unquoted value containing `:` | `title:a:b` |
|
||||
| An `id:` value that is not an unquoted positive integer | `id:abc`, `id:0`, `id:"61"` |
|
||||
|
||||
## Settings File
|
||||
|
||||
Settings (language, theme, card sort order, column width and the confirmation switches) are stored in `app.json`:
|
||||
|
||||
| Platform | Location |
|
||||
|---|---|
|
||||
| Windows | `%APPDATA%\YKanBan\app.json` |
|
||||
| Linux, macOS | `~/.config/YKanBan/app.json` (`$XDG_CONFIG_HOME/YKanBan/app.json` when that is set) |
|
||||
|
||||
- The file is written when YKanBan exits. With several instances running, the last one to exit overwrites the file with its own settings.
|
||||
- A language change takes effect after restarting YKanBan; a theme change applies as soon as the settings dialog is accepted.
|
||||
- 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.
|
||||
- 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.
|
||||
@@ -0,0 +1,53 @@
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace YKanBan.Tests.Conventions;
|
||||
|
||||
/// <summary>
|
||||
/// Source-level guards for code-behind conventions (plan §8.1): inside control,
|
||||
/// window and application code-behind a bare <c>Resources.Key</c> resolves to
|
||||
/// the <c>StyledElement.Resources</c> instance property, so the generated class
|
||||
/// must be written as <c>YKanBan.Resources</c> (or through a using alias).
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
public partial class CodeBehindConventionTests {
|
||||
/// <summary>A <c>Resources.</c> member access not preceded by a qualifier or identifier character.</summary>
|
||||
[GeneratedRegex(@"(?<![\w.])Resources\.")]
|
||||
private static partial Regex BareResourcesAccess();
|
||||
|
||||
/// <summary>
|
||||
/// Locates the application project's source folder from this file's compile-time path.
|
||||
/// </summary>
|
||||
/// <param name="thisFile">Filled in by the compiler.</param>
|
||||
/// <returns>The YKanBan project folder.</returns>
|
||||
private static string ApplicationSourceFolder([CallerFilePath] string thisFile = "") {
|
||||
DirectoryInfo? directory = new FileInfo(thisFile).Directory;
|
||||
while (directory is not null && !File.Exists(Path.Combine(directory.FullName, "YKanBan", "YKanBan.csproj"))) {
|
||||
directory = directory.Parent;
|
||||
}
|
||||
|
||||
Assert.IsNotNull(directory, "Repository root not found from the test source path.");
|
||||
return Path.Combine(directory.FullName, "YKanBan");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CodeBehindNeverUsesBareResourcesClassName() {
|
||||
string root = ApplicationSourceFolder();
|
||||
string[] files = Directory.GetFiles(root, "*.axaml.cs", SearchOption.AllDirectories)
|
||||
.Where(path => !path.Split(Path.DirectorySeparatorChar).Any(part => part is "obj" or "bin"))
|
||||
.ToArray();
|
||||
Assert.IsTrue(files.Length > 0, "No code-behind files found.");
|
||||
|
||||
var offenders = new List<string>();
|
||||
foreach (string file in files) {
|
||||
string[] lines = File.ReadAllLines(file);
|
||||
for (int index = 0; index < lines.Length; index++) {
|
||||
if (BareResourcesAccess().IsMatch(lines[index])) {
|
||||
offenders.Add($"{Path.GetRelativePath(root, file)}:{index + 1}: {lines[index].Trim()}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Assert.AreEqual(0, offenders.Count, "Use YKanBan.Resources in code-behind:" + Environment.NewLine + string.Join(Environment.NewLine, offenders));
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
using System.Globalization;
|
||||
using System.Text;
|
||||
|
||||
using YKanBan.Export;
|
||||
using YKanBan.Models;
|
||||
|
||||
@@ -14,8 +15,7 @@ namespace YKanBan.Tests.Export;
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
[DoNotParallelize]
|
||||
public class MarkdownExporterTests
|
||||
{
|
||||
public class MarkdownExporterTests {
|
||||
private static readonly DateTimeOffset ExportedAt = new(2026, 9, 30, 14, 25, 37, TimeSpan.Zero);
|
||||
|
||||
/// <summary>
|
||||
@@ -46,8 +46,7 @@ public class MarkdownExporterTests
|
||||
/// Builds the board fixture: one working column with two cards, one empty column and two tags.
|
||||
/// </summary>
|
||||
/// <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 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.
|
||||
/// </summary>
|
||||
/// <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();
|
||||
return MarkdownExporter.Export("MyRepo", columns, cards, tags, ExportedAt);
|
||||
}
|
||||
@@ -82,10 +80,9 @@ public class MarkdownExporterTests
|
||||
/// </summary>
|
||||
/// <param name="culture">The UI culture.</param>
|
||||
/// <returns>The expected Markdown document.</returns>
|
||||
private static string BuildExpected(CultureInfo culture)
|
||||
{
|
||||
string created = Local(2026, 9, 1, 10, 0).ToString(Resources.Export_CardTimePattern, culture);
|
||||
string updated = Local(2026, 9, 28, 18, 30).ToString(Resources.Export_CardTimePattern, culture);
|
||||
private static string BuildExpected(CultureInfo 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);
|
||||
|
||||
var builder = new StringBuilder();
|
||||
|
||||
@@ -133,38 +130,30 @@ public class MarkdownExporterTests
|
||||
/// Asserts that the exporter output matches the resource-built expected document.
|
||||
/// </summary>
|
||||
/// <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;
|
||||
try
|
||||
{
|
||||
try {
|
||||
Resources.Culture = culture;
|
||||
Assert.AreEqual(Normalize(BuildExpected(culture)), Normalize(ExportBoard()));
|
||||
}
|
||||
finally
|
||||
{
|
||||
} finally {
|
||||
Resources.Culture = original;
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void EnglishOutputMatchesTemplate()
|
||||
{
|
||||
public void EnglishOutputMatchesTemplate() {
|
||||
AssertOutputMatches(new CultureInfo("en"));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void ChineseOutputMatchesTemplate()
|
||||
{
|
||||
public void ChineseOutputMatchesTemplate() {
|
||||
AssertOutputMatches(new CultureInfo("zh-Hans"));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void FileNameFollowsLanguage()
|
||||
{
|
||||
public void FileNameFollowsLanguage() {
|
||||
CultureInfo? original = Resources.Culture;
|
||||
try
|
||||
{
|
||||
try {
|
||||
Resources.Culture = new CultureInfo("en");
|
||||
Assert.AreEqual(
|
||||
string.Format(Resources.Culture, Resources.Export_FileNamePattern, "MyRepo", ExportedAt),
|
||||
@@ -174,19 +163,15 @@ public class MarkdownExporterTests
|
||||
Assert.AreEqual(
|
||||
string.Format(Resources.Culture, Resources.Export_FileNamePattern, "MyRepo", ExportedAt),
|
||||
MarkdownExporter.BuildFileName("MyRepo", ExportedAt));
|
||||
}
|
||||
finally
|
||||
{
|
||||
} finally {
|
||||
Resources.Culture = original;
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TagTableCellsEscapePipesAndLineBreaks()
|
||||
{
|
||||
public void TagTableCellsEscapePipesAndLineBreaks() {
|
||||
CultureInfo? original = Resources.Culture;
|
||||
try
|
||||
{
|
||||
try {
|
||||
Resources.Culture = new CultureInfo("en");
|
||||
var tag = new TagModel(1, "a|b", RgbColor.Parse("#112233"), "first\nsecond");
|
||||
string markdown = MarkdownExporter.Export(
|
||||
@@ -196,10 +181,65 @@ public class MarkdownExporterTests
|
||||
[(tag, 0L)],
|
||||
ExportedAt);
|
||||
|
||||
StringAssert.Contains(markdown, "| a\\|b | #112233 | first second | 0 |");
|
||||
StringAssert.Contains(markdown, "| a\\|b | #112233 | first<br>second | 0 |");
|
||||
} finally {
|
||||
Resources.Culture = original;
|
||||
}
|
||||
finally
|
||||
{
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TagTableCellsEscapeBackslashes() {
|
||||
CultureInfo? original = Resources.Culture;
|
||||
try {
|
||||
Resources.Culture = new CultureInfo("en");
|
||||
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(
|
||||
"W",
|
||||
[new ColumnModel(1, "C", string.Empty, 1, 1)],
|
||||
[new CardModel(1, 1, "T", string.Empty, 1, 1, [tag])],
|
||||
[(tag, 1L)],
|
||||
ExportedAt);
|
||||
|
||||
StringAssert.Contains(markdown, "``a`b``");
|
||||
} finally {
|
||||
Resources.Culture = original;
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void FileNameDropsInvalidCharactersAndFallsBackToAppName() {
|
||||
CultureInfo? original = Resources.Culture;
|
||||
try {
|
||||
Resources.Culture = new CultureInfo("en");
|
||||
|
||||
// A drive root workspace name "D:\" must not leak ':' or '\' into the file name.
|
||||
string name = MarkdownExporter.BuildFileName("D:\\", ExportedAt);
|
||||
Assert.IsFalse(name.Contains(':'));
|
||||
Assert.IsFalse(name.Contains('\\'));
|
||||
|
||||
// A name made only of invalid characters falls back to the application name.
|
||||
string fallback = MarkdownExporter.BuildFileName("///", ExportedAt);
|
||||
StringAssert.StartsWith(fallback, Resources.App_Name);
|
||||
} finally {
|
||||
Resources.Culture = original;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,40 +1,85 @@
|
||||
using YKanBan.Launching;
|
||||
using YKanBan.Tests.TestUtilities;
|
||||
|
||||
namespace YKanBan.Tests.Launching;
|
||||
|
||||
/// <summary>
|
||||
/// Tests for the <c>ykanban <path></c> command-line contract across its
|
||||
/// three branches: no argument, one valid path, and invalid input.
|
||||
/// Tests for the <c>ykanban <path></c> command-line contract: exactly one
|
||||
/// existing folder, resolved to an absolute path; everything else is rejected.
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
public class LaunchArgumentsTests
|
||||
{
|
||||
public class LaunchArgumentsTests {
|
||||
[TestMethod]
|
||||
public void NoArgumentsIsRejected()
|
||||
{
|
||||
public void NoArgumentsIsRejected() {
|
||||
Assert.IsFalse(LaunchArguments.TryParse([], out string? path));
|
||||
Assert.IsNull(path);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void BlankArgumentIsRejected()
|
||||
{
|
||||
public void BlankArgumentIsRejected() {
|
||||
Assert.IsFalse(LaunchArguments.TryParse([" "], out string? path));
|
||||
Assert.IsNull(path);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void MoreThanOneArgumentIsRejected()
|
||||
{
|
||||
public void MoreThanOneArgumentIsRejected() {
|
||||
Assert.IsFalse(LaunchArguments.TryParse(["a", "b"], out string? path));
|
||||
Assert.IsNull(path);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void SinglePathIsAccepted()
|
||||
{
|
||||
bool parsed = LaunchArguments.TryParse([@"C:\Repo\MyProject"], out string? path);
|
||||
[DataRow("--help")]
|
||||
[DataRow("-x")]
|
||||
public void OptionLikeArgumentIsRejected(string argument) {
|
||||
Assert.IsFalse(LaunchArguments.TryParse([argument], out string? path));
|
||||
Assert.IsNull(path);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void NonExistentFolderIsRejected() {
|
||||
using var directory = new TempDirectory();
|
||||
string missing = Path.Combine(directory.FullPath, "nope");
|
||||
|
||||
Assert.IsFalse(LaunchArguments.TryParse([missing], out string? path));
|
||||
Assert.IsNull(path);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void FileInsteadOfFolderIsRejected() {
|
||||
using var directory = new TempDirectory();
|
||||
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(@"C:\Repo\MyProject", path);
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -7,11 +7,9 @@ namespace YKanBan.Tests.Models;
|
||||
/// boundary in both directions.
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
public class RgbColorTests
|
||||
{
|
||||
public class RgbColorTests {
|
||||
[TestMethod]
|
||||
public void ParseSplitsComponents()
|
||||
{
|
||||
public void ParseSplitsComponents() {
|
||||
RgbColor color = RgbColor.Parse("#102030");
|
||||
Assert.AreEqual((byte)0x10, color.R);
|
||||
Assert.AreEqual((byte)0x20, color.G);
|
||||
@@ -22,8 +20,7 @@ public class RgbColorTests
|
||||
[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));
|
||||
}
|
||||
|
||||
@@ -36,41 +33,35 @@ public class RgbColorTests
|
||||
[DataRow("#12345g")]
|
||||
[DataRow(" #112233")]
|
||||
[DataRow("#112233 ")]
|
||||
public void ParseRejectsMalformedText(string text)
|
||||
{
|
||||
public void ParseRejectsMalformedText(string text) {
|
||||
Assert.ThrowsExactly<FormatException>(() => RgbColor.Parse(text));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TryParseRejectsNull()
|
||||
{
|
||||
public void TryParseRejectsNull() {
|
||||
Assert.IsFalse(RgbColor.TryParse(null, out RgbColor color));
|
||||
Assert.AreEqual(default, color);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TryParseAcceptsValidText()
|
||||
{
|
||||
public void TryParseAcceptsValidText() {
|
||||
Assert.IsTrue(RgbColor.TryParse("#010203", out RgbColor color));
|
||||
Assert.AreEqual(new RgbColor(1, 2, 3), color);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void ToStringUsesCanonicalLowercase()
|
||||
{
|
||||
public void ToStringUsesCanonicalLowercase() {
|
||||
Assert.AreEqual("#ff0a00", new RgbColor(0xFF, 0x0A, 0x00).ToString());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TextRoundTrips()
|
||||
{
|
||||
public void TextRoundTrips() {
|
||||
var color = new RgbColor(0x12, 0xAB, 0xCD);
|
||||
Assert.AreEqual(color, RgbColor.Parse(color.ToString()));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void EqualityComparesComponents()
|
||||
{
|
||||
public void EqualityComparesComponents() {
|
||||
Assert.AreEqual(new RgbColor(1, 2, 3), new RgbColor(1, 2, 3));
|
||||
Assert.AreNotEqual(new RgbColor(1, 2, 3), new RgbColor(1, 2, 4));
|
||||
}
|
||||
|
||||
@@ -7,15 +7,13 @@ namespace YKanBan.Tests;
|
||||
/// application project and that the test runner can discover and execute tests.
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
public class ProjectReferenceTests
|
||||
{
|
||||
public class ProjectReferenceTests {
|
||||
/// <summary>
|
||||
/// Verifies that a type defined in the application assembly can be
|
||||
/// referenced from the test project.
|
||||
/// </summary>
|
||||
[TestMethod]
|
||||
public void ApplicationAssemblyIsReferenceable()
|
||||
{
|
||||
public void ApplicationAssemblyIsReferenceable() {
|
||||
Assert.IsNotNull(typeof(App));
|
||||
}
|
||||
}
|
||||
@@ -7,8 +7,7 @@ namespace YKanBan.Tests.Search;
|
||||
/// records compare by reference for their Terms collections by design (see the
|
||||
/// YYC MARK note in SearchNodes.cs), so tests provide equality explicitly.
|
||||
/// </summary>
|
||||
public sealed class SearchNodeComparer : IEqualityComparer<SearchNode>
|
||||
{
|
||||
public sealed class SearchNodeComparer : IEqualityComparer<SearchNode> {
|
||||
/// <summary>
|
||||
/// Gets the shared comparer instance.
|
||||
/// </summary>
|
||||
@@ -20,19 +19,15 @@ public sealed class SearchNodeComparer : IEqualityComparer<SearchNode>
|
||||
/// <param name="x">The first node.</param>
|
||||
/// <param name="y">The second node.</param>
|
||||
/// <returns><see langword="true"/> when the nodes are structurally equal.</returns>
|
||||
public bool Equals(SearchNode? x, SearchNode? y)
|
||||
{
|
||||
if (ReferenceEquals(x, y))
|
||||
{
|
||||
public bool Equals(SearchNode? x, SearchNode? y) {
|
||||
if (ReferenceEquals(x, y)) {
|
||||
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 (x, y) switch
|
||||
{
|
||||
return (x, y) switch {
|
||||
(SearchNode.Or a, SearchNode.Or 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,
|
||||
@@ -58,10 +53,8 @@ public sealed class SearchNodeComparer : IEqualityComparer<SearchNode>
|
||||
/// <param name="x">The first sequence.</param>
|
||||
/// <param name="y">The second sequence.</param>
|
||||
/// <returns><see langword="true"/> when both sequences match element-wise.</returns>
|
||||
private static bool SequencesEqual(IReadOnlyList<SearchNode> x, IReadOnlyList<SearchNode> y)
|
||||
{
|
||||
if (x.Count != y.Count)
|
||||
{
|
||||
private static bool SequencesEqual(IReadOnlyList<SearchNode> x, IReadOnlyList<SearchNode> y) {
|
||||
if (x.Count != y.Count) {
|
||||
return false;
|
||||
}
|
||||
return x.Zip(y).All(pair => Instance.Equals(pair.First, pair.Second));
|
||||
|
||||
@@ -8,15 +8,13 @@ namespace YKanBan.Tests.Search;
|
||||
/// <see cref="SearchSyntaxException"/>).
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
public class SearchQueryParserTests
|
||||
{
|
||||
public class SearchQueryParserTests {
|
||||
/// <summary>
|
||||
/// Parses and asserts structural equality against the expected AST.
|
||||
/// </summary>
|
||||
/// <param name="expected">The expected AST.</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);
|
||||
Assert.IsNotNull(parsed, $"Blank-looking input: '{text}'.");
|
||||
Assert.AreEqual(expected, parsed, SearchNodeComparer.Instance);
|
||||
@@ -26,53 +24,46 @@ public class SearchQueryParserTests
|
||||
/// Asserts that the input violates the grammar.
|
||||
/// </summary>
|
||||
/// <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));
|
||||
}
|
||||
|
||||
#region Successful parses
|
||||
|
||||
[TestMethod]
|
||||
public void BlankInputReturnsNull()
|
||||
{
|
||||
public void BlankInputReturnsNull() {
|
||||
Assert.IsNull(SearchQueryParser.Parse(string.Empty));
|
||||
Assert.IsNull(SearchQueryParser.Parse(" "));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void SingleWordIsFreeText()
|
||||
{
|
||||
public void SingleWordIsFreeText() {
|
||||
AssertParsesTo(new SearchNode.FreeText("login"), "login");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void AdjacentWordsAreImplicitAnd()
|
||||
{
|
||||
public void AdjacentWordsAreImplicitAnd() {
|
||||
AssertParsesTo(
|
||||
new SearchNode.And([new SearchNode.FreeText("fix"), new SearchNode.FreeText("login")]),
|
||||
"fix login");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void ExplicitAndKeyword()
|
||||
{
|
||||
public void ExplicitAndKeyword() {
|
||||
AssertParsesTo(
|
||||
new SearchNode.And([new SearchNode.FreeText("a"), new SearchNode.FreeText("b")]),
|
||||
"a AND b");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void OrKeyword()
|
||||
{
|
||||
public void OrKeyword() {
|
||||
AssertParsesTo(
|
||||
new SearchNode.Or([new SearchNode.FreeText("a"), new SearchNode.FreeText("b")]),
|
||||
"a OR b");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void ImplicitAndBindsTighterThanOr()
|
||||
{
|
||||
public void ImplicitAndBindsTighterThanOr() {
|
||||
AssertParsesTo(
|
||||
new SearchNode.Or([
|
||||
new SearchNode.And([new SearchNode.FreeText("a"), new SearchNode.FreeText("b")]),
|
||||
@@ -81,8 +72,7 @@ public class SearchQueryParserTests
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void ParenthesesForceGrouping()
|
||||
{
|
||||
public void ParenthesesForceGrouping() {
|
||||
AssertParsesTo(
|
||||
new SearchNode.And([
|
||||
new SearchNode.FreeText("a"),
|
||||
@@ -91,16 +81,14 @@ public class SearchQueryParserTests
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void NestedParenthesesCollapse()
|
||||
{
|
||||
public void NestedParenthesesCollapse() {
|
||||
AssertParsesTo(
|
||||
new SearchNode.Or([new SearchNode.FreeText("a"), new SearchNode.FreeText("b")]),
|
||||
"((a OR b))");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void LowercaseKeywordsArePlainWords()
|
||||
{
|
||||
public void LowercaseKeywordsArePlainWords() {
|
||||
AssertParsesTo(
|
||||
new SearchNode.And([
|
||||
new SearchNode.FreeText("a"),
|
||||
@@ -111,14 +99,12 @@ public class SearchQueryParserTests
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void PhraseIsFreeText()
|
||||
{
|
||||
public void PhraseIsFreeText() {
|
||||
AssertParsesTo(new SearchNode.FreeText("hello world"), "\"hello world\"");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void QuotedOperatorKeywordIsFreeText()
|
||||
{
|
||||
public void QuotedOperatorKeywordIsFreeText() {
|
||||
// A quoted AND/OR is literal text, not an operator.
|
||||
AssertParsesTo(new SearchNode.FreeText("AND"), "\"AND\"");
|
||||
AssertParsesTo(
|
||||
@@ -127,55 +113,54 @@ public class SearchQueryParserTests
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void PhraseSupportsEscapes()
|
||||
{
|
||||
public void PhraseSupportsEscapes() {
|
||||
// Escaped quote and escaped backslash.
|
||||
AssertParsesTo(new SearchNode.FreeText("a\"b"), "\"a\\\"b\"");
|
||||
AssertParsesTo(new SearchNode.FreeText("a\\b"), "\"a\\\\b\"");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TagQualifier()
|
||||
{
|
||||
public void TagQualifier() {
|
||||
AssertParsesTo(new SearchNode.TagName("bug"), "tag:bug");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TagQualifierAcceptsPhraseValue()
|
||||
{
|
||||
public void TagQualifierAcceptsPhraseValue() {
|
||||
AssertParsesTo(new SearchNode.TagName("a b"), "tag:\"a b\"");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void QualifierValueMayContainColons()
|
||||
{
|
||||
AssertParsesTo(new SearchNode.TagName("a:b"), "tag:a:b");
|
||||
public void QuotedQualifierValueMayContainColonsAndOperators() {
|
||||
AssertParsesTo(new SearchNode.TagName("a:b"), "tag:\"a:b\"");
|
||||
AssertParsesTo(new SearchNode.TagName("AND"), "tag:\"AND\"");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TitleAndContentQualifiers()
|
||||
{
|
||||
public void TitleAndContentQualifiers() {
|
||||
AssertParsesTo(new SearchNode.FieldText(SearchField.Title, "foo"), "title:foo");
|
||||
AssertParsesTo(new SearchNode.FieldText(SearchField.Content, "foo"), "content:foo");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void ColumnQualifierAcceptsPhraseValue()
|
||||
{
|
||||
public void ColumnQualifierAcceptsPhraseValue() {
|
||||
AssertParsesTo(new SearchNode.ColumnTitle("To Do"), "column:\"To Do\"");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void IdQualifierParsesNumber()
|
||||
{
|
||||
public void IdQualifierParsesNumber() {
|
||||
AssertParsesTo(new SearchNode.CardId(42), "id:42");
|
||||
AssertParsesTo(new SearchNode.CardId(12), "id:\"12\"");
|
||||
AssertParsesTo(new SearchNode.CardId(61), "id:#61");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void ColonWithoutKeyPrefixIsFreeText()
|
||||
{
|
||||
AssertParsesTo(new SearchNode.FreeText(":foo"), ":foo");
|
||||
public void QuotedTextWithColonIsFreeText() {
|
||||
AssertParsesTo(new SearchNode.FreeText("http://x"), "\"http://x\"");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void WordMayContainHashAndPunctuation() {
|
||||
AssertParsesTo(new SearchNode.FreeText("#61"), "#61");
|
||||
AssertParsesTo(new SearchNode.FreeText("c#/.net"), "c#/.net");
|
||||
}
|
||||
|
||||
#endregion
|
||||
@@ -183,106 +168,165 @@ public class SearchQueryParserTests
|
||||
#region Strict failures
|
||||
|
||||
[TestMethod]
|
||||
public void UnterminatedPhraseIsAnError()
|
||||
{
|
||||
public void UnterminatedPhraseIsAnError() {
|
||||
AssertSyntaxError("\"abc def");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TrailingUnterminatedPhraseIsAnError()
|
||||
{
|
||||
public void TrailingUnterminatedPhraseIsAnError() {
|
||||
AssertSyntaxError("a \"abc");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void InvalidEscapeInPhraseIsAnError()
|
||||
{
|
||||
public void InvalidEscapeInPhraseIsAnError() {
|
||||
// A bare backslash (not followed by a quote or another backslash) is invalid.
|
||||
AssertSyntaxError("\"a\\b\"");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void InvalidEscapeInQualifierPhraseIsAnError()
|
||||
{
|
||||
public void InvalidEscapeInQualifierPhraseIsAnError() {
|
||||
AssertSyntaxError("tag:\"a\\x\"");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void UnbalancedOpenParenIsAnError()
|
||||
{
|
||||
public void UnbalancedOpenParenIsAnError() {
|
||||
AssertSyntaxError("(a");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void StrayCloseParenIsAnError()
|
||||
{
|
||||
public void StrayCloseParenIsAnError() {
|
||||
AssertSyntaxError("a)");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void EmptyParensAreAnError()
|
||||
{
|
||||
public void EmptyParensAreAnError() {
|
||||
AssertSyntaxError("()");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void DanglingOrIsAnError()
|
||||
{
|
||||
public void DanglingOrIsAnError() {
|
||||
AssertSyntaxError("a OR");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void DanglingAndIsAnError()
|
||||
{
|
||||
public void DanglingAndIsAnError() {
|
||||
AssertSyntaxError("a AND");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void LeadingAndIsAnError()
|
||||
{
|
||||
public void LeadingAndIsAnError() {
|
||||
AssertSyntaxError("AND a");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void OperatorAtOperandPositionIsAnError()
|
||||
{
|
||||
public void OperatorAtOperandPositionIsAnError() {
|
||||
AssertSyntaxError("a AND OR b");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void QualifierWithoutValueIsAnError()
|
||||
{
|
||||
public void QualifierWithoutValueIsAnError() {
|
||||
AssertSyntaxError("tag:");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void SpacedQualifierValueIsAnError()
|
||||
{
|
||||
public void SpacedQualifierValueIsAnError() {
|
||||
AssertSyntaxError("tag: bug");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void NonNumericIdIsAnError()
|
||||
{
|
||||
AssertSyntaxError("id:12x");
|
||||
[DataRow("tag: \"x\"")]
|
||||
[DataRow("title: \"a b\"")]
|
||||
public void SpacedQualifierPhraseValueIsAnError(string text) {
|
||||
AssertSyntaxError(text);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void UnknownQualifierKeyIsAnError()
|
||||
{
|
||||
[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]
|
||||
[DataRow("id:12x")]
|
||||
[DataRow("id:abc")]
|
||||
[DataRow("id:0")]
|
||||
[DataRow("id:-1")]
|
||||
[DataRow("id:+1")]
|
||||
[DataRow("id:#")]
|
||||
[DataRow("id:##1")]
|
||||
[DataRow("id:1.5")]
|
||||
[DataRow("id:٣")]
|
||||
[DataRow("id:99999999999999999999")]
|
||||
public void InvalidIdValueIsAnError(string text) {
|
||||
AssertSyntaxError(text);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void QuotedIdValueIsAnError() {
|
||||
AssertSyntaxError("id:\"61\"");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[DataRow("tag:AND")]
|
||||
[DataRow("tag:OR")]
|
||||
[DataRow("title:AND")]
|
||||
public void BareOperatorAsQualifierValueIsAnError(string text) {
|
||||
AssertSyntaxError(text);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void UnquotedQualifierValueWithColonIsAnError() {
|
||||
AssertSyntaxError("tag:a:b");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[DataRow(":foo")]
|
||||
[DataRow("http://x")]
|
||||
[DataRow("a:")]
|
||||
public void ColonAfterNonKeyIsAnError(string text) {
|
||||
AssertSyntaxError(text);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[DataRow("a\\b")]
|
||||
[DataRow("\\")]
|
||||
[DataRow("tag:a\\b")]
|
||||
public void BackslashInBareWordIsAnError(string text) {
|
||||
AssertSyntaxError(text);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void UnknownQualifierKeyIsAnError() {
|
||||
AssertSyntaxError("foo:bar");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void QualifierKeysAreCaseSensitive()
|
||||
{
|
||||
public void QualifierKeysAreCaseSensitive() {
|
||||
// "Tag" is a key-like prefix but not the known lowercase "tag", so it is unknown.
|
||||
AssertSyntaxError("Tag:x");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void SyntaxErrorCarriesDescriptiveMessage()
|
||||
{
|
||||
public void SyntaxErrorCarriesDescriptiveMessage() {
|
||||
SearchSyntaxException exception = Assert.ThrowsExactly<SearchSyntaxException>(
|
||||
() => SearchQueryParser.Parse("a AND"));
|
||||
Assert.IsFalse(string.IsNullOrEmpty(exception.Message));
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
using Microsoft.Data.Sqlite;
|
||||
|
||||
using YKanBan.Search;
|
||||
using YKanBan.Storage.Workspace;
|
||||
using YKanBan.Tests.TestUtilities;
|
||||
@@ -10,31 +11,29 @@ namespace YKanBan.Tests.Search;
|
||||
/// workspace database.
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
public class SearchSqlCompilerTests
|
||||
{
|
||||
public class SearchSqlCompilerTests {
|
||||
/// <summary>
|
||||
/// Owns a workspace with a fixed card/tag fixture.
|
||||
/// </summary>
|
||||
private sealed class SearchFixture : IDisposable
|
||||
{
|
||||
private sealed class SearchFixture : IDisposable {
|
||||
public TempDirectory Directory { get; } = new();
|
||||
|
||||
public SqliteConnection Connection { get; }
|
||||
|
||||
public SearchFixture()
|
||||
{
|
||||
public SearchFixture() {
|
||||
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".
|
||||
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 ('Archive', '', 1, 1);");
|
||||
|
||||
// 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 (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 (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.
|
||||
SqliteTestHelper.Exec(setup, "INSERT INTO tags (name, color, description) VALUES ('Bug', '#ff0000', '');");
|
||||
@@ -54,38 +53,33 @@ public class SearchSqlCompilerTests
|
||||
/// </summary>
|
||||
/// <param name="queryText">The search text.</param>
|
||||
/// <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);
|
||||
Assert.IsNotNull(query, "Blank fixture queries are not expected here.");
|
||||
CompiledSearch compiled = SearchSqlCompiler.Compile(query);
|
||||
|
||||
using var command = Connection.CreateCommand();
|
||||
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);
|
||||
}
|
||||
using var reader = command.ExecuteReader();
|
||||
|
||||
var ids = new List<long>();
|
||||
while (reader.Read())
|
||||
{
|
||||
while (reader.Read()) {
|
||||
ids.Add(reader.GetInt64(0));
|
||||
}
|
||||
return ids;
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
public void Dispose() {
|
||||
Connection.Dispose();
|
||||
Directory.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void FreeTextMatchesTitleOrContentCaseInsensitively()
|
||||
{
|
||||
public void FreeTextMatchesTitleOrContentCaseInsensitively() {
|
||||
using var fixture = new SearchFixture();
|
||||
CollectionAssert.AreEqual(new[] { 2L }, fixture.Search("apple"));
|
||||
CollectionAssert.AreEqual(new[] { 1L }, fixture.Search("login"));
|
||||
@@ -94,8 +88,7 @@ public class SearchSqlCompilerTests
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void FieldQualifiersScopeToTheirField()
|
||||
{
|
||||
public void FieldQualifiersScopeToTheirField() {
|
||||
using var fixture = new SearchFixture();
|
||||
CollectionAssert.AreEqual(new[] { 2L }, fixture.Search("title:apple"));
|
||||
CollectionAssert.AreEqual(new[] { 3L }, fixture.Search("content:banana"));
|
||||
@@ -103,8 +96,7 @@ public class SearchSqlCompilerTests
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TagQualifierMatchesExactlyAndCaseInsensitively()
|
||||
{
|
||||
public void TagQualifierMatchesExactlyAndCaseInsensitively() {
|
||||
using var fixture = new SearchFixture();
|
||||
CollectionAssert.AreEqual(new[] { 1L }, fixture.Search("tag:bug"));
|
||||
CollectionAssert.AreEqual(new[] { 2L, 3L }, fixture.Search("tag:ui"));
|
||||
@@ -116,8 +108,7 @@ public class SearchSqlCompilerTests
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void ColumnQualifierMatchesColumnTitleExactly()
|
||||
{
|
||||
public void ColumnQualifierMatchesColumnTitleExactly() {
|
||||
using var fixture = new SearchFixture();
|
||||
CollectionAssert.AreEqual(new[] { 1L, 4L }, fixture.Search("column:\"to do\""));
|
||||
CollectionAssert.AreEqual(new[] { 2L, 3L }, fixture.Search("column:\"in progress\""));
|
||||
@@ -128,16 +119,14 @@ public class SearchSqlCompilerTests
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void IdQualifierMatchesExactly()
|
||||
{
|
||||
public void IdQualifierMatchesExactly() {
|
||||
using var fixture = new SearchFixture();
|
||||
CollectionAssert.AreEqual(new[] { 3L }, fixture.Search("id:3"));
|
||||
Assert.AreEqual(0, fixture.Search("id:99").Count);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void AndOrCombination()
|
||||
{
|
||||
public void AndOrCombination() {
|
||||
using var fixture = new SearchFixture();
|
||||
CollectionAssert.AreEqual(new[] { 2L, 3L }, fixture.Search("apple OR banana"));
|
||||
CollectionAssert.AreEqual(new[] { 2L }, fixture.Search("apple AND id:2"));
|
||||
@@ -145,8 +134,7 @@ public class SearchSqlCompilerTests
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void ParenthesizedGrouping()
|
||||
{
|
||||
public void ParenthesizedGrouping() {
|
||||
using var fixture = new SearchFixture();
|
||||
|
||||
// (apple OR banana) hits cards 2,3; intersected with column "In Progress" (2,3).
|
||||
@@ -157,22 +145,27 @@ public class SearchSqlCompilerTests
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void LikeWildcardsInUserTextMatchLiterally()
|
||||
{
|
||||
public void PercentAndUnderscoreInUserTextMatchLiterally() {
|
||||
using var fixture = new SearchFixture();
|
||||
CollectionAssert.AreEqual(new[] { 4L }, fixture.Search("100%"));
|
||||
CollectionAssert.AreEqual(new[] { 4L }, fixture.Search("a_b"));
|
||||
}
|
||||
|
||||
[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"));
|
||||
|
||||
StringAssert.Contains(compiled.Predicate, "$p0");
|
||||
StringAssert.Contains(compiled.Predicate, "$p1");
|
||||
Assert.AreEqual(2, compiled.Parameters.Count);
|
||||
Assert.AreEqual("%x%", compiled.Parameters[0].Value);
|
||||
Assert.AreEqual("%x%", compiled.Parameters[1].Value);
|
||||
Assert.AreEqual(1, compiled.Parameters.Count);
|
||||
Assert.AreEqual("x", compiled.Parameters[0].Value);
|
||||
}
|
||||
}
|
||||
@@ -8,11 +8,9 @@ namespace YKanBan.Tests.Storage.AppData;
|
||||
/// degradation on a missing or corrupt file.
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
public class AppConfigStoreTests
|
||||
{
|
||||
public class AppConfigStoreTests {
|
||||
[TestMethod]
|
||||
public void LoadMissingFileReturnsDefaults()
|
||||
{
|
||||
public void LoadMissingFileReturnsDefaults() {
|
||||
using var directory = new TempDirectory();
|
||||
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.DefaultLanguage, config.Language);
|
||||
Assert.AreEqual(ThemeOption.FollowSystem, config.Theme);
|
||||
Assert.AreEqual(CardSortOption.Id, config.Sort.Card);
|
||||
Assert.AreEqual(ColumnWidthPreset.Standard, config.ColumnWidth.Preset);
|
||||
Assert.AreEqual(320, config.ColumnWidth.CustomPixels);
|
||||
Assert.AreEqual(SortOption.IdAscending, config.Display.CardSort);
|
||||
Assert.AreEqual(SortOption.IdAscending, config.Display.ColumnSort);
|
||||
Assert.AreEqual(ColumnWidthPreset.Standard, config.Display.ColumnWidth.Preset);
|
||||
Assert.AreEqual(320, config.Display.ColumnWidth.CustomPixels);
|
||||
Assert.IsTrue(config.Confirmations.DeleteCard);
|
||||
Assert.IsTrue(config.Confirmations.DeleteColumn);
|
||||
Assert.IsTrue(config.Confirmations.DeleteTag);
|
||||
@@ -31,8 +30,7 @@ public class AppConfigStoreTests
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void LoadCorruptFileBacksUpAndReturnsDefaults()
|
||||
{
|
||||
public void LoadCorruptFileBacksUpAndReturnsDefaults() {
|
||||
using var directory = new TempDirectory();
|
||||
string path = Path.Combine(directory.FullPath, "app.json");
|
||||
File.WriteAllText(path, "{ this is not valid json");
|
||||
@@ -46,8 +44,7 @@ public class AppConfigStoreTests
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void LoadJsonNullReturnsDefaults()
|
||||
{
|
||||
public void LoadJsonNullReturnsDefaults() {
|
||||
using var directory = new TempDirectory();
|
||||
string path = Path.Combine(directory.FullPath, "app.json");
|
||||
File.WriteAllText(path, "null");
|
||||
@@ -57,8 +54,40 @@ public class AppConfigStoreTests
|
||||
}
|
||||
|
||||
[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();
|
||||
string path = Path.Combine(directory.FullPath, "app.json");
|
||||
File.WriteAllText(path, $$"""
|
||||
@@ -66,8 +95,11 @@ public class AppConfigStoreTests
|
||||
"version": {{AppConfig.CurrentFormatVersion}},
|
||||
"language": "zh-Hans",
|
||||
"theme": "dark",
|
||||
"sort": { "card": "title" },
|
||||
"column-width": { "preset": "custom", "custom-pixels": 400 },
|
||||
"display": {
|
||||
"column-width": { "preset": "custom", "custom-pixels": 400 },
|
||||
"card-sort": "title-asc",
|
||||
"column-sort": "id-desc"
|
||||
},
|
||||
"confirmations": {
|
||||
"delete-card": false,
|
||||
"delete-column": false,
|
||||
@@ -82,9 +114,10 @@ public class AppConfigStoreTests
|
||||
|
||||
Assert.AreEqual("zh-Hans", config.Language);
|
||||
Assert.AreEqual(ThemeOption.Dark, config.Theme);
|
||||
Assert.AreEqual(CardSortOption.Title, config.Sort.Card);
|
||||
Assert.AreEqual(ColumnWidthPreset.Custom, config.ColumnWidth.Preset);
|
||||
Assert.AreEqual(400, config.ColumnWidth.CustomPixels);
|
||||
Assert.AreEqual(SortOption.TitleAscending, config.Display.CardSort);
|
||||
Assert.AreEqual(SortOption.IdDescending, config.Display.ColumnSort);
|
||||
Assert.AreEqual(ColumnWidthPreset.Custom, config.Display.ColumnWidth.Preset);
|
||||
Assert.AreEqual(400, config.Display.ColumnWidth.CustomPixels);
|
||||
Assert.IsFalse(config.Confirmations.DeleteCard);
|
||||
Assert.IsFalse(config.Confirmations.DeleteColumn);
|
||||
Assert.IsFalse(config.Confirmations.DeleteTag);
|
||||
@@ -92,8 +125,7 @@ public class AppConfigStoreTests
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void LoadMissingSectionsFillsDefaults()
|
||||
{
|
||||
public void LoadMissingSectionsFillsDefaults() {
|
||||
using var directory = new TempDirectory();
|
||||
string path = Path.Combine(directory.FullPath, "app.json");
|
||||
File.WriteAllText(path, $$"""{ "version": {{AppConfig.CurrentFormatVersion}} }""");
|
||||
@@ -101,24 +133,25 @@ public class AppConfigStoreTests
|
||||
|
||||
AppConfig config = store.Load();
|
||||
|
||||
Assert.IsNotNull(config.Sort);
|
||||
Assert.IsNotNull(config.ColumnWidth);
|
||||
Assert.IsNotNull(config.Display);
|
||||
Assert.IsNotNull(config.Display.ColumnWidth);
|
||||
Assert.IsNotNull(config.Confirmations);
|
||||
Assert.AreEqual(ColumnWidthPreset.Standard, config.ColumnWidth.Preset);
|
||||
Assert.AreEqual(ColumnWidthPreset.Standard, config.Display.ColumnWidth.Preset);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void SaveWritesKebabCaseKeysAndEnumValues()
|
||||
{
|
||||
public void SaveWritesKebabCaseKeysAndEnumValues() {
|
||||
using var directory = new TempDirectory();
|
||||
string path = Path.Combine(directory.FullPath, "app.json");
|
||||
var store = new AppConfigStore(path);
|
||||
|
||||
var config = new AppConfig
|
||||
{
|
||||
var config = new AppConfig {
|
||||
Theme = ThemeOption.FollowSystem,
|
||||
Sort = new SortSettings { Card = CardSortOption.UpdatedAt },
|
||||
ColumnWidth = new ColumnWidthSettings { Preset = ColumnWidthPreset.Custom, CustomPixels = 500 },
|
||||
Display = new DisplaySettings {
|
||||
CardSort = SortOption.UpdatedDescending,
|
||||
ColumnSort = SortOption.CreatedAscending,
|
||||
ColumnWidth = new ColumnWidthSettings { Preset = ColumnWidthPreset.Custom, CustomPixels = 500 },
|
||||
},
|
||||
Confirmations = new ConfirmationSettings { DeleteColumn = false },
|
||||
};
|
||||
store.Save(config);
|
||||
@@ -126,27 +159,31 @@ public class AppConfigStoreTests
|
||||
string json = File.ReadAllText(path);
|
||||
StringAssert.Contains(json, "\"delete-column\"");
|
||||
StringAssert.Contains(json, "\"discard-edit\"");
|
||||
StringAssert.Contains(json, "\"card-sort\"");
|
||||
StringAssert.Contains(json, "\"column-sort\"");
|
||||
StringAssert.Contains(json, "\"custom-pixels\"");
|
||||
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.
|
||||
Assert.IsFalse(json.Contains("deleteColumn", StringComparison.Ordinal));
|
||||
Assert.IsFalse(json.Contains("CustomPixels", StringComparison.Ordinal));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void SaveThenLoadRoundTrips()
|
||||
{
|
||||
public void SaveThenLoadRoundTrips() {
|
||||
using var directory = new TempDirectory();
|
||||
string path = Path.Combine(directory.FullPath, "app.json");
|
||||
var store = new AppConfigStore(path);
|
||||
|
||||
var config = new AppConfig
|
||||
{
|
||||
var config = new AppConfig {
|
||||
Language = "zh-Hans",
|
||||
Theme = ThemeOption.Light,
|
||||
Sort = new SortSettings { Card = CardSortOption.CreatedAt },
|
||||
ColumnWidth = new ColumnWidthSettings { Preset = ColumnWidthPreset.Wide },
|
||||
Display = new DisplaySettings {
|
||||
CardSort = SortOption.CreatedDescending,
|
||||
ColumnSort = SortOption.TitleAscending,
|
||||
ColumnWidth = new ColumnWidthSettings { Preset = ColumnWidthPreset.Wide },
|
||||
},
|
||||
Confirmations = new ConfirmationSettings { DiscardEdit = false },
|
||||
};
|
||||
store.Save(config);
|
||||
@@ -154,8 +191,9 @@ public class AppConfigStoreTests
|
||||
AppConfig reloaded = store.Load();
|
||||
Assert.AreEqual(config.Language, reloaded.Language);
|
||||
Assert.AreEqual(config.Theme, reloaded.Theme);
|
||||
Assert.AreEqual(config.Sort.Card, reloaded.Sort.Card);
|
||||
Assert.AreEqual(config.ColumnWidth.Preset, reloaded.ColumnWidth.Preset);
|
||||
Assert.AreEqual(config.Display.CardSort, reloaded.Display.CardSort);
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
using Microsoft.Data.Sqlite;
|
||||
|
||||
using YKanBan.Storage;
|
||||
using YKanBan.Storage.Workspace;
|
||||
using YKanBan.Tests.TestUtilities;
|
||||
@@ -10,11 +11,9 @@ namespace YKanBan.Tests.Storage;
|
||||
/// user_version-driven migration runner.
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
public class SqliteDatabaseTests
|
||||
{
|
||||
public class SqliteDatabaseTests {
|
||||
[TestMethod]
|
||||
public void OpenAppliesMandatoryPragmas()
|
||||
{
|
||||
public void OpenAppliesMandatoryPragmas() {
|
||||
using var directory = new TempDirectory();
|
||||
string databasePath = Path.Combine(directory.FullPath, "pragmas.db");
|
||||
|
||||
@@ -25,8 +24,7 @@ public class SqliteDatabaseTests
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void OpenSetsUserVersionToLatestMigration()
|
||||
{
|
||||
public void OpenSetsUserVersionToLatestMigration() {
|
||||
using var directory = new TempDirectory();
|
||||
string databasePath = Path.Combine(directory.FullPath, "version.db");
|
||||
|
||||
@@ -35,13 +33,11 @@ public class SqliteDatabaseTests
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void ReopenKeepsWalJournalMode()
|
||||
{
|
||||
public void ReopenKeepsWalJournalMode() {
|
||||
using var directory = new TempDirectory();
|
||||
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.
|
||||
@@ -50,14 +46,12 @@ public class SqliteDatabaseTests
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void OpenRejectsNewerStoredSchemaVersion()
|
||||
{
|
||||
public void OpenRejectsNewerStoredSchemaVersion() {
|
||||
using var directory = new TempDirectory();
|
||||
string databasePath = Path.Combine(directory.FullPath, "newer.db");
|
||||
|
||||
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};");
|
||||
}
|
||||
|
||||
@@ -68,8 +62,7 @@ public class SqliteDatabaseTests
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void OpenRejectsNonContiguousMigrationList()
|
||||
{
|
||||
public void OpenRejectsNonContiguousMigrationList() {
|
||||
using var directory = new TempDirectory();
|
||||
string databasePath = Path.Combine(directory.FullPath, "gap.db");
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
using Microsoft.Data.Sqlite;
|
||||
|
||||
using YKanBan.Storage;
|
||||
using YKanBan.Storage.Workspace;
|
||||
using YKanBan.Tests.TestUtilities;
|
||||
@@ -11,11 +12,9 @@ namespace YKanBan.Tests.Storage.Workspace;
|
||||
/// content.
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
public class WorkspaceInitializerTests
|
||||
{
|
||||
public class WorkspaceInitializerTests {
|
||||
[TestMethod]
|
||||
public void IsWorkspaceReflectsInitializationState()
|
||||
{
|
||||
public void IsWorkspaceReflectsInitializationState() {
|
||||
using var directory = new TempDirectory();
|
||||
Assert.IsFalse(WorkspaceInitializer.IsWorkspace(directory.FullPath));
|
||||
|
||||
@@ -24,8 +23,7 @@ public class WorkspaceInitializerTests
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void InitializeCreatesStructureAndMigratedEmptyDatabase()
|
||||
{
|
||||
public void InitializeCreatesStructureAndMigratedEmptyDatabase() {
|
||||
using var directory = new TempDirectory();
|
||||
WorkspaceInitializer.Initialize(directory.FullPath);
|
||||
|
||||
@@ -43,8 +41,7 @@ public class WorkspaceInitializerTests
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void InitializeMissingFolderThrows()
|
||||
{
|
||||
public void InitializeMissingFolderThrows() {
|
||||
using var directory = new TempDirectory();
|
||||
string missing = Path.Combine(directory.FullPath, "not-created");
|
||||
|
||||
@@ -54,8 +51,7 @@ public class WorkspaceInitializerTests
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void InitializeTwiceThrows()
|
||||
{
|
||||
public void InitializeTwiceThrows() {
|
||||
using var directory = new TempDirectory();
|
||||
WorkspaceInitializer.Initialize(directory.FullPath);
|
||||
|
||||
|
||||
@@ -5,14 +5,12 @@ using YKanBan.Tests.TestUtilities;
|
||||
namespace YKanBan.Tests.Storage.Workspace;
|
||||
|
||||
/// <summary>
|
||||
/// Tests for exclusive lock acquisition, diagnostics and release.
|
||||
/// Tests for exclusive lock acquisition and release.
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
public class WorkspaceLockTests
|
||||
{
|
||||
public class WorkspaceLockTests {
|
||||
[TestMethod]
|
||||
public void AcquireThenDisposeThenAcquireAgainSucceeds()
|
||||
{
|
||||
public void AcquireThenDisposeThenAcquireAgainSucceeds() {
|
||||
using var directory = new TempDirectory();
|
||||
WorkspaceInitializer.Initialize(directory.FullPath);
|
||||
|
||||
@@ -22,8 +20,7 @@ public class WorkspaceLockTests
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void SecondAcquireWhileHeldThrows()
|
||||
{
|
||||
public void SecondAcquireWhileHeldThrows() {
|
||||
using var directory = new TempDirectory();
|
||||
WorkspaceInitializer.Initialize(directory.FullPath);
|
||||
|
||||
@@ -34,26 +31,21 @@ public class WorkspaceLockTests
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void AcquireWithoutYkanbanThrowsNotInitialized()
|
||||
{
|
||||
public void AcquireWithoutYkanbanThrowsNotInitialized() {
|
||||
using var directory = new TempDirectory();
|
||||
Assert.ThrowsExactly<WorkspaceNotInitializedException>(
|
||||
() => WorkspaceLock.Acquire(directory.FullPath));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void LockFileContainsHolderDiagnosticsAfterRelease()
|
||||
{
|
||||
public void LockFileIsEmptyAfterRelease() {
|
||||
using var directory = new TempDirectory();
|
||||
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.
|
||||
string content = File.ReadAllText(WorkspacePaths.LockFile(directory.FullPath));
|
||||
StringAssert.Contains(content, "pid=");
|
||||
StringAssert.Contains(content, $"machine={Environment.MachineName}");
|
||||
// The lock file survives release but carries no content; only the OS handle matters.
|
||||
Assert.AreEqual(0L, new FileInfo(WorkspacePaths.LockFile(directory.FullPath)).Length);
|
||||
}
|
||||
}
|
||||
@@ -1,98 +1,139 @@
|
||||
using System.Globalization;
|
||||
|
||||
using Microsoft.Data.Sqlite;
|
||||
|
||||
using YKanBan.Storage.Workspace;
|
||||
using YKanBan.Tests.TestUtilities;
|
||||
|
||||
namespace YKanBan.Tests.Storage.Workspace;
|
||||
|
||||
/// <summary>
|
||||
/// Verifies that the preset column titles follow the UI language active when
|
||||
/// they are added and then live as ordinary data. These tests mutate the
|
||||
/// global <see cref="Resources.Culture"/>, so they are marked do-not-parallelize.
|
||||
/// 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 global
|
||||
/// <see cref="Resources.Culture"/>, so they are marked do-not-parallelize.
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
[DoNotParallelize]
|
||||
public class WorkspacePresetTests
|
||||
{
|
||||
public class WorkspacePresetTests {
|
||||
[TestMethod]
|
||||
public void AddPresetColumnsStoresEnglishTitlesUnderEnglishCulture()
|
||||
{
|
||||
public void AddPresetColumnsStoresEnglishTextUnderEnglishCulture() {
|
||||
CultureInfo? original = Resources.Culture;
|
||||
try
|
||||
{
|
||||
try {
|
||||
Resources.Culture = new CultureInfo("en");
|
||||
string[] expected =
|
||||
[
|
||||
Resources.PresetColumn_Todo,
|
||||
Resources.PresetColumn_InProgress,
|
||||
Resources.PresetColumn_Done,
|
||||
];
|
||||
|
||||
using var directory = new TempDirectory();
|
||||
WorkspaceInitializer.Initialize(directory.FullPath);
|
||||
WorkspacePreset.AddPresetColumns(directory.FullPath);
|
||||
|
||||
using SqliteConnection connection = SqliteTestHelper.OpenWorkspace(directory.FullPath);
|
||||
CollectionAssert.AreEqual(expected, SqliteTestHelper.GetColumnTitles(connection));
|
||||
}
|
||||
finally
|
||||
{
|
||||
CollectionAssert.AreEqual(
|
||||
new[]
|
||||
{
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void AddPresetColumnsStoresChineseTitlesUnderChineseCulture()
|
||||
{
|
||||
public void AddPresetColumnsStoresChineseTextUnderChineseCulture() {
|
||||
CultureInfo? original = Resources.Culture;
|
||||
try
|
||||
{
|
||||
try {
|
||||
Resources.Culture = new CultureInfo("zh-Hans");
|
||||
string[] expected =
|
||||
[
|
||||
Resources.PresetColumn_Todo,
|
||||
Resources.PresetColumn_InProgress,
|
||||
Resources.PresetColumn_Done,
|
||||
];
|
||||
|
||||
using var directory = new TempDirectory();
|
||||
WorkspaceInitializer.Initialize(directory.FullPath);
|
||||
WorkspacePreset.AddPresetColumns(directory.FullPath);
|
||||
|
||||
using SqliteConnection connection = SqliteTestHelper.OpenWorkspace(directory.FullPath);
|
||||
CollectionAssert.AreEqual(expected, SqliteTestHelper.GetColumnTitles(connection));
|
||||
}
|
||||
finally
|
||||
{
|
||||
CollectionAssert.AreEqual(
|
||||
new[]
|
||||
{
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void PresetTitlesAreDataAndIgnoreLaterCultureChanges()
|
||||
{
|
||||
public void AddPresetTagsStoresEightTagsUnderEnglishCulture() {
|
||||
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");
|
||||
string[] expected =
|
||||
[
|
||||
Resources.PresetColumn_Todo,
|
||||
Resources.PresetColumn_InProgress,
|
||||
Resources.PresetColumn_Done,
|
||||
];
|
||||
|
||||
using var directory = new TempDirectory();
|
||||
WorkspaceInitializer.Initialize(directory.FullPath);
|
||||
WorkspacePreset.AddPresetColumns(directory.FullPath);
|
||||
WorkspacePreset.AddPresetTags(directory.FullPath);
|
||||
|
||||
// Switching the language after adding the presets must not rewrite stored data.
|
||||
Resources.Culture = new CultureInfo("zh-Hans");
|
||||
using SqliteConnection connection = SqliteTestHelper.OpenWorkspace(directory.FullPath);
|
||||
CollectionAssert.AreEqual(expected, SqliteTestHelper.GetColumnTitles(connection));
|
||||
}
|
||||
finally
|
||||
{
|
||||
Assert.AreEqual("To Do", SqliteTestHelper.GetColumnTitles(connection)[0]);
|
||||
Assert.AreEqual("bug", SqliteTestHelper.GetTags(connection)[0].Name);
|
||||
} finally {
|
||||
Resources.Culture = original;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
using Microsoft.Data.Sqlite;
|
||||
|
||||
using YKanBan.Models;
|
||||
using YKanBan.Search;
|
||||
using YKanBan.Storage.Workspace;
|
||||
using YKanBan.Tests.TestUtilities;
|
||||
|
||||
@@ -10,16 +12,14 @@ namespace YKanBan.Tests.Storage.Workspace;
|
||||
/// transaction atomicity and the timestamp refresh rules.
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
public class WorkspaceRepositoryTests
|
||||
{
|
||||
public class WorkspaceRepositoryTests {
|
||||
/// <summary>
|
||||
/// Owns a workspace with fixed-timestamp fixture data (one column, one
|
||||
/// card, two tags linked to the card) plus the repository under test.
|
||||
/// Fixture timestamps are small literal values so that any real write,
|
||||
/// which stamps the current Unix time, is observable.
|
||||
/// </summary>
|
||||
private sealed class RepositoryFixture : IDisposable
|
||||
{
|
||||
private sealed class RepositoryFixture : IDisposable {
|
||||
public TempDirectory Directory { get; } = new();
|
||||
|
||||
public WorkspaceRepository Repository { get; }
|
||||
@@ -32,12 +32,10 @@ public class WorkspaceRepositoryTests
|
||||
|
||||
public long UiTagId { get; } = 2;
|
||||
|
||||
public RepositoryFixture()
|
||||
{
|
||||
public RepositoryFixture() {
|
||||
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 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', '');");
|
||||
@@ -49,16 +47,14 @@ public class WorkspaceRepositoryTests
|
||||
Repository = new WorkspaceRepository(Directory.FullPath);
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
public void Dispose() {
|
||||
Repository.Dispose();
|
||||
Directory.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void GetColumnsReturnsTheSeededColumn()
|
||||
{
|
||||
public void GetColumnsReturnsTheSeededColumn() {
|
||||
using var fixture = new RepositoryFixture();
|
||||
ColumnModel column = fixture.Repository.GetColumn(fixture.ColumnId)!;
|
||||
Assert.AreEqual("Col", column.Title);
|
||||
@@ -66,8 +62,7 @@ public class WorkspaceRepositoryTests
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void AddColumnSetsEqualTimestamps()
|
||||
{
|
||||
public void AddColumnSetsEqualTimestamps() {
|
||||
using var fixture = new RepositoryFixture();
|
||||
ColumnModel column = fixture.Repository.AddColumn("New", "desc");
|
||||
Assert.IsTrue(column.CreatedAt > 0L);
|
||||
@@ -75,8 +70,7 @@ public class WorkspaceRepositoryTests
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void UpdateColumnWithoutChangeWritesNothing()
|
||||
{
|
||||
public void UpdateColumnWithoutChangeWritesNothing() {
|
||||
using var fixture = new RepositoryFixture();
|
||||
|
||||
ColumnModel result = fixture.Repository.UpdateColumn(fixture.ColumnId, "Col", "");
|
||||
@@ -86,8 +80,7 @@ public class WorkspaceRepositoryTests
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void UpdateColumnChangeRefreshesTimestamp()
|
||||
{
|
||||
public void UpdateColumnChangeRefreshesTimestamp() {
|
||||
using var fixture = new RepositoryFixture();
|
||||
|
||||
ColumnModel updated = fixture.Repository.UpdateColumn(fixture.ColumnId, "Col2", "desc");
|
||||
@@ -97,8 +90,7 @@ public class WorkspaceRepositoryTests
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void DeleteColumnCascadesToCardsAndTagLinks()
|
||||
{
|
||||
public void DeleteColumnCascadesToCardsAndTagLinks() {
|
||||
using var fixture = new RepositoryFixture();
|
||||
|
||||
Assert.IsTrue(fixture.Repository.DeleteColumn(fixture.ColumnId));
|
||||
@@ -111,8 +103,7 @@ public class WorkspaceRepositoryTests
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void DeleteCardRemovesTagLinksButKeepsTags()
|
||||
{
|
||||
public void DeleteCardRemovesTagLinksButKeepsTags() {
|
||||
using var fixture = new RepositoryFixture();
|
||||
|
||||
Assert.IsTrue(fixture.Repository.DeleteCard(fixture.CardId));
|
||||
@@ -124,8 +115,7 @@ public class WorkspaceRepositoryTests
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void DeleteTagDetachesFromCardsButKeepsCards()
|
||||
{
|
||||
public void DeleteTagDetachesFromCardsButKeepsCards() {
|
||||
using var fixture = new RepositoryFixture();
|
||||
|
||||
Assert.IsTrue(fixture.Repository.DeleteTag(fixture.BugTagId));
|
||||
@@ -137,8 +127,7 @@ public class WorkspaceRepositoryTests
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void UpdateCardWithoutEffectiveChangeWritesNothing()
|
||||
{
|
||||
public void UpdateCardWithoutEffectiveChangeWritesNothing() {
|
||||
using var fixture = new RepositoryFixture();
|
||||
|
||||
CardModel result = fixture.Repository.UpdateCard(
|
||||
@@ -148,8 +137,7 @@ public class WorkspaceRepositoryTests
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void UpdateCardTitleChangeRefreshesTimestamp()
|
||||
{
|
||||
public void UpdateCardTitleChangeRefreshesTimestamp() {
|
||||
using var fixture = new RepositoryFixture();
|
||||
|
||||
CardModel updated = fixture.Repository.UpdateCard(
|
||||
@@ -160,8 +148,7 @@ public class WorkspaceRepositoryTests
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void UpdateCardTagSetOnlyChangeStillRefreshesTimestamp()
|
||||
{
|
||||
public void UpdateCardTagSetOnlyChangeStillRefreshesTimestamp() {
|
||||
using var fixture = new RepositoryFixture();
|
||||
|
||||
CardModel updated = fixture.Repository.UpdateCard(fixture.CardId, "T", "C", [fixture.BugTagId]);
|
||||
@@ -171,8 +158,7 @@ public class WorkspaceRepositoryTests
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void UpdateCardWithUnknownTagRollsBackAtomically()
|
||||
{
|
||||
public void UpdateCardWithUnknownTagRollsBackAtomically() {
|
||||
using var fixture = new RepositoryFixture();
|
||||
|
||||
// Tag 999 does not exist: the FK fires mid-transaction and the whole edit must roll back.
|
||||
@@ -187,8 +173,7 @@ public class WorkspaceRepositoryTests
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void MoveCardUpdatesColumnWithoutRefreshingTimestamp()
|
||||
{
|
||||
public void MoveCardUpdatesColumnWithoutRefreshingTimestamp() {
|
||||
using var fixture = new RepositoryFixture();
|
||||
long target = fixture.Repository.AddColumn("Target", "").Id;
|
||||
|
||||
@@ -201,8 +186,7 @@ public class WorkspaceRepositoryTests
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void MoveCardToCurrentColumnIsNoOp()
|
||||
{
|
||||
public void MoveCardToCurrentColumnIsNoOp() {
|
||||
using var fixture = new RepositoryFixture();
|
||||
|
||||
Assert.IsFalse(fixture.Repository.MoveCard(fixture.CardId, fixture.ColumnId));
|
||||
@@ -211,8 +195,7 @@ public class WorkspaceRepositoryTests
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void AddCardCreatesWithEqualTimestampsAndLinkedTags()
|
||||
{
|
||||
public void AddCardCreatesWithEqualTimestampsAndLinkedTags() {
|
||||
using var fixture = new RepositoryFixture();
|
||||
|
||||
CardModel card = fixture.Repository.AddCard(fixture.ColumnId, "N", "body", [fixture.UiTagId]);
|
||||
@@ -224,8 +207,7 @@ public class WorkspaceRepositoryTests
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void UpdateTagWithoutChangeWritesNothing()
|
||||
{
|
||||
public void UpdateTagWithoutChangeWritesNothing() {
|
||||
using var fixture = new RepositoryFixture();
|
||||
|
||||
TagModel result = fixture.Repository.UpdateTag(
|
||||
@@ -236,8 +218,7 @@ public class WorkspaceRepositoryTests
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void UpdateTagChangeWrites()
|
||||
{
|
||||
public void UpdateTagChangeWrites() {
|
||||
using var fixture = new RepositoryFixture();
|
||||
|
||||
TagModel updated = fixture.Repository.UpdateTag(
|
||||
@@ -250,16 +231,24 @@ public class WorkspaceRepositoryTests
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void AddTagWithDuplicateNameIsRejected()
|
||||
{
|
||||
public void AddTagWithDuplicateNameIsRejected() {
|
||||
using var fixture = new RepositoryFixture();
|
||||
Assert.ThrowsExactly<SqliteException>(() =>
|
||||
fixture.Repository.AddTag("bug", RgbColor.Parse("#123456"), ""));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void GetTagsWithUsageCountsAssignments()
|
||||
{
|
||||
public void GetCardIdsMatchingRunsTheCompiledSearch() {
|
||||
using var fixture = new RepositoryFixture();
|
||||
CompiledSearch compiled = SearchSqlCompiler.Compile(new SearchNode.FreeText("T"));
|
||||
|
||||
IReadOnlyCollection<long> ids = fixture.Repository.GetCardIdsMatching(compiled);
|
||||
|
||||
CollectionAssert.AreEquivalent(new[] { fixture.CardId }, ids.ToList());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void GetTagsWithUsageCountsAssignments() {
|
||||
using var fixture = new RepositoryFixture();
|
||||
|
||||
IReadOnlyList<(TagModel Tag, long UsageCount)> before = fixture.Repository.GetTagsWithUsage();
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
using Microsoft.Data.Sqlite;
|
||||
|
||||
using YKanBan.Storage;
|
||||
using YKanBan.Storage.Workspace;
|
||||
using YKanBan.Tests.TestUtilities;
|
||||
@@ -10,19 +11,16 @@ namespace YKanBan.Tests.Storage.Workspace;
|
||||
/// and that the cascading delete chains work as specified.
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
public class WorkspaceSchemaTests
|
||||
{
|
||||
public class WorkspaceSchemaTests {
|
||||
/// <summary>
|
||||
/// Owns a temp directory plus a fresh workspace-schema database for a single test.
|
||||
/// </summary>
|
||||
private sealed class FreshDatabase : IDisposable
|
||||
{
|
||||
private sealed class FreshDatabase : IDisposable {
|
||||
public TempDirectory Directory { get; } = new();
|
||||
|
||||
public SqliteConnection Connection { get; }
|
||||
|
||||
public FreshDatabase()
|
||||
{
|
||||
public FreshDatabase() {
|
||||
Connection = SqliteDatabase.Open(
|
||||
Path.Combine(Directory.FullPath, "ws.db"), WorkspaceSchema.Migrations);
|
||||
}
|
||||
@@ -30,24 +28,21 @@ public class WorkspaceSchemaTests
|
||||
/// <summary>
|
||||
/// Closes the connection before removing the temporary directory.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
public void Dispose() {
|
||||
Connection.Dispose();
|
||||
Directory.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void EmptyColumnTitleIsRejected()
|
||||
{
|
||||
public void EmptyColumnTitleIsRejected() {
|
||||
using var db = new FreshDatabase();
|
||||
Assert.ThrowsExactly<SqliteException>(() =>
|
||||
SqliteTestHelper.Exec(db.Connection, "INSERT INTO columns (title, created_at, updated_at) VALUES ('', 1, 1);"));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void WhitespaceColumnTitleIsAccepted()
|
||||
{
|
||||
public void WhitespaceColumnTitleIsAccepted() {
|
||||
using var db = new FreshDatabase();
|
||||
// No trimming: a single space is a non-empty title as far as the DDL is concerned.
|
||||
int affected = SqliteTestHelper.Exec(
|
||||
@@ -56,8 +51,7 @@ public class WorkspaceSchemaTests
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void DuplicateColumnTitleIsRejected()
|
||||
{
|
||||
public void DuplicateColumnTitleIsRejected() {
|
||||
using var db = new FreshDatabase();
|
||||
SqliteTestHelper.Exec(db.Connection, "INSERT INTO columns (title, created_at, updated_at) VALUES ('Foo', 1, 1);");
|
||||
Assert.ThrowsExactly<SqliteException>(() =>
|
||||
@@ -65,8 +59,7 @@ public class WorkspaceSchemaTests
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void ColumnTitlesCompareCaseSensitively()
|
||||
{
|
||||
public void ColumnTitlesCompareCaseSensitively() {
|
||||
using var db = new FreshDatabase();
|
||||
// BINARY collation: 'Foo' and 'foo' are distinct titles.
|
||||
SqliteTestHelper.Exec(db.Connection, "INSERT INTO columns (title, created_at, updated_at) VALUES ('Foo', 1, 1);");
|
||||
@@ -75,28 +68,24 @@ public class WorkspaceSchemaTests
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void EmptyTagNameIsRejected()
|
||||
{
|
||||
public void EmptyTagNameIsRejected() {
|
||||
using var db = new FreshDatabase();
|
||||
Assert.ThrowsExactly<SqliteException>(() =>
|
||||
SqliteTestHelper.Exec(db.Connection, "INSERT INTO tags (name, color) VALUES ('', '#112233');"));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TagNamesAcceptSpacesEmojiAndReservedWords()
|
||||
{
|
||||
public void TagNamesAcceptSpacesEmojiAndReservedWords() {
|
||||
using var db = new FreshDatabase();
|
||||
// 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));
|
||||
}
|
||||
Assert.AreEqual(5L, SqliteTestHelper.ScalarLong(db.Connection, "SELECT COUNT(*) FROM tags;"));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void DuplicateTagNameIsRejected()
|
||||
{
|
||||
public void DuplicateTagNameIsRejected() {
|
||||
using var db = new FreshDatabase();
|
||||
SqliteTestHelper.Exec(db.Connection, "INSERT INTO tags (name, color) VALUES ('bug', '#112233');");
|
||||
Assert.ThrowsExactly<SqliteException>(() =>
|
||||
@@ -107,8 +96,7 @@ public class WorkspaceSchemaTests
|
||||
[DataRow("#000000")]
|
||||
[DataRow("#FFFFFF")]
|
||||
[DataRow("#a1B2c3")]
|
||||
public void ValidTagColorsAreAccepted(string color)
|
||||
{
|
||||
public void ValidTagColorsAreAccepted(string color) {
|
||||
using var db = new FreshDatabase();
|
||||
int affected = SqliteTestHelper.Exec(
|
||||
db.Connection, "INSERT INTO tags (name, color) VALUES ('x', $c);", ("$c", color));
|
||||
@@ -124,16 +112,14 @@ public class WorkspaceSchemaTests
|
||||
[DataRow(" #112233")]
|
||||
[DataRow("#112233 ")]
|
||||
[DataRow("")]
|
||||
public void InvalidTagColorsAreRejected(string color)
|
||||
{
|
||||
public void InvalidTagColorsAreRejected(string color) {
|
||||
using var db = new FreshDatabase();
|
||||
Assert.ThrowsExactly<SqliteException>(() =>
|
||||
SqliteTestHelper.Exec(db.Connection, "INSERT INTO tags (name, color) VALUES ('x', $c);", ("$c", color)));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CardRequiresExistingColumn()
|
||||
{
|
||||
public void CardRequiresExistingColumn() {
|
||||
using var db = new FreshDatabase();
|
||||
// foreign_keys=ON makes the FK enforceable; this is the DDL contract behind the cascades.
|
||||
Assert.ThrowsExactly<SqliteException>(() =>
|
||||
@@ -141,8 +127,7 @@ public class WorkspaceSchemaTests
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CardDefaultsToEmptyTitleAndContent()
|
||||
{
|
||||
public void CardDefaultsToEmptyTitleAndContent() {
|
||||
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 cards (column_id, created_at, updated_at) VALUES (1, 1, 1);");
|
||||
@@ -153,8 +138,7 @@ public class WorkspaceSchemaTests
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CardTagDuplicateAssignmentIsRejected()
|
||||
{
|
||||
public void CardTagDuplicateAssignmentIsRejected() {
|
||||
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 cards (column_id, created_at, updated_at) VALUES (1, 1, 1);");
|
||||
@@ -167,8 +151,7 @@ public class WorkspaceSchemaTests
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void DeletingColumnCascadesToCardsAndCardTags()
|
||||
{
|
||||
public void DeletingColumnCascadesToCardsAndCardTags() {
|
||||
using var db = new FreshDatabase();
|
||||
InsertBoardRow(db.Connection);
|
||||
|
||||
@@ -182,8 +165,7 @@ public class WorkspaceSchemaTests
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void DeletingCardCascadesToCardTagsOnly()
|
||||
{
|
||||
public void DeletingCardCascadesToCardTagsOnly() {
|
||||
using var db = new FreshDatabase();
|
||||
InsertBoardRow(db.Connection);
|
||||
|
||||
@@ -196,8 +178,7 @@ public class WorkspaceSchemaTests
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void DeletingTagRemovesAssignmentsButKeepsCards()
|
||||
{
|
||||
public void DeletingTagRemovesAssignmentsButKeepsCards() {
|
||||
using var db = new FreshDatabase();
|
||||
InsertBoardRow(db.Connection);
|
||||
|
||||
@@ -214,8 +195,7 @@ public class WorkspaceSchemaTests
|
||||
/// Inserts one column, one card, one tag and their assignment, ready for a cascade test.
|
||||
/// </summary>
|
||||
/// <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 cards (column_id, created_at, updated_at) VALUES (1, 1, 1);");
|
||||
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.
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
public class WorkspaceSessionTests
|
||||
{
|
||||
public class WorkspaceSessionTests {
|
||||
[TestMethod]
|
||||
public void OpenHoldsLockUntilDisposed()
|
||||
{
|
||||
public void OpenHoldsLockUntilDisposed() {
|
||||
using var directory = new TempDirectory();
|
||||
WorkspaceInitializer.Initialize(directory.FullPath);
|
||||
|
||||
@@ -25,8 +23,7 @@ public class WorkspaceSessionTests
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void DisposeReleasesLockForReopen()
|
||||
{
|
||||
public void DisposeReleasesLockForReopen() {
|
||||
using var directory = new TempDirectory();
|
||||
WorkspaceInitializer.Initialize(directory.FullPath);
|
||||
|
||||
@@ -37,8 +34,7 @@ public class WorkspaceSessionTests
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void OpenUninitializedFolderThrowsNotInitialized()
|
||||
{
|
||||
public void OpenUninitializedFolderThrowsNotInitialized() {
|
||||
using var directory = new TempDirectory();
|
||||
|
||||
Assert.ThrowsExactly<WorkspaceNotInitializedException>(
|
||||
@@ -46,8 +42,43 @@ public class WorkspaceSessionTests
|
||||
}
|
||||
|
||||
[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();
|
||||
WorkspaceInitializer.Initialize(directory.FullPath);
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
using Microsoft.Data.Sqlite;
|
||||
|
||||
using YKanBan.Storage;
|
||||
using YKanBan.Storage.Workspace;
|
||||
|
||||
@@ -8,8 +9,7 @@ namespace YKanBan.Tests.TestUtilities;
|
||||
/// Shared helpers for the storage tests: small SQL conveniences plus opening a
|
||||
/// workspace database with the real migration list.
|
||||
/// </summary>
|
||||
public static class SqliteTestHelper
|
||||
{
|
||||
public static class SqliteTestHelper {
|
||||
/// <summary>
|
||||
/// Executes a non-query SQL statement and returns the affected row count.
|
||||
/// </summary>
|
||||
@@ -17,12 +17,10 @@ public static class SqliteTestHelper
|
||||
/// <param name="sql">The statement to execute.</param>
|
||||
/// <param name="parameters">Name/value pairs bound as SQL parameters.</param>
|
||||
/// <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();
|
||||
command.CommandText = sql;
|
||||
foreach ((string name, object? value) in parameters)
|
||||
{
|
||||
foreach ((string name, object? value) in parameters) {
|
||||
command.Parameters.AddWithValue(name, value);
|
||||
}
|
||||
return command.ExecuteNonQuery();
|
||||
@@ -34,8 +32,7 @@ public static class SqliteTestHelper
|
||||
/// <param name="connection">An open database connection.</param>
|
||||
/// <param name="sql">The query to execute.</param>
|
||||
/// <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();
|
||||
command.CommandText = sql;
|
||||
return (string)command.ExecuteScalar()!;
|
||||
@@ -47,8 +44,7 @@ public static class SqliteTestHelper
|
||||
/// <param name="connection">An open database connection.</param>
|
||||
/// <param name="sql">The query to execute.</param>
|
||||
/// <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();
|
||||
command.CommandText = sql;
|
||||
return (long)command.ExecuteScalar()!;
|
||||
@@ -60,8 +56,7 @@ public static class SqliteTestHelper
|
||||
/// <param name="connection">An open database connection.</param>
|
||||
/// <param name="tableName">The table name to look for.</param>
|
||||
/// <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();
|
||||
command.CommandText = "SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name=$name;";
|
||||
command.Parameters.AddWithValue("$name", tableName);
|
||||
@@ -73,27 +68,58 @@ public static class SqliteTestHelper
|
||||
/// </summary>
|
||||
/// <param name="connection">An open database connection.</param>
|
||||
/// <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();
|
||||
command.CommandText = "SELECT title FROM columns ORDER BY id ASC;";
|
||||
using var reader = command.ExecuteReader();
|
||||
|
||||
var titles = new List<string>();
|
||||
while (reader.Read())
|
||||
{
|
||||
while (reader.Read()) {
|
||||
titles.Add(reader.GetString(0));
|
||||
}
|
||||
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>
|
||||
/// Opens a workspace database with the real workspace migration list.
|
||||
/// </summary>
|
||||
/// <param name="folderPath">The workspace folder path.</param>
|
||||
/// <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);
|
||||
}
|
||||
}
|
||||
@@ -5,15 +5,13 @@ namespace YKanBan.Tests.TestUtilities;
|
||||
/// disposal. The removal is retried once because SQLite WAL sidecar files can
|
||||
/// linger for a moment after the connections close.
|
||||
/// </summary>
|
||||
public sealed class TempDirectory : IDisposable
|
||||
{
|
||||
public sealed class TempDirectory : IDisposable {
|
||||
/// <summary>
|
||||
/// Gets the unique directory path managed by this instance.
|
||||
/// </summary>
|
||||
public string FullPath { get; }
|
||||
|
||||
public TempDirectory()
|
||||
{
|
||||
public TempDirectory() {
|
||||
FullPath = Path.Combine(Path.GetTempPath(), "ykanban-tests-" + Guid.NewGuid().ToString("N"));
|
||||
Directory.CreateDirectory(FullPath);
|
||||
}
|
||||
@@ -21,21 +19,19 @@ public sealed class TempDirectory : IDisposable
|
||||
/// <summary>
|
||||
/// Deletes the directory tree, retrying once after a short delay.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
try
|
||||
{
|
||||
public void Dispose() {
|
||||
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);
|
||||
}
|
||||
catch (IOException)
|
||||
{
|
||||
} catch (IOException) {
|
||||
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);
|
||||
}
|
||||
catch (IOException)
|
||||
{
|
||||
} catch (IOException) {
|
||||
// Leftovers in the OS temp folder are harmless; never fail a test over cleanup.
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
using System.Globalization;
|
||||
|
||||
using Microsoft.Data.Sqlite;
|
||||
|
||||
using YKanBan.Storage;
|
||||
using YKanBan.ViewModels.ErrorPages;
|
||||
|
||||
namespace YKanBan.Tests.ViewModels;
|
||||
|
||||
/// <summary>
|
||||
/// Tests for the open-failed page's exception-type → localized message mapping
|
||||
/// and its English details. Mutates the global <see cref="Resources.Culture"/>,
|
||||
/// therefore marked do-not-parallelize.
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
[DoNotParallelize]
|
||||
public class OpenFailedPageViewModelTests {
|
||||
private const string Folder = "/work/repo";
|
||||
|
||||
private static void WithCulture(string language, Action action) {
|
||||
CultureInfo? original = Resources.Culture;
|
||||
try {
|
||||
Resources.Culture = new CultureInfo(language);
|
||||
action();
|
||||
} finally {
|
||||
Resources.Culture = original;
|
||||
}
|
||||
}
|
||||
|
||||
private static string Expected(string pattern, params object[] arguments) =>
|
||||
string.Format(Resources.Culture, pattern, [Folder, .. arguments]);
|
||||
|
||||
[TestMethod]
|
||||
[DataRow("en")]
|
||||
[DataRow("zh-Hans")]
|
||||
public void EachRecognizedExceptionTypeHasItsOwnMessage(string language) {
|
||||
WithCulture(language, () => {
|
||||
Assert.AreEqual(
|
||||
Expected(Resources.Error_OpenFailed_SchemaTooNew, 3L, 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(
|
||||
Expected(Resources.Error_OpenFailed_Database),
|
||||
OpenFailedPageViewModel.BuildMessage(Folder, new SqliteException("file is not a database", 26)));
|
||||
Assert.AreEqual(
|
||||
Expected(Resources.Error_OpenFailed_AccessDenied),
|
||||
OpenFailedPageViewModel.BuildMessage(Folder, new UnauthorizedAccessException()));
|
||||
Assert.AreEqual(
|
||||
Expected(Resources.Error_OpenFailed_Io),
|
||||
OpenFailedPageViewModel.BuildMessage(Folder, new IOException()));
|
||||
Assert.AreEqual(
|
||||
Expected(Resources.Error_OpenFailed_Io),
|
||||
OpenFailedPageViewModel.BuildMessage(Folder, new DirectoryNotFoundException()));
|
||||
});
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void UnrecognizedExceptionGetsTheGenericMessage() {
|
||||
WithCulture("en", () => {
|
||||
Assert.AreEqual(
|
||||
Expected(Resources.Error_OpenFailed_Generic),
|
||||
OpenFailedPageViewModel.BuildMessage(Folder, new InvalidOperationException()));
|
||||
Assert.AreEqual(
|
||||
Expected(Resources.Error_OpenFailed_Generic),
|
||||
OpenFailedPageViewModel.BuildMessage(Folder, new WorkspaceDirectoryMissingException(Folder)));
|
||||
});
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void DetailsCarryTheEnglishExceptionTextInAnyLanguage() {
|
||||
WithCulture("zh-Hans", () => {
|
||||
var exception = new SchemaVersionException(3, 1);
|
||||
var page = new OpenFailedPageViewModel(Folder, exception);
|
||||
|
||||
Assert.AreEqual(Folder, page.FolderPath);
|
||||
StringAssert.Contains(page.Details, typeof(SchemaVersionException).FullName!);
|
||||
StringAssert.Contains(page.Details, exception.Message);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net9.0</TargetFramework>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<IsPackable>false</IsPackable>
|
||||
|
||||
@@ -12,6 +12,7 @@
|
||||
<Application.Styles>
|
||||
<!-- Semi.Avalonia provides the light and dark palettes; icons need their own theme. -->
|
||||
<semi:SemiTheme/>
|
||||
<semi:ColorPickerSemiTheme/>
|
||||
<StyleInclude Source="avares://IconPacks.Avalonia.Lucide/Lucide.axaml"/>
|
||||
</Application.Styles>
|
||||
|
||||
@@ -26,10 +27,20 @@
|
||||
<ResourceDictionary x:Key="Light">
|
||||
<SolidColorBrush x:Key="TopBarBackgroundBrush" Color="#F6F7F9"/>
|
||||
<SolidColorBrush x:Key="TopBarBorderBrush" Color="#E2E4EA"/>
|
||||
<SolidColorBrush x:Key="BoardColumnBackgroundBrush" Color="#F1F2F5"/>
|
||||
<SolidColorBrush x:Key="BoardColumnBorderBrush" Color="#E2E4EA"/>
|
||||
<SolidColorBrush x:Key="CardBackgroundBrush" Color="#FFFFFF"/>
|
||||
<SolidColorBrush x:Key="CardBorderBrush" Color="#E2E4EA"/>
|
||||
<SolidColorBrush x:Key="ErrorTextBrush" Color="#C0392B"/>
|
||||
</ResourceDictionary>
|
||||
<ResourceDictionary x:Key="Dark">
|
||||
<SolidColorBrush x:Key="TopBarBackgroundBrush" Color="#1C1E24"/>
|
||||
<SolidColorBrush x:Key="TopBarBorderBrush" Color="#2C2F37"/>
|
||||
<SolidColorBrush x:Key="BoardColumnBackgroundBrush" Color="#17181C"/>
|
||||
<SolidColorBrush x:Key="BoardColumnBorderBrush" Color="#2C2F37"/>
|
||||
<SolidColorBrush x:Key="CardBackgroundBrush" Color="#23252B"/>
|
||||
<SolidColorBrush x:Key="CardBorderBrush" Color="#33363F"/>
|
||||
<SolidColorBrush x:Key="ErrorTextBrush" Color="#FF6B6B"/>
|
||||
</ResourceDictionary>
|
||||
</ResourceDictionary.ThemeDictionaries>
|
||||
</ResourceDictionary>
|
||||
|
||||
+30
-34
@@ -1,20 +1,22 @@
|
||||
using System.Globalization;
|
||||
|
||||
using Avalonia;
|
||||
using Avalonia.Controls.ApplicationLifetimes;
|
||||
using Avalonia.Data.Core.Plugins;
|
||||
using Avalonia.Markup.Xaml;
|
||||
using Avalonia.Media;
|
||||
using Avalonia.Styling;
|
||||
|
||||
using YKanBan.Services;
|
||||
using YKanBan.Storage.AppData;
|
||||
using YKanBan.ViewModels;
|
||||
using YKanBan.Views;
|
||||
|
||||
using Resx = YKanBan.Resources;
|
||||
|
||||
namespace YKanBan;
|
||||
|
||||
public partial class App : Application
|
||||
{
|
||||
public partial class App : Application {
|
||||
/// <summary>
|
||||
/// Gets the process-wide composition root, created at startup.
|
||||
/// </summary>
|
||||
@@ -26,15 +28,18 @@ public partial class App : Application
|
||||
/// </summary>
|
||||
public static string StartupLanguage { get; private set; } = AppConfig.DefaultLanguage;
|
||||
|
||||
public override void Initialize()
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the flow direction of the startup culture. FlowDirection does not
|
||||
/// inherit across windows, so the main window and every modal window apply it.
|
||||
/// </summary>
|
||||
public static FlowDirection UiFlowDirection { get; private set; } = FlowDirection.LeftToRight;
|
||||
|
||||
public override void Initialize() {
|
||||
AvaloniaXamlLoader.Load(this);
|
||||
}
|
||||
|
||||
public override void OnFrameworkInitializationCompleted()
|
||||
{
|
||||
if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
|
||||
{
|
||||
public override void OnFrameworkInitializationCompleted() {
|
||||
if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop) {
|
||||
DisableAvaloniaDataAnnotationValidation();
|
||||
|
||||
// Startup order: apply the configured culture, its RTL flow direction
|
||||
@@ -43,19 +48,19 @@ public partial class App : Application
|
||||
CultureInfo culture = ResolveCulture(Services.Config.Language);
|
||||
StartupLanguage = Services.Config.Language;
|
||||
Resx.Culture = culture;
|
||||
|
||||
// RTL detection drives the flow direction of every window; the two
|
||||
// supported languages are LTR, but the infrastructure stays in
|
||||
// place for future languages.
|
||||
UiFlowDirection = culture.TextInfo.IsRightToLeft
|
||||
? FlowDirection.RightToLeft
|
||||
: FlowDirection.LeftToRight;
|
||||
ApplyTheme(Services.Config.Theme);
|
||||
|
||||
var viewModel = new MainWindowViewModel(Services, desktop.Args ?? []);
|
||||
desktop.MainWindow = new MainWindow
|
||||
{
|
||||
desktop.MainWindow = new MainWindow {
|
||||
DataContext = viewModel,
|
||||
|
||||
// RTL detection drives the whole window flow direction; the two
|
||||
// supported languages are LTR, but the infrastructure stays in
|
||||
// place for future languages.
|
||||
FlowDirection = culture.TextInfo.IsRightToLeft
|
||||
? FlowDirection.RightToLeft
|
||||
: FlowDirection.LeftToRight,
|
||||
FlowDirection = UiFlowDirection,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -67,14 +72,10 @@ public partial class App : Application
|
||||
/// </summary>
|
||||
/// <param name="language">The language code from app.json.</param>
|
||||
/// <returns>The resolved culture.</returns>
|
||||
public static CultureInfo ResolveCulture(string language)
|
||||
{
|
||||
try
|
||||
{
|
||||
public static CultureInfo ResolveCulture(string language) {
|
||||
try {
|
||||
return new CultureInfo(language);
|
||||
}
|
||||
catch (CultureNotFoundException)
|
||||
{
|
||||
} catch (CultureNotFoundException) {
|
||||
return new CultureInfo(AppConfig.DefaultLanguage);
|
||||
}
|
||||
}
|
||||
@@ -84,28 +85,23 @@ public partial class App : Application
|
||||
/// inherits the operating system preference.
|
||||
/// </summary>
|
||||
/// <param name="option">The theme selection.</param>
|
||||
public static void ApplyTheme(ThemeOption option)
|
||||
{
|
||||
if (Current is null)
|
||||
{
|
||||
public static void ApplyTheme(ThemeOption option) {
|
||||
if (Current is null) {
|
||||
return;
|
||||
}
|
||||
|
||||
Current.RequestedThemeVariant = option switch
|
||||
{
|
||||
Current.RequestedThemeVariant = option switch {
|
||||
ThemeOption.Light => ThemeVariant.Light,
|
||||
ThemeOption.Dark => ThemeVariant.Dark,
|
||||
_ => ThemeVariant.Default,
|
||||
};
|
||||
}
|
||||
|
||||
private static void DisableAvaloniaDataAnnotationValidation()
|
||||
{
|
||||
private static void DisableAvaloniaDataAnnotationValidation() {
|
||||
var dataValidationPluginsToRemove =
|
||||
BindingPlugins.DataValidators.OfType<DataAnnotationsValidationPlugin>().ToArray();
|
||||
|
||||
foreach (var plugin in dataValidationPluginsToRemove)
|
||||
{
|
||||
foreach (var plugin in dataValidationPluginsToRemove) {
|
||||
BindingPlugins.DataValidators.Remove(plugin);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -25,6 +25,12 @@
|
||||
<data name="Common_Cancel" xml:space="preserve">
|
||||
<value>Cancel</value>
|
||||
</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">
|
||||
<value>Export</value>
|
||||
</data>
|
||||
@@ -40,6 +46,219 @@
|
||||
<data name="Tab_Board" xml:space="preserve">
|
||||
<value>Board</value>
|
||||
</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">
|
||||
<value>Invalid arguments</value>
|
||||
</data>
|
||||
@@ -49,12 +268,6 @@
|
||||
<data name="Error_Argument_Usage" xml:space="preserve">
|
||||
<value>Usage: ykanban <path></value>
|
||||
</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">
|
||||
<value>No workspace here</value>
|
||||
</data>
|
||||
@@ -62,7 +275,7 @@
|
||||
<value>The folder does not contain a .ykanban workspace: {0}</value>
|
||||
</data>
|
||||
<data name="Error_NotInitialized_Initialize" xml:space="preserve">
|
||||
<value>Initialize workspace</value>
|
||||
<value>Initialize Workspace</value>
|
||||
</data>
|
||||
<data name="Error_LockConflict_Title" xml:space="preserve">
|
||||
<value>Workspace locked</value>
|
||||
@@ -95,7 +308,7 @@
|
||||
<value>Dark</value>
|
||||
</data>
|
||||
<data name="Settings_ThemeFollowSystem" xml:space="preserve">
|
||||
<value>Follow system</value>
|
||||
<value>Follow System</value>
|
||||
</data>
|
||||
<data name="Settings_Confirmations" xml:space="preserve">
|
||||
<value>Confirmations</value>
|
||||
@@ -130,21 +343,75 @@
|
||||
<data name="PresetColumn_Todo" xml:space="preserve">
|
||||
<value>To Do</value>
|
||||
</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">
|
||||
<value>In Progress</value>
|
||||
</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">
|
||||
<value>Done</value>
|
||||
</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">
|
||||
<value>{0}-export-{1:yyyyMMdd-HHmmss}.md</value>
|
||||
</data>
|
||||
<data name="Export_TimePattern" xml:space="preserve">
|
||||
<value>yyyy-MM-dd HH:mm:ss</value>
|
||||
</data>
|
||||
<data name="Export_CardTimePattern" xml:space="preserve">
|
||||
<value>yyyy-MM-dd HH:mm</value>
|
||||
</data>
|
||||
<data name="Export_WorkspaceHeading" xml:space="preserve">
|
||||
<value># {0}</value>
|
||||
</data>
|
||||
@@ -166,4 +433,34 @@
|
||||
<data name="Export_TagsTableHeader" xml:space="preserve">
|
||||
<value>| Name | Color | Description | Usage |</value>
|
||||
</data>
|
||||
<data name="Export_Done_Title" xml:space="preserve">
|
||||
<value>Export Complete</value>
|
||||
</data>
|
||||
<data name="Export_Done_Message" xml:space="preserve">
|
||||
<value>Exported to: {0}</value>
|
||||
</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_DatabaseMissing" xml:space="preserve">
|
||||
<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 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>
|
||||
</root>
|
||||
@@ -25,6 +25,12 @@
|
||||
<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>
|
||||
@@ -40,6 +46,219 @@
|
||||
<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>编号:{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>
|
||||
@@ -49,12 +268,6 @@
|
||||
<data name="Error_Argument_Usage" xml:space="preserve">
|
||||
<value>用法:ykanban <路径></value>
|
||||
</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">
|
||||
<value>尚未初始化</value>
|
||||
</data>
|
||||
@@ -130,21 +343,75 @@
|
||||
<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</value>
|
||||
</data>
|
||||
<data name="Export_CardTimePattern" xml:space="preserve">
|
||||
<value>yyyy年M月d日 HH:mm</value>
|
||||
</data>
|
||||
<data name="Export_WorkspaceHeading" xml:space="preserve">
|
||||
<value># {0}</value>
|
||||
</data>
|
||||
@@ -166,4 +433,34 @@
|
||||
<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>
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 172 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 21 KiB |
@@ -1,18 +1,22 @@
|
||||
using System.Globalization;
|
||||
using System.Text;
|
||||
|
||||
using YKanBan.Models;
|
||||
|
||||
namespace YKanBan.Export;
|
||||
|
||||
/// <summary>
|
||||
/// Generates the human-readable Markdown snapshot of a whole board. All
|
||||
/// template text and time formats come from the ResX resources in the current
|
||||
/// UI language; the export timestamp uses the per-language pattern, card
|
||||
/// timestamps use the shared minute-precision pattern. The output is meant for
|
||||
/// reading only — there is no re-import.
|
||||
/// template text and the one time format come from the ResX resources in the
|
||||
/// current UI language; every timestamp (export time and card created/modified
|
||||
/// times) uses that per-language pattern. The document uses the platform's
|
||||
/// newline. Card bodies and column descriptions are emitted verbatim; column and
|
||||
/// card titles are collapsed to one line; tag names become inline code with a
|
||||
/// long enough backtick fence; tag table cells escape '\' and '|' and turn line
|
||||
/// breaks into <br>. The output is meant for reading only — there is no
|
||||
/// re-import.
|
||||
/// </summary>
|
||||
public static class MarkdownExporter
|
||||
{
|
||||
public static class MarkdownExporter {
|
||||
/// <summary>
|
||||
/// Renders the whole board to Markdown.
|
||||
/// </summary>
|
||||
@@ -27,31 +31,29 @@ public static class MarkdownExporter
|
||||
IReadOnlyList<ColumnModel> columns,
|
||||
IReadOnlyList<CardModel> cards,
|
||||
IReadOnlyList<(TagModel Tag, long UsageCount)> tags,
|
||||
DateTimeOffset exportedAt)
|
||||
{
|
||||
DateTimeOffset exportedAt) {
|
||||
CultureInfo culture = Resources.Culture ?? CultureInfo.CurrentUICulture;
|
||||
|
||||
var builder = new StringBuilder();
|
||||
|
||||
// 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(
|
||||
culture, Resources.Export_ExportedAtLine, exportedAt.ToString(Resources.Export_TimePattern, culture)));
|
||||
builder.AppendLine();
|
||||
|
||||
// Board body: every column in id order, empty ones included.
|
||||
foreach (ColumnModel column in columns)
|
||||
{
|
||||
IReadOnlyList<CardModel> cardsInColumn = cards.Where(card => card.ColumnId == column.Id).ToArray();
|
||||
builder.AppendLine(string.Format(culture, Resources.Export_ColumnHeading, column.Title, cardsInColumn.Count));
|
||||
if (column.Description.Length > 0)
|
||||
{
|
||||
builder.AppendLine(SingleLine(column.Description));
|
||||
// Board body: every column in id order, empty ones included; independent of
|
||||
// the board's search filter and card sort option.
|
||||
foreach (ColumnModel column in columns.OrderBy(column => column.Id)) {
|
||||
IReadOnlyList<CardModel> cardsInColumn =
|
||||
cards.Where(card => card.ColumnId == column.Id).OrderBy(card => card.Id).ToArray();
|
||||
builder.AppendLine(string.Format(culture, Resources.Export_ColumnHeading, SingleLine(column.Title), cardsInColumn.Count));
|
||||
if (column.Description.Length > 0) {
|
||||
builder.AppendLine(column.Description);
|
||||
}
|
||||
builder.AppendLine();
|
||||
|
||||
foreach (CardModel card in cardsInColumn)
|
||||
{
|
||||
foreach (CardModel card in cardsInColumn) {
|
||||
AppendCard(builder, card, culture);
|
||||
}
|
||||
}
|
||||
@@ -62,43 +64,55 @@ public static class MarkdownExporter
|
||||
|
||||
/// <summary>
|
||||
/// 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>
|
||||
/// <param name="workspaceName">Workspace display name.</param>
|
||||
/// <param name="exportedAt">Export moment.</param>
|
||||
/// <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;
|
||||
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>
|
||||
/// Appends one card block: heading, body, tags line and timestamps line.
|
||||
/// </summary>
|
||||
/// <param name="builder">The output builder.</param>
|
||||
/// <param name="card">The card to render.</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.
|
||||
builder.AppendLine(card.Title.Length == 0
|
||||
? $"### #{card.Id}"
|
||||
: $"### #{card.Id} {SingleLine(card.Title)}");
|
||||
|
||||
if (card.Content.Length > 0)
|
||||
{
|
||||
if (card.Content.Length > 0) {
|
||||
builder.AppendLine(card.Content);
|
||||
}
|
||||
|
||||
if (card.Tags.Count > 0)
|
||||
{
|
||||
string names = string.Join(" ", card.Tags.Select(tag => $"`{tag.Name}`"));
|
||||
if (card.Tags.Count > 0) {
|
||||
string names = string.Join(" ", card.Tags.Select(tag => InlineCode(tag.Name)));
|
||||
builder.AppendLine(string.Format(culture, Resources.Export_TagsLine, names));
|
||||
}
|
||||
|
||||
string created = ToLocalTime(card.CreatedAt).ToString(Resources.Export_CardTimePattern, culture);
|
||||
string updated = ToLocalTime(card.UpdatedAt).ToString(Resources.Export_CardTimePattern, culture);
|
||||
string created = ToLocalTime(card.CreatedAt).ToString(Resources.Export_TimePattern, culture);
|
||||
string updated = ToLocalTime(card.UpdatedAt).ToString(Resources.Export_TimePattern, culture);
|
||||
builder.AppendLine(string.Format(culture, Resources.Export_CreatedModifiedLine, created, updated));
|
||||
builder.AppendLine();
|
||||
}
|
||||
@@ -112,24 +126,45 @@ public static class MarkdownExporter
|
||||
private static void AppendTagTable(
|
||||
StringBuilder builder,
|
||||
IReadOnlyList<(TagModel Tag, long UsageCount)> tags,
|
||||
CultureInfo culture)
|
||||
{
|
||||
CultureInfo culture) {
|
||||
builder.AppendLine(Resources.Export_TagsSummaryHeading);
|
||||
builder.AppendLine(Resources.Export_TagsTableHeader);
|
||||
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.
|
||||
builder.AppendLine($"| {Cell(tag.Name)} | {tag.Color} | {Cell(tag.Description)} | {usage} |");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Formats a table cell: single line with escaped pipe characters.
|
||||
/// Formats a table cell: escaped backslashes and pipe characters, line breaks as <br>.
|
||||
/// </summary>
|
||||
/// <param name="text">The raw cell text.</param>
|
||||
/// <returns>The escaped single-line text.</returns>
|
||||
private static string Cell(string text) => SingleLine(text).Replace("|", "\\|");
|
||||
private static string Cell(string text) =>
|
||||
// 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>
|
||||
/// Renders text as an inline code span whose backtick fence is one longer than
|
||||
/// the longest backtick run inside, padded with spaces when the text starts or
|
||||
/// ends with a backtick.
|
||||
/// </summary>
|
||||
/// <param name="text">The raw text.</param>
|
||||
/// <returns>The inline code span.</returns>
|
||||
private static string InlineCode(string text) {
|
||||
int longestRun = 0;
|
||||
int run = 0;
|
||||
foreach (char character in text) {
|
||||
run = character == '`' ? run + 1 : 0;
|
||||
longestRun = Math.Max(longestRun, run);
|
||||
}
|
||||
|
||||
string fence = new('`', longestRun + 1);
|
||||
string padding = text.StartsWith('`') || text.EndsWith('`') ? " " : string.Empty;
|
||||
return fence + padding + text + padding + fence;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Collapses line breaks so the text stays on one Markdown line.
|
||||
|
||||
@@ -4,28 +4,40 @@ namespace YKanBan.Launching;
|
||||
|
||||
/// <summary>
|
||||
/// Parses raw command-line arguments. The only accepted form is a single,
|
||||
/// non-blank workspace path (<c>ykanban <path></c>); zero arguments,
|
||||
/// more than one argument, or a blank argument is rejected as an argument
|
||||
/// error. The path itself is not checked for existence here.
|
||||
/// non-blank, existing workspace folder (<c>ykanban <path></c>); zero
|
||||
/// arguments, more than one argument, a blank argument, an argument starting
|
||||
/// with <c>-</c> (any option form, <c>--help</c> included), a malformed path or
|
||||
/// a path that is not an existing folder is rejected as an argument error. A
|
||||
/// relative path is resolved against the process's current directory.
|
||||
/// </summary>
|
||||
public static class LaunchArguments
|
||||
{
|
||||
public static class LaunchArguments {
|
||||
/// <summary>
|
||||
/// Tries to parse command-line arguments following the
|
||||
/// <c>ykanban <path></c> contract.
|
||||
/// </summary>
|
||||
/// <param name="arguments">The raw arguments, excluding the executable name.</param>
|
||||
/// <param name="folderPath">The parsed workspace path on success, otherwise <see langword="null"/>.</param>
|
||||
/// <returns><see langword="true"/> when exactly one non-blank path was supplied.</returns>
|
||||
public static bool TryParse(IReadOnlyList<string> arguments, [NotNullWhen(true)] out string? folderPath)
|
||||
{
|
||||
if (arguments.Count == 1 && !string.IsNullOrWhiteSpace(arguments[0]))
|
||||
{
|
||||
folderPath = arguments[0];
|
||||
return true;
|
||||
/// <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>
|
||||
public static bool TryParse(IReadOnlyList<string> arguments, [NotNullWhen(true)] out string? folderPath) {
|
||||
folderPath = null;
|
||||
if (arguments.Count != 1 || string.IsNullOrWhiteSpace(arguments[0]) || arguments[0].StartsWith('-')) {
|
||||
return false;
|
||||
}
|
||||
|
||||
folderPath = null;
|
||||
return false;
|
||||
string fullPath;
|
||||
try {
|
||||
fullPath = Path.GetFullPath(arguments[0]);
|
||||
} 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.
|
||||
return false;
|
||||
}
|
||||
|
||||
// Existence is checked here so every caller gets an already validated folder.
|
||||
if (!Directory.Exists(fullPath)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
folderPath = fullPath;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -10,8 +10,7 @@ namespace YKanBan.Models;
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public readonly record struct RgbColor(byte R, byte G, byte B)
|
||||
{
|
||||
public readonly record struct RgbColor(byte R, byte G, byte B) {
|
||||
/// <summary>
|
||||
/// Parses a "#RRGGBB" text with case-insensitive hex digits.
|
||||
/// </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="color">The parsed color on success, otherwise the default value.</param>
|
||||
/// <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;
|
||||
if (text is not { Length: 7 } || text[0] != '#')
|
||||
{
|
||||
if (text is not { Length: 7 } || text[0] != '#') {
|
||||
return false;
|
||||
}
|
||||
|
||||
// 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);
|
||||
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="value">The parsed byte value.</param>
|
||||
/// <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;
|
||||
int high = HexDigit(text[start]);
|
||||
int low = HexDigit(text[start + 1]);
|
||||
if (high < 0 || low < 0)
|
||||
{
|
||||
if (high < 0 || low < 0) {
|
||||
return false;
|
||||
}
|
||||
value = (byte)((high << 4) | low);
|
||||
@@ -77,8 +71,7 @@ public readonly record struct RgbColor(byte R, byte G, byte B)
|
||||
/// </summary>
|
||||
/// <param name="character">The character to convert.</param>
|
||||
/// <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',
|
||||
>= 'a' and <= 'f' => character - 'a' + 10,
|
||||
>= 'A' and <= 'F' => character - 'A' + 10,
|
||||
|
||||
+2
-4
@@ -2,14 +2,12 @@
|
||||
|
||||
namespace YKanBan;
|
||||
|
||||
sealed class Program
|
||||
{
|
||||
sealed class Program {
|
||||
// Initialization code. Don't use any Avalonia, third-party APIs or any
|
||||
// SynchronizationContext-reliant code before AppMain is called: things aren't initialized
|
||||
// yet and stuff might break.
|
||||
[STAThread]
|
||||
public static void Main(string[] args)
|
||||
{
|
||||
public static void Main(string[] args) {
|
||||
BuildAvaloniaApp().StartWithClassicDesktopLifetime(args);
|
||||
|
||||
// The lifetime has ended: persist the configuration once, then release services.
|
||||
|
||||
@@ -5,8 +5,7 @@ namespace YKanBan.Search;
|
||||
/// <summary>
|
||||
/// Lexical tokens of the search syntax.
|
||||
/// </summary>
|
||||
public abstract record SearchToken
|
||||
{
|
||||
public abstract record SearchToken {
|
||||
/// <summary>
|
||||
/// A bare word; qualifier detection happens later from the text.
|
||||
/// </summary>
|
||||
@@ -35,12 +34,14 @@ public abstract record SearchToken
|
||||
/// quoted phrases and parentheses; whitespace only separates tokens.
|
||||
///
|
||||
/// 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, and an
|
||||
/// unterminated phrase is rejected. Any input not covered by the token rules
|
||||
/// is rejected rather than silently ignored.
|
||||
/// escapes, a bare backslash or an unknown escape is rejected, a backslash in a
|
||||
/// bare word is rejected, and an unterminated phrase is rejected. A phrase
|
||||
/// 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>
|
||||
public static class SearchLexer
|
||||
{
|
||||
public static class SearchLexer {
|
||||
/// <summary>A valid phrase escape sequence: <c>\"</c> or <c>\\</c>.</summary>
|
||||
private static readonly Parser<char, char> PhraseEscape =
|
||||
Parser.Try(Parser.String("\\\"").Select(_ => '"'))
|
||||
@@ -62,43 +63,99 @@ public static class SearchLexer
|
||||
private static readonly Parser<char, SearchToken> CloseParenParser =
|
||||
Parser.Char(')').Select(_ => (SearchToken)new SearchToken.CloseParen());
|
||||
|
||||
// ':' stays inside the word token (the parser splits qualifiers); a backslash
|
||||
// is not a word character, so a bare one is left over and rejected by End.
|
||||
private static readonly Parser<char, SearchToken> WordParser =
|
||||
Parser<char>.Token(character =>
|
||||
!char.IsWhiteSpace(character) && character != '(' && character != ')' && character != '"')
|
||||
!char.IsWhiteSpace(character) && character != '(' && character != ')' && character != '"' && character != '\\')
|
||||
.AtLeastOnce()
|
||||
.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(
|
||||
PhraseParser
|
||||
from start in Parser<char>.CurrentOffset
|
||||
from token in PhraseParser
|
||||
.Or(OpenParenParser)
|
||||
.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
|
||||
// then rejects any leftover input, which turns dangling quotes or invalid
|
||||
// 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()
|
||||
.Before(Parser.SkipWhitespaces)
|
||||
.Before(Parser<char>.End)
|
||||
.Select(tokens => (IReadOnlyList<SearchToken>)tokens.ToList());
|
||||
.Select(tokens => (IReadOnlyList<PositionedToken>)tokens.ToList());
|
||||
|
||||
/// <summary>
|
||||
/// Tokenizes the search text.
|
||||
/// </summary>
|
||||
/// <param name="input">The raw search text.</param>
|
||||
/// <returns>The token stream.</returns>
|
||||
/// <exception cref="SearchSyntaxException">The text contains an invalid escape or an unterminated phrase.</exception>
|
||||
public static IReadOnlyList<SearchToken> Tokenize(string input)
|
||||
{
|
||||
try
|
||||
{
|
||||
return Lexer.ParseOrThrow(input);
|
||||
}
|
||||
catch (ParseException exception)
|
||||
{
|
||||
/// <exception cref="SearchSyntaxException">
|
||||
/// 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.
|
||||
/// </exception>
|
||||
public static IReadOnlyList<SearchToken> Tokenize(string input) {
|
||||
IReadOnlyList<PositionedToken> tokens;
|
||||
try {
|
||||
tokens = Lexer.ParseOrThrow(input);
|
||||
} catch (ParseException 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);
|
||||
}
|
||||
@@ -10,8 +10,7 @@ namespace YKanBan.Search;
|
||||
/// Root of the search query AST. Search keywords are fixed English grammar
|
||||
/// and are never localized.
|
||||
/// </summary>
|
||||
public abstract record SearchNode
|
||||
{
|
||||
public abstract record SearchNode {
|
||||
/// <summary>
|
||||
/// Disjunction: matches when any term matches (OR).
|
||||
/// </summary>
|
||||
@@ -59,11 +58,14 @@ public abstract record SearchNode
|
||||
/// <summary>
|
||||
/// The card fields a <see cref="SearchNode.FieldText"/> atom can scope to.
|
||||
/// </summary>
|
||||
public enum SearchField
|
||||
{
|
||||
/// <summary>The card title.</summary>
|
||||
public enum SearchField {
|
||||
/// <summary>
|
||||
/// The card title.
|
||||
/// </summary>
|
||||
Title,
|
||||
|
||||
/// <summary>The card content body.</summary>
|
||||
/// <summary>
|
||||
/// The card content body.
|
||||
/// </summary>
|
||||
Content,
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
using System.Globalization;
|
||||
|
||||
using Pidgin;
|
||||
|
||||
namespace YKanBan.Search;
|
||||
@@ -6,16 +7,17 @@ namespace YKanBan.Search;
|
||||
/// <summary>
|
||||
/// Parses the search grammar with Pidgin, strictly: any malformed input
|
||||
/// (unbalanced parentheses, dangling or consecutive operators, unterminated
|
||||
/// phrases, invalid escapes, qualifier keys without a value or with an
|
||||
/// unknown/non-numeric id value) raises <see cref="SearchSyntaxException"/>.
|
||||
/// phrases, invalid escapes, a backslash in a bare word, unknown qualifier
|
||||
/// keys, qualifiers without a value, unquoted values containing ':' or equal
|
||||
/// to AND/OR, and id values that are not an unquoted positive integer with an
|
||||
/// optional '#') raises <see cref="SearchSyntaxException"/>.
|
||||
///
|
||||
/// Only uppercase AND/OR are operators (lowercase ones are plain words); AND —
|
||||
/// explicit or by adjacency — binds tighter than OR; parentheses group. Blank
|
||||
/// input returns null and means "show everything". Search keywords and
|
||||
/// qualifier keys are fixed English grammar and are never localized.
|
||||
/// </summary>
|
||||
public static class SearchQueryParser
|
||||
{
|
||||
public static class SearchQueryParser {
|
||||
/// <summary>The recognized qualifier keys; add new entries here to extend the grammar.</summary>
|
||||
private static readonly (string Key, QualifierKind Kind)[] QualifierTable =
|
||||
[
|
||||
@@ -102,20 +104,20 @@ public static class SearchQueryParser
|
||||
/// <param name="text">The raw search text.</param>
|
||||
/// <returns>The parsed query, or <see langword="null"/> for blank input (meaning: show everything).</returns>
|
||||
/// <exception cref="SearchSyntaxException">The text violates the grammar.</exception>
|
||||
public static SearchNode? Parse(string text)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(text))
|
||||
{
|
||||
public static SearchNode? Parse(string text) {
|
||||
if (string.IsNullOrWhiteSpace(text)) {
|
||||
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();
|
||||
return Query.ParseOrThrow(tokens);
|
||||
}
|
||||
catch (ParseException exception)
|
||||
{
|
||||
} catch (ParseException exception) {
|
||||
throw new SearchSyntaxException(exception.Message, exception);
|
||||
}
|
||||
}
|
||||
@@ -128,70 +130,88 @@ public static class SearchQueryParser
|
||||
/// </summary>
|
||||
/// <param name="word">The word token text.</param>
|
||||
/// <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(':');
|
||||
|
||||
// Only a leading run of letters/digits/underscores before ':' can be a qualifier key.
|
||||
if (colonIndex <= 0 || !IsQualifierKeyCandidate(word.AsSpan(0, colonIndex)))
|
||||
{
|
||||
if (colonIndex < 0) {
|
||||
return Parser<SearchToken>.Return<SearchNode>(new SearchNode.FreeText(word));
|
||||
}
|
||||
|
||||
// Any ':' in a bare word makes it a qualifier, so the text before it must be a known key.
|
||||
string key = word[..colonIndex];
|
||||
string value = word[(colonIndex + 1)..];
|
||||
|
||||
if (!TryLookupQualifier(key, out QualifierKind kind))
|
||||
{
|
||||
return Parser<SearchToken>.Fail<SearchNode>($"Unknown qualifier key '{key}'.");
|
||||
if (!TryLookupQualifier(key, out QualifierKind kind)) {
|
||||
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".
|
||||
return value.Length == 0
|
||||
? PhraseText.Bind(text => AtomParser(kind, text))
|
||||
: AtomParser(kind, value);
|
||||
if (value.Length == 0) {
|
||||
return kind == QualifierKind.Id
|
||||
? Parser<SearchToken>.Fail<SearchNode>("The id qualifier expects an unquoted positive integer.")
|
||||
: PhraseText.Select(phrase => TextAtom(kind, phrase));
|
||||
}
|
||||
|
||||
if (value.Contains(':')) {
|
||||
return Parser<SearchToken>.Fail<SearchNode>($"Unquoted value '{value}' of qualifier '{key}' contains ':'; quote the value.");
|
||||
}
|
||||
|
||||
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.");
|
||||
}
|
||||
|
||||
if (kind == QualifierKind.Id) {
|
||||
return TryParseCardId(value, out long id)
|
||||
? Parser<SearchToken>.Return<SearchNode>(new SearchNode.CardId(id))
|
||||
: Parser<SearchToken>.Fail<SearchNode>($"The id qualifier expects a positive integer, got '{value}'.");
|
||||
}
|
||||
|
||||
return Parser<SearchToken>.Return(TextAtom(kind, value));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the atom parser for a qualifier value, failing strictly on a non-numeric id.
|
||||
/// Builds the atom for a textual qualifier value.
|
||||
/// </summary>
|
||||
/// <param name="kind">The qualifier kind.</param>
|
||||
/// <param name="kind">The qualifier kind; never <see cref="QualifierKind.Id"/>.</param>
|
||||
/// <param name="value">The qualifier value.</param>
|
||||
/// <returns>The parser producing the atom node.</returns>
|
||||
private static Parser<SearchToken, SearchNode> AtomParser(QualifierKind kind, string value) =>
|
||||
AtomFrom(kind, value) is { } atom
|
||||
? Parser<SearchToken>.Return(atom)
|
||||
: Parser<SearchToken>.Fail<SearchNode>($"The id qualifier expects an integer, got '{value}'.");
|
||||
|
||||
/// <summary>
|
||||
/// Builds the atom for a qualifier value; null when an id value is not an integer.
|
||||
/// </summary>
|
||||
/// <param name="kind">The qualifier kind.</param>
|
||||
/// <param name="value">The qualifier value.</param>
|
||||
/// <returns>The atom node, or <see langword="null"/> for an invalid id value.</returns>
|
||||
private static SearchNode? AtomFrom(QualifierKind kind, string value) => kind switch
|
||||
{
|
||||
/// <returns>The atom node.</returns>
|
||||
private static SearchNode TextAtom(QualifierKind kind, string value) => kind switch {
|
||||
QualifierKind.Tag => new SearchNode.TagName(value),
|
||||
QualifierKind.Title => new SearchNode.FieldText(SearchField.Title, value),
|
||||
QualifierKind.Content => new SearchNode.FieldText(SearchField.Content, value),
|
||||
QualifierKind.Column => new SearchNode.ColumnTitle(value),
|
||||
QualifierKind.Id when long.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out long id) =>
|
||||
new SearchNode.CardId(id),
|
||||
_ => null,
|
||||
_ => throw new InvalidOperationException($"Qualifier kind {kind} has no textual value."),
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Parses an id qualifier value: decimal digits with an optional leading
|
||||
/// <c>#</c>, denoting a positive integer.
|
||||
/// </summary>
|
||||
/// <param name="value">The inline qualifier value.</param>
|
||||
/// <param name="id">The parsed card id.</param>
|
||||
/// <returns><see langword="true"/> when the value is a valid positive card id.</returns>
|
||||
private static bool TryParseCardId(string value, out long id) {
|
||||
ReadOnlySpan<char> digits = value.AsSpan();
|
||||
if (digits.StartsWith("#")) {
|
||||
digits = digits[1..];
|
||||
}
|
||||
|
||||
// Digits only: the span check rules out signs, whitespace and other NumberStyles leniency.
|
||||
id = 0;
|
||||
return digits.Length > 0
|
||||
&& !digits.ContainsAnyExceptInRange('0', '9')
|
||||
&& long.TryParse(digits, NumberStyles.None, CultureInfo.InvariantCulture, out id)
|
||||
&& id > 0;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Looks up a qualifier key in the extension table with ordinal (case-sensitive) matching.
|
||||
/// </summary>
|
||||
/// <param name="key">The key text before the colon.</param>
|
||||
/// <param name="kind">The matching qualifier kind.</param>
|
||||
/// <returns><see langword="true"/> when the key is known.</returns>
|
||||
private static bool TryLookupQualifier(string key, out QualifierKind kind)
|
||||
{
|
||||
foreach ((string candidate, QualifierKind candidateKind) in QualifierTable)
|
||||
{
|
||||
if (string.Equals(candidate, key, StringComparison.Ordinal))
|
||||
{
|
||||
private static bool TryLookupQualifier(string key, out QualifierKind kind) {
|
||||
foreach ((string candidate, QualifierKind candidateKind) in QualifierTable) {
|
||||
if (string.Equals(candidate, key, StringComparison.Ordinal)) {
|
||||
kind = candidateKind;
|
||||
return true;
|
||||
}
|
||||
@@ -201,33 +221,13 @@ public static class SearchQueryParser
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns whether the text looks like a qualifier key: a non-empty run of
|
||||
/// letters, digits or underscores.
|
||||
/// </summary>
|
||||
/// <param name="text">The candidate key text.</param>
|
||||
/// <returns><see langword="true"/> when every character is a word character.</returns>
|
||||
private static bool IsQualifierKeyCandidate(ReadOnlySpan<char> text)
|
||||
{
|
||||
foreach (char character in text)
|
||||
{
|
||||
if (!(char.IsLetterOrDigit(character) || character == '_'))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Collapses an AND chain into a single node.
|
||||
/// </summary>
|
||||
/// <param name="first">The first operand.</param>
|
||||
/// <param name="rest">The remaining operands.</param>
|
||||
/// <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];
|
||||
return terms.Count == 1 ? terms[0] : new SearchNode.And(terms);
|
||||
}
|
||||
@@ -237,8 +237,7 @@ public static class SearchQueryParser
|
||||
/// </summary>
|
||||
/// <param name="terms">The operands.</param>
|
||||
/// <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();
|
||||
return list.Count == 1 ? list[0] : new SearchNode.Or(list);
|
||||
}
|
||||
@@ -246,8 +245,7 @@ public static class SearchQueryParser
|
||||
#endregion
|
||||
|
||||
/// <summary>The recognized qualifier kinds.</summary>
|
||||
private enum QualifierKind
|
||||
{
|
||||
private enum QualifierKind {
|
||||
Tag,
|
||||
Title,
|
||||
Content,
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
using YKanBan.Storage;
|
||||
|
||||
namespace YKanBan.Search;
|
||||
|
||||
/// <summary>
|
||||
@@ -10,20 +12,19 @@ public sealed record CompiledSearch(string Predicate, IReadOnlyList<(string Name
|
||||
|
||||
/// <summary>
|
||||
/// Compiles a parsed search AST into a parameterized SQL predicate. Matching is
|
||||
/// case-insensitive with SQLite's built-in semantics: LIKE's default case
|
||||
/// folding for substring matches plus COLLATE NOCASE for exact matches. LIKE
|
||||
/// wildcards and the escape character in user text are escaped so they match
|
||||
/// literally.
|
||||
/// Unicode case-insensitive: both sides are folded with
|
||||
/// <see cref="SqliteDatabase.Fold"/> (the column side through the per-connection
|
||||
/// <see cref="SqliteDatabase.FoldFunctionName"/> function) and then compared
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public static class SearchSqlCompiler
|
||||
{
|
||||
public static class SearchSqlCompiler {
|
||||
/// <summary>
|
||||
/// Compiles the query into a SQL predicate.
|
||||
/// </summary>
|
||||
/// <param name="query">The parsed search AST.</param>
|
||||
/// <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)>();
|
||||
string predicate = Build(query, parameters);
|
||||
return new CompiledSearch(predicate, parameters);
|
||||
@@ -35,49 +36,41 @@ public static class SearchSqlCompiler
|
||||
/// <param name="node">The AST node to compile.</param>
|
||||
/// <param name="parameters">The parameter accumulator.</param>
|
||||
/// <returns>The SQL boolean expression for the node.</returns>
|
||||
private static string Build(SearchNode node, List<(string Name, object Value)> parameters)
|
||||
{
|
||||
switch (node)
|
||||
{
|
||||
private static string Build(SearchNode node, List<(string Name, object Value)> parameters) {
|
||||
switch (node) {
|
||||
case SearchNode.And and:
|
||||
return "(" + string.Join(" AND ", and.Terms.Select(term => Build(term, parameters))) + ")";
|
||||
|
||||
case SearchNode.Or or:
|
||||
return "(" + string.Join(" OR ", or.Terms.Select(term => Build(term, parameters))) + ")";
|
||||
|
||||
case SearchNode.FreeText freeText:
|
||||
{
|
||||
// A bare word matches a substring of the title OR the content.
|
||||
string titleParam = AddParameter(parameters, "%" + EscapeLike(freeText.Text) + "%");
|
||||
string contentParam = AddParameter(parameters, "%" + EscapeLike(freeText.Text) + "%");
|
||||
return $"(c.title LIKE {titleParam} ESCAPE '\\' OR c.content LIKE {contentParam} ESCAPE '\\')";
|
||||
}
|
||||
case SearchNode.FreeText freeText: {
|
||||
// A bare word matches a substring of the title OR the content.
|
||||
string param = AddParameter(parameters, SqliteDatabase.Fold(freeText.Text));
|
||||
return $"({Contains("c.title", param)} OR {Contains("c.content", param)})";
|
||||
}
|
||||
|
||||
case SearchNode.FieldText field:
|
||||
{
|
||||
string column = field.Field == SearchField.Title ? "c.title" : "c.content";
|
||||
string param = AddParameter(parameters, "%" + EscapeLike(field.Text) + "%");
|
||||
return $"{column} LIKE {param} ESCAPE '\\'";
|
||||
}
|
||||
case SearchNode.FieldText field: {
|
||||
string column = field.Field == SearchField.Title ? "c.title" : "c.content";
|
||||
string param = AddParameter(parameters, SqliteDatabase.Fold(field.Text));
|
||||
return Contains(column, param);
|
||||
}
|
||||
|
||||
case SearchNode.TagName tag:
|
||||
{
|
||||
string param = AddParameter(parameters, tag.Name);
|
||||
return "EXISTS (SELECT 1 FROM card_tags ct JOIN tags t ON t.id = ct.tag_id " +
|
||||
$"WHERE ct.card_id = c.id AND t.name COLLATE NOCASE = {param})";
|
||||
}
|
||||
case SearchNode.TagName tag: {
|
||||
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 " +
|
||||
$"WHERE ct.card_id = c.id AND {Folded("t.name")} = {param})";
|
||||
}
|
||||
|
||||
case SearchNode.ColumnTitle column:
|
||||
{
|
||||
string param = AddParameter(parameters, column.Title);
|
||||
return $"c.column_id IN (SELECT id FROM columns WHERE title COLLATE NOCASE = {param})";
|
||||
}
|
||||
case SearchNode.ColumnTitle column: {
|
||||
string param = AddParameter(parameters, SqliteDatabase.Fold(column.Title));
|
||||
return $"c.column_id IN (SELECT id FROM columns WHERE {Folded("title")} = {param})";
|
||||
}
|
||||
|
||||
case SearchNode.CardId id:
|
||||
{
|
||||
string param = AddParameter(parameters, id.Id);
|
||||
return $"c.id = {param}";
|
||||
}
|
||||
case SearchNode.CardId id: {
|
||||
string param = AddParameter(parameters, id.Id);
|
||||
return $"c.id = {param}";
|
||||
}
|
||||
|
||||
default:
|
||||
throw new InvalidOperationException($"Unsupported search node: {node.GetType().Name}");
|
||||
@@ -90,18 +83,24 @@ public static class SearchSqlCompiler
|
||||
/// <param name="parameters">The parameter accumulator.</param>
|
||||
/// <param name="value">The value to bind.</param>
|
||||
/// <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);
|
||||
parameters.Add((name, value));
|
||||
return name;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Escapes LIKE wildcards and the escape character inside user text.
|
||||
/// Wraps a column expression in the case-folding SQL function.
|
||||
/// </summary>
|
||||
/// <param name="text">The raw user text.</param>
|
||||
/// <returns>The text with <c>\</c>, <c>%</c> and <c>_</c> escaped.</returns>
|
||||
private static string EscapeLike(string text) =>
|
||||
text.Replace("\\", "\\\\").Replace("%", "\\%").Replace("_", "\\_");
|
||||
/// <param name="column">The column expression.</param>
|
||||
/// <returns>The folded column expression.</returns>
|
||||
private static string Folded(string column) => $"{SqliteDatabase.FoldFunctionName}({column})";
|
||||
|
||||
/// <summary>
|
||||
/// Builds an ordinal substring test of a folded column against an already folded parameter.
|
||||
/// </summary>
|
||||
/// <param name="column">The column expression.</param>
|
||||
/// <param name="param">The placeholder of the folded search text.</param>
|
||||
/// <returns>The SQL boolean expression.</returns>
|
||||
private static string Contains(string column, string param) => $"instr({Folded(column)}, {param}) > 0";
|
||||
}
|
||||
@@ -6,15 +6,21 @@ namespace YKanBan.Search;
|
||||
/// search error instead of coupling to Pidgin types. The message is never
|
||||
/// localized.
|
||||
/// </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>
|
||||
/// Initializes the exception with a descriptive English message.
|
||||
/// </summary>
|
||||
/// <param name="message">The English diagnostic message.</param>
|
||||
/// <param name="innerException">The underlying parse failure.</param>
|
||||
public SearchSyntaxException(string message, Exception innerException)
|
||||
: base(message, innerException)
|
||||
{
|
||||
: base(message, innerException) {
|
||||
}
|
||||
}
|
||||
@@ -8,13 +8,11 @@ namespace YKanBan.Services;
|
||||
/// the single open workspace session. The configuration is persisted once at
|
||||
/// shutdown; the session (lock plus connection) lives until disposal.
|
||||
/// </summary>
|
||||
public sealed class AppServices : IDisposable
|
||||
{
|
||||
public sealed class AppServices : IDisposable {
|
||||
/// <summary>
|
||||
/// Loads the configuration and prepares the service graph.
|
||||
/// </summary>
|
||||
public AppServices()
|
||||
{
|
||||
public AppServices() {
|
||||
ConfigStore = new AppConfigStore(AppDataPaths.AppConfigJsonPath);
|
||||
Config = ConfigStore.Load();
|
||||
}
|
||||
@@ -42,15 +40,38 @@ public sealed class AppServices : IDisposable
|
||||
/// <returns>The open session.</returns>
|
||||
/// <exception cref="YKanBan.Storage.WorkspaceNotInitializedException">The folder has no .ykanban structure.</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);
|
||||
return Session;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a fresh workspace and opens it, holding the lock throughout.
|
||||
/// </summary>
|
||||
/// <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>
|
||||
|
||||
@@ -1,49 +1,88 @@
|
||||
using System.Runtime.Serialization;
|
||||
|
||||
using Newtonsoft.Json;
|
||||
|
||||
namespace YKanBan.Storage.AppData;
|
||||
|
||||
/// <summary>
|
||||
/// Card ordering options. Every order falls back to id ascending as the final
|
||||
/// tie-breaker.
|
||||
/// Display ordering options, used for both cards and columns. Except for the id
|
||||
/// order, every option falls back to id ascending as the final tie-breaker.
|
||||
/// </summary>
|
||||
public enum CardSortOption
|
||||
{
|
||||
/// <summary>Primary key ascending (default).</summary>
|
||||
[EnumMember(Value = "id")]
|
||||
Id,
|
||||
public enum SortOption {
|
||||
/// <summary>
|
||||
/// Primary key ascending.
|
||||
/// </summary>
|
||||
[EnumMember(Value = "id-asc")]
|
||||
IdAscending,
|
||||
|
||||
/// <summary>Creation time, oldest first.</summary>
|
||||
[EnumMember(Value = "created-at")]
|
||||
CreatedAt,
|
||||
/// <summary>
|
||||
/// Primary key descending.
|
||||
/// </summary>
|
||||
[EnumMember(Value = "id-desc")]
|
||||
IdDescending,
|
||||
|
||||
/// <summary>Last modification time, most recently modified first.</summary>
|
||||
[EnumMember(Value = "updated-at")]
|
||||
UpdatedAt,
|
||||
/// <summary>
|
||||
/// Creation time ascending.
|
||||
/// </summary>
|
||||
[EnumMember(Value = "created-asc")]
|
||||
CreatedAscending,
|
||||
|
||||
/// <summary>Title by code points (BINARY collation); empty titles sort first.</summary>
|
||||
[EnumMember(Value = "title")]
|
||||
Title,
|
||||
/// <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>
|
||||
/// Column width presets. <see cref="Custom"/> uses a user-defined pixel width.
|
||||
/// </summary>
|
||||
public enum ColumnWidthPreset
|
||||
{
|
||||
/// <summary>Narrow preset.</summary>
|
||||
public enum ColumnWidthPreset {
|
||||
/// <summary>
|
||||
/// Narrow preset.
|
||||
/// </summary>
|
||||
[EnumMember(Value = "narrow")]
|
||||
Narrow,
|
||||
|
||||
/// <summary>Standard preset (320 px, the default).</summary>
|
||||
/// <summary>
|
||||
/// Standard preset (320 px, the default).
|
||||
/// </summary>
|
||||
[EnumMember(Value = "standard")]
|
||||
Standard,
|
||||
|
||||
/// <summary>Wide preset.</summary>
|
||||
/// <summary>
|
||||
/// Wide preset.
|
||||
/// </summary>
|
||||
[EnumMember(Value = "wide")]
|
||||
Wide,
|
||||
|
||||
/// <summary>User-defined pixel width (160–720).</summary>
|
||||
/// <summary>
|
||||
/// User-defined pixel width (160–720).
|
||||
/// </summary>
|
||||
[EnumMember(Value = "custom")]
|
||||
Custom,
|
||||
}
|
||||
@@ -51,38 +90,30 @@ public enum ColumnWidthPreset
|
||||
/// <summary>
|
||||
/// UI theme selection.
|
||||
/// </summary>
|
||||
public enum ThemeOption
|
||||
{
|
||||
/// <summary>Always light.</summary>
|
||||
public enum ThemeOption {
|
||||
/// <summary>
|
||||
/// Always light.
|
||||
/// </summary>
|
||||
[EnumMember(Value = "light")]
|
||||
Light,
|
||||
|
||||
/// <summary>Always dark.</summary>
|
||||
/// <summary>
|
||||
/// Always dark.
|
||||
/// </summary>
|
||||
[EnumMember(Value = "dark")]
|
||||
Dark,
|
||||
|
||||
/// <summary>Follow the operating system setting (default).</summary>
|
||||
/// <summary>
|
||||
/// Follow the operating system setting (default).
|
||||
/// </summary>
|
||||
[EnumMember(Value = "follow-system")]
|
||||
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>
|
||||
/// Board column width settings, applied globally.
|
||||
/// </summary>
|
||||
public sealed class ColumnWidthSettings
|
||||
{
|
||||
public sealed class ColumnWidthSettings {
|
||||
/// <summary>
|
||||
/// Gets or sets the active width preset.
|
||||
/// </summary>
|
||||
@@ -97,11 +128,34 @@ public sealed class ColumnWidthSettings
|
||||
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>
|
||||
/// Confirmation-dialog toggles for the destructive actions.
|
||||
/// </summary>
|
||||
public sealed class ConfirmationSettings
|
||||
{
|
||||
public sealed class ConfirmationSettings {
|
||||
/// <summary>
|
||||
/// Gets or sets whether deleting a card asks for confirmation.
|
||||
/// </summary>
|
||||
@@ -133,8 +187,7 @@ public sealed class ConfirmationSettings
|
||||
/// <see cref="JsonPropertyAttribute"/> and <see cref="EnumMemberAttribute"/>).
|
||||
/// The <c>version</c> field is the migration hook for future format changes.
|
||||
/// </summary>
|
||||
public sealed class AppConfig
|
||||
{
|
||||
public sealed class AppConfig {
|
||||
/// <summary>
|
||||
/// Current configuration format version.
|
||||
/// </summary>
|
||||
@@ -164,16 +217,10 @@ public sealed class AppConfig
|
||||
public ThemeOption Theme { get; set; } = ThemeOption.FollowSystem;
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the card ordering settings.
|
||||
/// Gets or sets the board display settings (width and ordering).
|
||||
/// </summary>
|
||||
[JsonProperty("sort")]
|
||||
public SortSettings Sort { get; set; } = new();
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the board column width settings.
|
||||
/// </summary>
|
||||
[JsonProperty("column-width")]
|
||||
public ColumnWidthSettings ColumnWidth { get; set; } = new();
|
||||
[JsonProperty("display")]
|
||||
public DisplaySettings Display { get; set; } = new();
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the confirmation-dialog settings.
|
||||
|
||||
@@ -4,20 +4,23 @@ using Newtonsoft.Json.Converters;
|
||||
namespace YKanBan.Storage.AppData;
|
||||
|
||||
/// <summary>
|
||||
/// Loads and saves app.json with graceful degradation: a missing file yields
|
||||
/// defaults; a corrupt file is backed up to app.json.bak and then defaults are
|
||||
/// used. Saving writes the file directly (no atomic replace) — losing the last
|
||||
/// session's settings to a crash is an accepted trade-off.
|
||||
/// Loads and saves app.json with graceful degradation: a missing or unreadable
|
||||
/// file yields defaults; a corrupt file is backed up to app.json.bak and then
|
||||
/// defaults are used. Saving writes the file directly (no atomic replace) —
|
||||
/// losing the last session's settings to a crash is an accepted trade-off.
|
||||
/// </summary>
|
||||
public sealed class AppConfigStore
|
||||
{
|
||||
private static readonly JsonSerializerSettings SerializerSettings = new()
|
||||
{
|
||||
public sealed class AppConfigStore {
|
||||
private static readonly JsonSerializerSettings SerializerSettings = new() {
|
||||
Formatting = Formatting.Indented,
|
||||
NullValueHandling = NullValueHandling.Ignore,
|
||||
|
||||
// Enums round-trip through the kebab-case strings declared via [EnumMember].
|
||||
Converters = { new StringEnumConverter() },
|
||||
// Enums round-trip through the kebab-case strings declared via [EnumMember];
|
||||
// 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 } },
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
@@ -33,38 +36,42 @@ public sealed class AppConfigStore
|
||||
|
||||
/// <summary>
|
||||
/// Loads the configuration. A missing file yields defaults; a corrupt file
|
||||
/// is backed up to app.json.bak and then defaults are used.
|
||||
/// is backed up to app.json.bak and then defaults are used; a file that
|
||||
/// exists but cannot be read (I/O or permission error) also yields defaults.
|
||||
/// </summary>
|
||||
/// <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() {
|
||||
// Missing file is a normal first-run state: run with defaults.
|
||||
if (!File.Exists(FilePath))
|
||||
{
|
||||
if (!File.Exists(FilePath)) {
|
||||
return new AppConfig();
|
||||
}
|
||||
|
||||
string json = File.ReadAllText(FilePath);
|
||||
try
|
||||
{
|
||||
string json;
|
||||
try {
|
||||
json = File.ReadAllText(FilePath);
|
||||
} catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) {
|
||||
// A bad app.json must not stop startup.
|
||||
return new AppConfig();
|
||||
}
|
||||
|
||||
try {
|
||||
// A JSON null literal deserializes to null; treat it like defaults.
|
||||
AppConfig? config = JsonConvert.DeserializeObject<AppConfig>(json, SerializerSettings);
|
||||
if (config is null)
|
||||
{
|
||||
if (config is null) {
|
||||
return new AppConfig();
|
||||
}
|
||||
|
||||
// Older or hand-edited files may miss whole sections; each falls back to its defaults.
|
||||
config.Sort ??= new SortSettings();
|
||||
config.ColumnWidth ??= new ColumnWidthSettings();
|
||||
config.Display ??= new DisplaySettings();
|
||||
config.Confirmations ??= new ConfirmationSettings();
|
||||
return config;
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
// Corrupt: keep a copy for inspection, then continue with defaults.
|
||||
File.Copy(FilePath, FilePath + ".bak", overwrite: true);
|
||||
} catch (JsonException) {
|
||||
// Corrupt: keep a copy for inspection (best effort), then continue with defaults.
|
||||
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.
|
||||
}
|
||||
return new AppConfig();
|
||||
}
|
||||
}
|
||||
@@ -73,12 +80,10 @@ public sealed class AppConfigStore
|
||||
/// Writes the configuration directly to disk (no atomic replace).
|
||||
/// </summary>
|
||||
/// <param name="config">The configuration to serialize.</param>
|
||||
public void Save(AppConfig config)
|
||||
{
|
||||
public void Save(AppConfig config) {
|
||||
// Create the parent folder on demand; normally it already exists.
|
||||
string? directory = Path.GetDirectoryName(FilePath);
|
||||
if (!string.IsNullOrEmpty(directory))
|
||||
{
|
||||
if (!string.IsNullOrEmpty(directory)) {
|
||||
Directory.CreateDirectory(directory);
|
||||
}
|
||||
|
||||
|
||||
@@ -5,8 +5,7 @@ namespace YKanBan.Storage.AppData;
|
||||
/// (%APPDATA%/YKanBan on Windows and the equivalent directory on other
|
||||
/// platforms).
|
||||
/// </summary>
|
||||
public static class AppDataPaths
|
||||
{
|
||||
public static class AppDataPaths {
|
||||
/// <summary>
|
||||
/// Gets the per-user YKanBan application data folder.
|
||||
/// </summary>
|
||||
|
||||
@@ -7,8 +7,21 @@ namespace YKanBan.Storage;
|
||||
/// the mandated PRAGMA configuration (WAL journal, NORMAL synchronous mode,
|
||||
/// foreign keys on) and applies incremental <c>user_version</c> migrations.
|
||||
/// </summary>
|
||||
public static class SqliteDatabase
|
||||
{
|
||||
public static class SqliteDatabase {
|
||||
/// <summary>
|
||||
/// Name of the per-connection SQL function that applies <see cref="Fold"/>;
|
||||
/// search uses it for Unicode case-insensitive matching.
|
||||
/// </summary>
|
||||
public const string FoldFunctionName = "ykb_fold";
|
||||
|
||||
/// <summary>
|
||||
/// Unicode case folding shared by the SQL function and the search
|
||||
/// parameters it is compared against; comparisons after folding are ordinal.
|
||||
/// </summary>
|
||||
/// <param name="text">The text to fold.</param>
|
||||
/// <returns>The invariant lowercase form.</returns>
|
||||
public static string Fold(string text) => text.ToLowerInvariant();
|
||||
|
||||
/// <summary>
|
||||
/// Opens (creating if needed) a database file, applies the mandatory
|
||||
/// PRAGMAs and runs any pending migrations.
|
||||
@@ -16,10 +29,8 @@ public static class SqliteDatabase
|
||||
/// <param name="databasePath">Path of the SQLite database file.</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>
|
||||
public static SqliteConnection Open(string databasePath, IReadOnlyList<SchemaMigration> migrations)
|
||||
{
|
||||
var connection = new SqliteConnection(new SqliteConnectionStringBuilder
|
||||
{
|
||||
public static SqliteConnection Open(string databasePath, IReadOnlyList<SchemaMigration> migrations) {
|
||||
var connection = new SqliteConnection(new SqliteConnectionStringBuilder {
|
||||
DataSource = databasePath,
|
||||
Mode = SqliteOpenMode.ReadWriteCreate,
|
||||
|
||||
@@ -28,14 +39,12 @@ public static class SqliteDatabase
|
||||
}.ToString());
|
||||
|
||||
connection.Open();
|
||||
try
|
||||
{
|
||||
try {
|
||||
ApplyPragmas(connection);
|
||||
RegisterFunctions(connection);
|
||||
ApplyMigrations(connection, migrations);
|
||||
return connection;
|
||||
}
|
||||
catch
|
||||
{
|
||||
} catch {
|
||||
connection.Dispose();
|
||||
throw;
|
||||
}
|
||||
@@ -46,8 +55,7 @@ public static class SqliteDatabase
|
||||
/// </summary>
|
||||
/// <param name="connection">An open database connection.</param>
|
||||
/// <returns>The stored schema version.</returns>
|
||||
public static long ReadUserVersion(SqliteConnection connection)
|
||||
{
|
||||
public static long ReadUserVersion(SqliteConnection connection) {
|
||||
using var command = connection.CreateCommand();
|
||||
command.CommandText = "PRAGMA user_version;";
|
||||
return (long)command.ExecuteScalar()!;
|
||||
@@ -59,14 +67,24 @@ public static class SqliteDatabase
|
||||
/// enabled on every connection or the DDL cascades never fire.
|
||||
/// </summary>
|
||||
/// <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.
|
||||
Execute(connection, "PRAGMA journal_mode=WAL;");
|
||||
Execute(connection, "PRAGMA synchronous=NORMAL;");
|
||||
Execute(connection, "PRAGMA foreign_keys=ON;");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Registers the custom SQL functions; like the PRAGMAs they live on the
|
||||
/// connection and must be registered on every one.
|
||||
/// </summary>
|
||||
/// <param name="connection">An open database connection.</param>
|
||||
internal static void RegisterFunctions(SqliteConnection connection) {
|
||||
// NULL never reaches it from the NOT NULL text columns, but stays NULL-safe regardless.
|
||||
connection.CreateFunction<string?, string?>(
|
||||
FoldFunctionName, text => text is null ? null : Fold(text), isDeterministic: true);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Runs every migration newer than the stored <c>user_version</c>, each in
|
||||
/// its own transaction together with its version bump.
|
||||
@@ -75,13 +93,10 @@ public static class SqliteDatabase
|
||||
/// <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="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.
|
||||
for (int index = 0; index < migrations.Count; index++)
|
||||
{
|
||||
if (migrations[index].Version != index + 1)
|
||||
{
|
||||
for (int index = 0; index < migrations.Count; index++) {
|
||||
if (migrations[index].Version != index + 1) {
|
||||
throw new ArgumentException("Migrations must be contiguous and start at version 1.", nameof(migrations));
|
||||
}
|
||||
}
|
||||
@@ -90,16 +105,13 @@ public static class SqliteDatabase
|
||||
int latest = migrations.Count;
|
||||
|
||||
// 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);
|
||||
}
|
||||
|
||||
// Apply each pending migration atomically so a crash never leaves a half-migrated database.
|
||||
foreach (SchemaMigration migration in migrations)
|
||||
{
|
||||
if (migration.Version <= current)
|
||||
{
|
||||
foreach (SchemaMigration migration in migrations) {
|
||||
if (migration.Version <= current) {
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -116,8 +128,7 @@ public static class SqliteDatabase
|
||||
/// <param name="connection">An open database connection.</param>
|
||||
/// <param name="commandText">The SQL script to execute.</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();
|
||||
command.Transaction = transaction;
|
||||
command.CommandText = commandText;
|
||||
|
||||
@@ -5,24 +5,21 @@ namespace YKanBan.Storage;
|
||||
/// Exception messages are always English and never localized; the UI maps the
|
||||
/// exception type to a localized resource key instead.
|
||||
/// </summary>
|
||||
public abstract class YKanBanException : Exception
|
||||
{
|
||||
public abstract class YKanBanException : Exception {
|
||||
/// <summary>
|
||||
/// Initializes the exception with an English diagnostic message.
|
||||
/// </summary>
|
||||
/// <param name="message">The English diagnostic message.</param>
|
||||
/// <param name="innerException">The underlying cause, when any.</param>
|
||||
protected YKanBanException(string message, Exception? innerException = null)
|
||||
: base(message, innerException)
|
||||
{
|
||||
: base(message, innerException) {
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Signals that the folder passed on the command line does not exist on disk.
|
||||
/// </summary>
|
||||
public sealed class WorkspaceDirectoryMissingException : YKanBanException
|
||||
{
|
||||
public sealed class WorkspaceDirectoryMissingException : YKanBanException {
|
||||
/// <summary>
|
||||
/// Gets the folder path that was expected to exist.
|
||||
/// </summary>
|
||||
@@ -33,8 +30,7 @@ public sealed class WorkspaceDirectoryMissingException : YKanBanException
|
||||
/// </summary>
|
||||
/// <param name="folderPath">The missing folder path.</param>
|
||||
public WorkspaceDirectoryMissingException(string folderPath)
|
||||
: base($"The folder does not exist: {folderPath}")
|
||||
{
|
||||
: base($"The folder does not exist: {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
|
||||
/// (yet) a workspace.
|
||||
/// </summary>
|
||||
public sealed class WorkspaceNotInitializedException : YKanBanException
|
||||
{
|
||||
public sealed class WorkspaceNotInitializedException : YKanBanException {
|
||||
/// <summary>
|
||||
/// Gets the folder path that lacks the .ykanban structure.
|
||||
/// </summary>
|
||||
@@ -55,56 +50,49 @@ public sealed class WorkspaceNotInitializedException : YKanBanException
|
||||
/// </summary>
|
||||
/// <param name="folderPath">The uninitialized folder path.</param>
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
/// <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>
|
||||
/// Signals that another instance already holds the workspace lock, so this
|
||||
/// process must not touch the workspace.
|
||||
/// </summary>
|
||||
public sealed class WorkspaceLockException : YKanBanException
|
||||
{
|
||||
public sealed class WorkspaceLockException : YKanBanException {
|
||||
/// <summary>
|
||||
/// Gets the lock file that could not be acquired.
|
||||
/// </summary>
|
||||
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>
|
||||
/// Initializes the exception for a failed lock acquisition.
|
||||
/// </summary>
|
||||
/// <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>
|
||||
public WorkspaceLockException(string lockFilePath, string? holderDiagnostics, Exception innerException)
|
||||
: base(BuildMessage(lockFilePath, holderDiagnostics), innerException)
|
||||
{
|
||||
public WorkspaceLockException(string lockFilePath, Exception innerException)
|
||||
: base($"The workspace is locked by another instance: {lockFilePath}", innerException) {
|
||||
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
|
||||
/// currently running, so its schema cannot be safely managed.
|
||||
/// </summary>
|
||||
public sealed class SchemaVersionException : YKanBanException
|
||||
{
|
||||
public sealed class SchemaVersionException : YKanBanException {
|
||||
/// <summary>
|
||||
/// Gets the user_version value found in the database.
|
||||
/// </summary>
|
||||
@@ -130,8 +117,7 @@ public sealed class SchemaVersionException : YKanBanException
|
||||
/// <param name="storedVersion">The user_version read from the database.</param>
|
||||
/// <param name="supportedVersion">The newest schema version this build supports.</param>
|
||||
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;
|
||||
SupportedVersion = supportedVersion;
|
||||
}
|
||||
|
||||
@@ -4,8 +4,7 @@ namespace YKanBan.Storage;
|
||||
/// Supplies the current Unix timestamp. Every timestamp persisted by YKanBan
|
||||
/// is an INTEGER count of Unix seconds.
|
||||
/// </summary>
|
||||
public static class UnixTime
|
||||
{
|
||||
public static class UnixTime {
|
||||
/// <summary>
|
||||
/// Gets the current UTC time expressed as Unix seconds.
|
||||
/// </summary>
|
||||
|
||||
@@ -8,8 +8,7 @@ namespace YKanBan.Storage.Workspace;
|
||||
/// separate concern handled by <see cref="WorkspacePreset"/>, so the
|
||||
/// database can be created without any rows.
|
||||
/// </summary>
|
||||
public static class WorkspaceInitializer
|
||||
{
|
||||
public static class WorkspaceInitializer {
|
||||
/// <summary>
|
||||
/// Returns whether the folder contains a .ykanban structure. Only the
|
||||
/// 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>
|
||||
/// <exception cref="WorkspaceDirectoryMissingException">The folder does not exist on disk.</exception>
|
||||
/// <exception cref="InvalidOperationException">The workspace database already exists.</exception>
|
||||
public static void Initialize(string folderPath)
|
||||
{
|
||||
if (!Directory.Exists(folderPath))
|
||||
{
|
||||
public static void Initialize(string folderPath) {
|
||||
// YYC MARK: this class is deliberately a lock-free, functional unit; it
|
||||
// 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);
|
||||
}
|
||||
|
||||
string databasePath = WorkspacePaths.Database(folderPath);
|
||||
if (File.Exists(databasePath))
|
||||
{
|
||||
if (File.Exists(databasePath)) {
|
||||
throw new InvalidOperationException($"The workspace database already exists: {databasePath}");
|
||||
}
|
||||
|
||||
|
||||
@@ -1,14 +1,11 @@
|
||||
using System.Text;
|
||||
|
||||
namespace YKanBan.Storage.Workspace;
|
||||
|
||||
/// <summary>
|
||||
/// Exclusive, OS-enforced lock over a workspace's ykanban.lock. The handle is
|
||||
/// held until disposal, so crashes and power loss release it automatically.
|
||||
/// The lock file also carries PID / machine name / time for human diagnostics.
|
||||
/// held until disposal, so crashes and power loss release it automatically. The
|
||||
/// lock file is kept empty; only its exclusive OS handle carries meaning.
|
||||
/// </summary>
|
||||
public sealed class WorkspaceLock : IDisposable
|
||||
{
|
||||
public sealed class WorkspaceLock : IDisposable {
|
||||
private readonly FileStream _stream;
|
||||
|
||||
/// <summary>
|
||||
@@ -16,8 +13,7 @@ public sealed class WorkspaceLock : IDisposable
|
||||
/// </summary>
|
||||
/// <param name="stream">The exclusively opened lock file stream.</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;
|
||||
LockFilePath = lockFilePath;
|
||||
}
|
||||
@@ -28,61 +24,30 @@ public sealed class WorkspaceLock : IDisposable
|
||||
public string LockFilePath { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Acquires the workspace lock, writing this process's diagnostics into it.
|
||||
/// Acquires the workspace lock, leaving the lock file empty.
|
||||
/// </summary>
|
||||
/// <param name="folderPath">The workspace folder to lock.</param>
|
||||
/// <returns>The held lock; dispose it to release.</returns>
|
||||
/// <exception cref="WorkspaceNotInitializedException">The folder has no .ykanban structure.</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);
|
||||
FileStream stream;
|
||||
try
|
||||
{
|
||||
// FileShare.None gives the exclusive semantics; FileMode.Create truncates stale content.
|
||||
try {
|
||||
// FileShare.None gives the exclusive semantics; FileMode.Create empties any stale file.
|
||||
// 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);
|
||||
}
|
||||
catch (DirectoryNotFoundException)
|
||||
{
|
||||
} catch (DirectoryNotFoundException) {
|
||||
throw new WorkspaceNotInitializedException(folderPath);
|
||||
}
|
||||
catch (IOException ex)
|
||||
{
|
||||
throw new WorkspaceLockException(lockFilePath, ReadDiagnosticsBestEffort(lockFilePath), ex);
|
||||
} catch (IOException ex) {
|
||||
throw new WorkspaceLockException(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);
|
||||
}
|
||||
|
||||
/// <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>
|
||||
/// Releases the exclusive handle. The lock file itself is intentionally
|
||||
/// left on disk; the OS releases the handle even on a crash.
|
||||
|
||||
@@ -4,8 +4,7 @@ namespace YKanBan.Storage.Workspace;
|
||||
/// Well-known file and folder names inside a workspace's .ykanban structure,
|
||||
/// plus helpers that combine them with a workspace folder path.
|
||||
/// </summary>
|
||||
public static class WorkspacePaths
|
||||
{
|
||||
public static class WorkspacePaths {
|
||||
/// <summary>
|
||||
/// Name of the workspace root folder created inside a managed project.
|
||||
/// </summary>
|
||||
|
||||
@@ -3,48 +3,85 @@ using Microsoft.Data.Sqlite;
|
||||
namespace YKanBan.Storage.Workspace;
|
||||
|
||||
/// <summary>
|
||||
/// Adds the initial workspace content. The three preset column titles are read
|
||||
/// straight from the ResX resources in the UI language active when they are
|
||||
/// added; they then become ordinary data that no longer follows language
|
||||
/// switches.
|
||||
/// Adds the initial workspace content. The preset column titles/descriptions and
|
||||
/// tag names/descriptions are read straight from the ResX resources in the UI
|
||||
/// language active when they are added; they then become ordinary data that no
|
||||
/// longer follows language switches.
|
||||
/// </summary>
|
||||
public static class WorkspacePreset
|
||||
{
|
||||
public static class WorkspacePreset {
|
||||
/// <summary>
|
||||
/// 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>
|
||||
/// <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>
|
||||
public static void AddPresetColumns(string folderPath)
|
||||
{
|
||||
public static void AddPresetColumns(string folderPath) {
|
||||
using SqliteConnection connection = SqliteDatabase.Open(
|
||||
WorkspacePaths.Database(folderPath), WorkspaceSchema.Migrations);
|
||||
|
||||
long now = UnixTime.Now;
|
||||
|
||||
// Preset titles are data at creation time: whatever the current language says gets stored.
|
||||
string[] titles =
|
||||
// Preset titles and descriptions are data at creation time: whatever the current language says gets stored.
|
||||
(string Title, string Description)[] columns =
|
||||
[
|
||||
Resources.PresetColumn_Todo,
|
||||
Resources.PresetColumn_InProgress,
|
||||
Resources.PresetColumn_Done,
|
||||
(Resources.PresetColumn_Todo, Resources.PresetColumn_Todo_Description),
|
||||
(Resources.PresetColumn_InProgress, Resources.PresetColumn_InProgress_Description),
|
||||
(Resources.PresetColumn_Done, Resources.PresetColumn_Done_Description),
|
||||
];
|
||||
|
||||
// Insert all three atomically so a partially populated workspace can never exist.
|
||||
using var transaction = connection.BeginTransaction();
|
||||
foreach (string title in titles)
|
||||
{
|
||||
foreach ((string title, string description) in columns) {
|
||||
using var command = connection.CreateCommand();
|
||||
command.Transaction = transaction;
|
||||
command.CommandText = """
|
||||
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("$description", description);
|
||||
command.Parameters.AddWithValue("$now", now);
|
||||
command.ExecuteNonQuery();
|
||||
}
|
||||
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();
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,7 @@
|
||||
using Microsoft.Data.Sqlite;
|
||||
|
||||
using YKanBan.Models;
|
||||
using YKanBan.Search;
|
||||
|
||||
namespace YKanBan.Storage.Workspace;
|
||||
|
||||
@@ -13,16 +15,14 @@ namespace YKanBan.Storage.Workspace;
|
||||
/// - columns.updated_at refreshes only when title or description changes;
|
||||
/// - a confirmation with no effective change performs no write at all.
|
||||
/// </summary>
|
||||
public sealed class WorkspaceRepository : IDisposable
|
||||
{
|
||||
public sealed class WorkspaceRepository : IDisposable {
|
||||
private readonly SqliteConnection _connection;
|
||||
|
||||
/// <summary>
|
||||
/// Opens the repository over an initialized workspace database.
|
||||
/// </summary>
|
||||
/// <param name="folderPath">The workspace folder.</param>
|
||||
public WorkspaceRepository(string folderPath)
|
||||
{
|
||||
public WorkspaceRepository(string folderPath) {
|
||||
_connection = SqliteDatabase.Open(WorkspacePaths.Database(folderPath), WorkspaceSchema.Migrations);
|
||||
}
|
||||
|
||||
@@ -37,15 +37,13 @@ public sealed class WorkspaceRepository : IDisposable
|
||||
/// Returns all columns ordered by id ascending.
|
||||
/// </summary>
|
||||
/// <returns>All columns in id order.</returns>
|
||||
public IReadOnlyList<ColumnModel> GetColumns()
|
||||
{
|
||||
public IReadOnlyList<ColumnModel> GetColumns() {
|
||||
using var command = CreateCommand(
|
||||
"SELECT id, title, description, created_at, updated_at FROM columns ORDER BY id ASC;");
|
||||
using var reader = command.ExecuteReader();
|
||||
|
||||
var columns = new List<ColumnModel>();
|
||||
while (reader.Read())
|
||||
{
|
||||
while (reader.Read()) {
|
||||
columns.Add(ReadColumn(reader));
|
||||
}
|
||||
return columns;
|
||||
@@ -56,8 +54,7 @@ public sealed class WorkspaceRepository : IDisposable
|
||||
/// </summary>
|
||||
/// <param name="columnId">The column id.</param>
|
||||
/// <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(
|
||||
"SELECT id, title, description, created_at, updated_at FROM columns WHERE id = $id;");
|
||||
command.Parameters.AddWithValue("$id", columnId);
|
||||
@@ -72,8 +69,7 @@ public sealed class WorkspaceRepository : IDisposable
|
||||
/// <param name="description">The optional description.</param>
|
||||
/// <returns>The created column.</returns>
|
||||
/// <exception cref="SqliteException">The title is empty or not unique.</exception>
|
||||
public ColumnModel AddColumn(string title, string description)
|
||||
{
|
||||
public ColumnModel AddColumn(string title, string description) {
|
||||
long now = UnixTime.Now;
|
||||
using var transaction = _connection.BeginTransaction();
|
||||
long id = ExecuteInsert(transaction,
|
||||
@@ -94,14 +90,12 @@ public sealed class WorkspaceRepository : IDisposable
|
||||
/// <returns>The updated column, or the unchanged one for a no-op.</returns>
|
||||
/// <exception cref="InvalidOperationException">The column does not exist.</exception>
|
||||
/// <exception cref="SqliteException">The new title is empty or 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)
|
||||
?? throw new InvalidOperationException($"Column {columnId} does not exist.");
|
||||
|
||||
// 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;
|
||||
}
|
||||
|
||||
@@ -132,8 +126,7 @@ public sealed class WorkspaceRepository : IDisposable
|
||||
/// Returns all cards with their assigned tags loaded, ordered by id ascending.
|
||||
/// </summary>
|
||||
/// <returns>All cards in id order.</returns>
|
||||
public IReadOnlyList<CardModel> GetCards()
|
||||
{
|
||||
public IReadOnlyList<CardModel> GetCards() {
|
||||
using var command = CreateCommand("""
|
||||
SELECT c.id, c.column_id, c.title, c.content, c.created_at, c.updated_at,
|
||||
t.id, t.name, t.color, t.description
|
||||
@@ -147,11 +140,9 @@ public sealed class WorkspaceRepository : IDisposable
|
||||
// Single grouped pass: one output card per distinct card id, with its tags accumulated alongside.
|
||||
var cards = new List<CardModel>();
|
||||
var tagsByCard = new Dictionary<long, List<TagModel>>();
|
||||
while (reader.Read())
|
||||
{
|
||||
while (reader.Read()) {
|
||||
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>();
|
||||
tagsByCard[cardId] = tags;
|
||||
cards.Add(new CardModel(
|
||||
@@ -164,21 +155,38 @@ public sealed class WorkspaceRepository : IDisposable
|
||||
tags));
|
||||
}
|
||||
|
||||
if (!reader.IsDBNull(6))
|
||||
{
|
||||
if (!reader.IsDBNull(6)) {
|
||||
tags.Add(ReadTag(reader, 6));
|
||||
}
|
||||
}
|
||||
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>
|
||||
/// Returns the card with the given id, with its tags loaded.
|
||||
/// </summary>
|
||||
/// <param name="cardId">The card id.</param>
|
||||
/// <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("""
|
||||
SELECT c.id, c.column_id, c.title, c.content, c.created_at, c.updated_at,
|
||||
t.id, t.name, t.color, t.description
|
||||
@@ -194,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.
|
||||
CardModel? card = null;
|
||||
var tags = new List<TagModel>();
|
||||
while (reader.Read())
|
||||
{
|
||||
while (reader.Read()) {
|
||||
card ??= new CardModel(
|
||||
reader.GetInt64(0),
|
||||
reader.GetInt64(1),
|
||||
@@ -205,8 +212,7 @@ public sealed class WorkspaceRepository : IDisposable
|
||||
reader.GetInt64(5),
|
||||
tags);
|
||||
|
||||
if (!reader.IsDBNull(6))
|
||||
{
|
||||
if (!reader.IsDBNull(6)) {
|
||||
tags.Add(ReadTag(reader, 6));
|
||||
}
|
||||
}
|
||||
@@ -222,15 +228,13 @@ public sealed class WorkspaceRepository : IDisposable
|
||||
/// <param name="tagIds">The tags to assign initially.</param>
|
||||
/// <returns>The created card with tags loaded.</returns>
|
||||
/// <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;
|
||||
using var transaction = _connection.BeginTransaction();
|
||||
long id = ExecuteInsert(transaction,
|
||||
"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));
|
||||
foreach (long tagId in tagIds.Distinct())
|
||||
{
|
||||
foreach (long tagId in tagIds.Distinct()) {
|
||||
ExecuteNonQuery(transaction,
|
||||
"INSERT INTO card_tags (card_id, tag_id) VALUES ($cardId, $tagId);",
|
||||
("$cardId", id), ("$tagId", tagId));
|
||||
@@ -253,15 +257,13 @@ public sealed class WorkspaceRepository : IDisposable
|
||||
/// <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="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)
|
||||
?? throw new InvalidOperationException($"Card {cardId} does not exist.");
|
||||
|
||||
// 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));
|
||||
if (existing.Title == title && existing.Content == content && !tagsChanged)
|
||||
{
|
||||
if (existing.Title == title && existing.Content == content && !tagsChanged) {
|
||||
return existing;
|
||||
}
|
||||
|
||||
@@ -274,8 +276,7 @@ public sealed class WorkspaceRepository : IDisposable
|
||||
|
||||
// Tag assignment is rewritten wholesale; card_tags carries nothing beyond the pair.
|
||||
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,
|
||||
"INSERT INTO card_tags (card_id, tag_id) VALUES ($cardId, $tagId);",
|
||||
("$cardId", cardId), ("$tagId", tagId));
|
||||
@@ -293,8 +294,7 @@ public sealed class WorkspaceRepository : IDisposable
|
||||
/// <param name="cardId">The card to move.</param>
|
||||
/// <param name="targetColumnId">The destination column.</param>
|
||||
/// <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(
|
||||
"UPDATE cards SET column_id = $columnId WHERE id = $id AND column_id <> $columnId;");
|
||||
command.Parameters.AddWithValue("$columnId", targetColumnId);
|
||||
@@ -317,15 +317,13 @@ public sealed class WorkspaceRepository : IDisposable
|
||||
/// Returns all tags ordered by id ascending; unreferenced tags are included.
|
||||
/// </summary>
|
||||
/// <returns>All tags in id order.</returns>
|
||||
public IReadOnlyList<TagModel> GetTags()
|
||||
{
|
||||
public IReadOnlyList<TagModel> GetTags() {
|
||||
using var command = CreateCommand(
|
||||
"SELECT id, name, color, description FROM tags ORDER BY id ASC;");
|
||||
using var reader = command.ExecuteReader();
|
||||
|
||||
var tags = new List<TagModel>();
|
||||
while (reader.Read())
|
||||
{
|
||||
while (reader.Read()) {
|
||||
tags.Add(ReadTag(reader, 0));
|
||||
}
|
||||
return tags;
|
||||
@@ -335,8 +333,7 @@ public sealed class WorkspaceRepository : IDisposable
|
||||
/// Returns every tag together with the number of cards using it, ordered by tag id.
|
||||
/// </summary>
|
||||
/// <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("""
|
||||
SELECT t.id, t.name, t.color, t.description, COUNT(ct.card_id)
|
||||
FROM tags t
|
||||
@@ -347,8 +344,7 @@ public sealed class WorkspaceRepository : IDisposable
|
||||
using var reader = command.ExecuteReader();
|
||||
|
||||
var tags = new List<(TagModel Tag, long UsageCount)>();
|
||||
while (reader.Read())
|
||||
{
|
||||
while (reader.Read()) {
|
||||
tags.Add((ReadTag(reader, 0), reader.GetInt64(4)));
|
||||
}
|
||||
return tags;
|
||||
@@ -362,8 +358,7 @@ public sealed class WorkspaceRepository : IDisposable
|
||||
/// <param name="description">The optional description.</param>
|
||||
/// <returns>The created tag.</returns>
|
||||
/// <exception cref="SqliteException">The name is empty or 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();
|
||||
long id = ExecuteInsert(transaction,
|
||||
"INSERT INTO tags (name, color, description) VALUES ($name, $color, $description);",
|
||||
@@ -383,14 +378,12 @@ public sealed class WorkspaceRepository : IDisposable
|
||||
/// <returns>The updated tag, or the unchanged one for a no-op.</returns>
|
||||
/// <exception cref="InvalidOperationException">The tag does not exist.</exception>
|
||||
/// <exception cref="SqliteException">The new name is empty or 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)
|
||||
?? throw new InvalidOperationException($"Tag {tagId} does not exist.");
|
||||
|
||||
// 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;
|
||||
}
|
||||
|
||||
@@ -421,8 +414,7 @@ public sealed class WorkspaceRepository : IDisposable
|
||||
/// </summary>
|
||||
/// <param name="tagId">The tag id.</param>
|
||||
/// <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(
|
||||
"SELECT id, name, color, description FROM tags WHERE id = $id;");
|
||||
command.Parameters.AddWithValue("$id", tagId);
|
||||
@@ -435,8 +427,7 @@ public sealed class WorkspaceRepository : IDisposable
|
||||
/// </summary>
|
||||
/// <param name="cardId">The card id.</param>
|
||||
/// <returns>The assigned tags in id order.</returns>
|
||||
private IReadOnlyList<TagModel> LoadTags(long cardId)
|
||||
{
|
||||
private IReadOnlyList<TagModel> LoadTags(long cardId) {
|
||||
using var command = CreateCommand("""
|
||||
SELECT t.id, t.name, t.color, t.description
|
||||
FROM tags t
|
||||
@@ -448,8 +439,7 @@ public sealed class WorkspaceRepository : IDisposable
|
||||
using var reader = command.ExecuteReader();
|
||||
|
||||
var tags = new List<TagModel>();
|
||||
while (reader.Read())
|
||||
{
|
||||
while (reader.Read()) {
|
||||
tags.Add(ReadTag(reader, 0));
|
||||
}
|
||||
return tags;
|
||||
@@ -479,8 +469,7 @@ public sealed class WorkspaceRepository : IDisposable
|
||||
/// <param name="sql">The command text.</param>
|
||||
/// <param name="transaction">The transaction to enlist in, when any.</param>
|
||||
/// <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();
|
||||
command.Transaction = transaction;
|
||||
command.CommandText = sql;
|
||||
@@ -493,11 +482,9 @@ public sealed class WorkspaceRepository : IDisposable
|
||||
/// <param name="transaction">The transaction to enlist in.</param>
|
||||
/// <param name="sql">The statement to execute.</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);
|
||||
foreach ((string name, object? value) in parameters)
|
||||
{
|
||||
foreach ((string name, object? value) in parameters) {
|
||||
command.Parameters.AddWithValue(name, value);
|
||||
}
|
||||
command.ExecuteNonQuery();
|
||||
@@ -510,8 +497,7 @@ public sealed class WorkspaceRepository : IDisposable
|
||||
/// <param name="sql">The INSERT statement.</param>
|
||||
/// <param name="parameters">Name/value pairs bound as SQL parameters.</param>
|
||||
/// <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);
|
||||
using SqliteCommand rowId = CreateCommand("SELECT last_insert_rowid();", transaction);
|
||||
return (long)rowId.ExecuteScalar()!;
|
||||
@@ -523,8 +509,7 @@ public sealed class WorkspaceRepository : IDisposable
|
||||
/// <param name="sql">The DELETE statement with an <c>$id</c> parameter.</param>
|
||||
/// <param name="id">The id to delete.</param>
|
||||
/// <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);
|
||||
command.Parameters.AddWithValue("$id", id);
|
||||
return command.ExecuteNonQuery() > 0;
|
||||
|
||||
@@ -7,8 +7,7 @@ namespace YKanBan.Storage.Workspace;
|
||||
/// KEY) so every stored row is valid by construction, and cascading deletes
|
||||
/// are covered by the same DDL.
|
||||
/// </summary>
|
||||
public static class WorkspaceSchema
|
||||
{
|
||||
public static class WorkspaceSchema {
|
||||
/// <summary>
|
||||
/// Newest workspace schema version this build understands.
|
||||
/// </summary>
|
||||
|
||||
@@ -7,8 +7,7 @@ namespace YKanBan.Storage.Workspace;
|
||||
/// any database work happens. Disposing releases the repository and then the
|
||||
/// lock.
|
||||
/// </summary>
|
||||
public sealed class WorkspaceSession : IDisposable
|
||||
{
|
||||
public sealed class WorkspaceSession : IDisposable {
|
||||
private readonly WorkspaceLock _workspaceLock;
|
||||
|
||||
/// <summary>
|
||||
@@ -17,8 +16,7 @@ public sealed class WorkspaceSession : IDisposable
|
||||
/// <param name="folderPath">The canonical workspace folder path.</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>
|
||||
private WorkspaceSession(string folderPath, WorkspaceLock workspaceLock, WorkspaceRepository repository)
|
||||
{
|
||||
private WorkspaceSession(string folderPath, WorkspaceLock workspaceLock, WorkspaceRepository repository) {
|
||||
FolderPath = folderPath;
|
||||
_workspaceLock = workspaceLock;
|
||||
Repository = repository;
|
||||
@@ -40,17 +38,59 @@ public sealed class WorkspaceSession : IDisposable
|
||||
/// <param name="folderPath">The workspace folder to open.</param>
|
||||
/// <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="WorkspaceDatabaseMissingException">.ykanban exists but its database file does not.</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);
|
||||
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);
|
||||
return new WorkspaceSession(folderPath, workspaceLock, repository);
|
||||
}
|
||||
catch
|
||||
{
|
||||
} catch {
|
||||
workspaceLock.Dispose();
|
||||
throw;
|
||||
}
|
||||
@@ -59,8 +99,7 @@ public sealed class WorkspaceSession : IDisposable
|
||||
/// <summary>
|
||||
/// Releases the repository connection, then the exclusive lock.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
public void Dispose() {
|
||||
Repository.Dispose();
|
||||
_workspaceLock.Dispose();
|
||||
}
|
||||
|
||||
+12
-10
@@ -1,31 +1,33 @@
|
||||
using System;
|
||||
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Controls.Templates;
|
||||
|
||||
using YKanBan.ViewModels;
|
||||
|
||||
namespace YKanBan;
|
||||
|
||||
public class ViewLocator : IDataTemplate
|
||||
{
|
||||
public class ViewLocator : IDataTemplate {
|
||||
|
||||
public Control? Build(object? param)
|
||||
{
|
||||
public Control? Build(object? param) {
|
||||
if (param is null)
|
||||
return null;
|
||||
|
||||
|
||||
var name = param.GetType().FullName!.Replace("ViewModel", "View", StringComparison.Ordinal);
|
||||
var type = Type.GetType(name);
|
||||
|
||||
if (type != null)
|
||||
{
|
||||
if (type != null) {
|
||||
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 };
|
||||
}
|
||||
|
||||
public bool Match(object? data)
|
||||
{
|
||||
public bool Match(object? data) {
|
||||
return data is ViewModelBase;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,343 @@
|
||||
using System.Collections.ObjectModel;
|
||||
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using CommunityToolkit.Mvvm.Input;
|
||||
|
||||
using YKanBan.Models;
|
||||
using YKanBan.Search;
|
||||
using YKanBan.Services;
|
||||
using YKanBan.Storage.AppData;
|
||||
using YKanBan.Storage.Workspace;
|
||||
|
||||
namespace YKanBan.ViewModels.Board;
|
||||
|
||||
/// <summary>
|
||||
/// The board tab: a toolbar (search box, add-column and the Display button)
|
||||
/// over horizontally arranged columns of vertically stacked cards. All
|
||||
/// persistence goes through the workspace repository; the board reloads from it
|
||||
/// after each change.
|
||||
/// </summary>
|
||||
public sealed partial class BoardViewModel : ViewModelBase {
|
||||
private readonly AppServices _services;
|
||||
private readonly WorkspaceRepository _repository;
|
||||
|
||||
// The active search result filter, or null when the whole board is shown.
|
||||
private IReadOnlyCollection<long>? _matchedCardIds;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes the board, loading its current content.
|
||||
/// </summary>
|
||||
/// <param name="services">The process composition root (configuration access).</param>
|
||||
/// <param name="session">The open workspace session.</param>
|
||||
public BoardViewModel(AppServices services, WorkspaceSession session) {
|
||||
_services = services;
|
||||
_repository = session.Repository;
|
||||
Display = new DisplaySettingsViewModel(_services.Config, Reload);
|
||||
|
||||
Reload();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the workspace repository used for all board data access.
|
||||
/// </summary>
|
||||
public WorkspaceRepository Repository => _repository;
|
||||
|
||||
/// <summary>
|
||||
/// 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>
|
||||
public ObservableCollection<ColumnViewModel> Columns { get; } = [];
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the search box text. The board does not filter on change;
|
||||
/// the search runs only when the search button is used.
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private string searchText = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the rendered column width in pixels, applied globally.
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private double columnWidth;
|
||||
|
||||
/// <summary>
|
||||
/// Gets a value indicating whether a search filter is currently applied.
|
||||
/// </summary>
|
||||
public bool IsFiltering => _matchedCardIds is not null;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the localized filter status text shown as the status icon tooltip.
|
||||
/// </summary>
|
||||
public string FilterStatusText => IsFiltering ? Resources.Board_FilterActive : Resources.Board_FilterInactive;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the status icon opacity: full while filtering, dimmed otherwise.
|
||||
/// </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>
|
||||
[RelayCommand]
|
||||
private Task AddNewColumnAsync() => AddColumn.Handle(Unit.Value);
|
||||
|
||||
/// <summary>
|
||||
/// 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);
|
||||
if (query is null) {
|
||||
ApplyFilter(null);
|
||||
return;
|
||||
}
|
||||
|
||||
CompiledSearch compiled = SearchSqlCompiler.Compile(query);
|
||||
ApplyFilter(_repository.GetCardIdsMatching(compiled));
|
||||
} catch (SearchSyntaxException exception) {
|
||||
// The error dialog carries the parser's non-localized English detail.
|
||||
await ShowSearchError.Handle(exception.Message);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Clears the search box and restores the unfiltered board.
|
||||
/// </summary>
|
||||
[RelayCommand]
|
||||
private void ClearSearch() {
|
||||
SearchText = string.Empty;
|
||||
ApplyFilter(null);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Applies a new result filter (null clears it) and rebuilds the board when it changed.
|
||||
/// </summary>
|
||||
/// <param name="matchedIds">The new filter, or <see langword="null"/> for no filter.</param>
|
||||
private void ApplyFilter(IReadOnlyCollection<long>? matchedIds) {
|
||||
if (_matchedCardIds is null && matchedIds is null) {
|
||||
return;
|
||||
}
|
||||
|
||||
_matchedCardIds = matchedIds;
|
||||
OnPropertyChanged(nameof(IsFiltering));
|
||||
OnPropertyChanged(nameof(FilterStatusText));
|
||||
OnPropertyChanged(nameof(FilterIconOpacity));
|
||||
Reload();
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Requests from columns and cards
|
||||
|
||||
/// <summary>
|
||||
/// 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>
|
||||
/// <param name="card">The card to delete.</param>
|
||||
/// <returns>A task completing after confirmation.</returns>
|
||||
public Task RequestDeleteCardAsync(CardViewModel card) => DeleteCard.Handle(card);
|
||||
|
||||
/// <summary>
|
||||
/// Requests moving the given card to another column.
|
||||
/// </summary>
|
||||
/// <param name="card">The card to move.</param>
|
||||
/// <returns>A task completing after the move.</returns>
|
||||
public Task RequestMoveCardAsync(CardViewModel card) => MoveCard.Handle(card);
|
||||
|
||||
/// <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))));
|
||||
}
|
||||
|
||||
ApplyColumnWidth();
|
||||
OnPropertyChanged(nameof(HasColumns));
|
||||
OnPropertyChanged(nameof(HasNoColumns));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Recomputes the global column width and pushes it to every column.
|
||||
/// </summary>
|
||||
public void ApplyColumnWidth() {
|
||||
ColumnWidth = ColumnWidthPixels(_services.Config.Display.ColumnWidth);
|
||||
foreach (ColumnViewModel column in Columns) {
|
||||
column.Width = ColumnWidth;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Resolves a column width setting to its pixel value.
|
||||
/// </summary>
|
||||
/// <param name="settings">The configured column width.</param>
|
||||
/// <returns>The width in pixels.</returns>
|
||||
public static double ColumnWidthPixels(ColumnWidthSettings settings) => settings.Preset switch {
|
||||
ColumnWidthPreset.Narrow => 240,
|
||||
ColumnWidthPreset.Wide => 480,
|
||||
ColumnWidthPreset.Custom => settings.CustomPixels,
|
||||
_ => 320,
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Orders cards by the selected option, tie-breaking by id ascending.
|
||||
/// </summary>
|
||||
/// <param name="cards">The cards to order.</param>
|
||||
/// <param name="option">The selected order.</param>
|
||||
/// <returns>The ordered cards.</returns>
|
||||
private static IEnumerable<CardModel> SortCards(IEnumerable<CardModel> cards, SortOption option) => option switch {
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
using CommunityToolkit.Mvvm.Input;
|
||||
|
||||
using YKanBan.Models;
|
||||
|
||||
namespace YKanBan.ViewModels.Board;
|
||||
|
||||
/// <summary>
|
||||
/// One card on the board. Clicking the card body opens the editor; the corner
|
||||
/// menu offers delete and move. The shown text is the "#id title" heading, a
|
||||
/// truncated content preview and the colored tag badges; timestamps are not
|
||||
/// shown on the board.
|
||||
/// </summary>
|
||||
public sealed partial class CardViewModel : ViewModelBase {
|
||||
/// <summary>
|
||||
/// Maximum number of content characters shown in the card preview.
|
||||
/// </summary>
|
||||
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;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes the card view from its model.
|
||||
/// </summary>
|
||||
/// <param name="board">The owning board view model.</param>
|
||||
/// <param name="card">The card model to display.</param>
|
||||
public CardViewModel(BoardViewModel board, CardModel card) {
|
||||
_board = board;
|
||||
Model = card;
|
||||
TagBadges = card.Tags.Select(tag => new TagBadgeViewModel(tag)).ToList();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the underlying card model.
|
||||
/// </summary>
|
||||
public CardModel Model { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the card id.
|
||||
/// </summary>
|
||||
public long Id => Model.Id;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the owning column id.
|
||||
/// </summary>
|
||||
public long ColumnId => Model.ColumnId;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the tag badges shown under the content.
|
||||
/// </summary>
|
||||
public IReadOnlyList<TagBadgeViewModel> TagBadges { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the bold id marker, for example "#61".
|
||||
/// </summary>
|
||||
public string IdText => $"#{Model.Id}";
|
||||
|
||||
/// <summary>
|
||||
/// Gets the card title, empty when the card has no title.
|
||||
/// </summary>
|
||||
public string TitleText => Model.Title;
|
||||
|
||||
/// <summary>
|
||||
/// Gets a value indicating whether the card has a title to show.
|
||||
/// </summary>
|
||||
public bool HasTitle => Model.Title.Length > 0;
|
||||
|
||||
/// <summary>
|
||||
/// Gets a value indicating whether the card has content to preview.
|
||||
/// </summary>
|
||||
public bool HasContent => Model.Content.Length > 0;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the content preview, truncated to at most 200 characters and
|
||||
/// 10 explicit lines, with an ellipsis when anything was cut.
|
||||
/// </summary>
|
||||
// YYC MARK: the preview is truncated here instead of in the view because
|
||||
// both a character cap and an explicit-line cap are needed, and because
|
||||
// Avalonia 11.3.x renders no ellipsis when MaxLines clips wrapped text
|
||||
// (fixed upstream in 12.1.2, PR #22017, never backported). Revisit after
|
||||
// upgrading Avalonia.
|
||||
public string PreviewContent {
|
||||
get {
|
||||
string content = Model.Content;
|
||||
|
||||
// Cut at whichever boundary comes first: 200 characters or the 10th line break.
|
||||
int limit = content.Length;
|
||||
int breaks = 0;
|
||||
for (int i = 0; i < content.Length; i++) {
|
||||
if (i == PreviewLength || (content[i] == '\n' && ++breaks == PreviewMaxLines)) {
|
||||
limit = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
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>
|
||||
/// Opens the card editor.
|
||||
/// </summary>
|
||||
[RelayCommand]
|
||||
private void Edit() => _ = _board.RequestEditCardAsync(this);
|
||||
|
||||
/// <summary>
|
||||
/// Asks the board to delete this card.
|
||||
/// </summary>
|
||||
[RelayCommand]
|
||||
private void Delete() => _ = _board.RequestDeleteCardAsync(this);
|
||||
|
||||
/// <summary>
|
||||
/// Asks the board to move this card to another column.
|
||||
/// </summary>
|
||||
[RelayCommand]
|
||||
private void Move() => _ = _board.RequestMoveCardAsync(this);
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
using System.Collections.ObjectModel;
|
||||
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using CommunityToolkit.Mvvm.Input;
|
||||
|
||||
using YKanBan.Models;
|
||||
|
||||
namespace YKanBan.ViewModels.Board;
|
||||
|
||||
/// <summary>
|
||||
/// One board column: a header with its title, card count and actions, plus the
|
||||
/// vertically stacked cards.
|
||||
/// </summary>
|
||||
public sealed partial class ColumnViewModel : ViewModelBase {
|
||||
private readonly BoardViewModel _board;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes the column view from its model and cards.
|
||||
/// </summary>
|
||||
/// <param name="board">The owning board view model.</param>
|
||||
/// <param name="column">The column model.</param>
|
||||
/// <param name="cards">The already sorted cards belonging to this column.</param>
|
||||
public ColumnViewModel(BoardViewModel board, ColumnModel column, IEnumerable<CardViewModel> cards) {
|
||||
_board = board;
|
||||
Model = column;
|
||||
Cards = new ObservableCollection<CardViewModel>(cards);
|
||||
width = board.ColumnWidth;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the underlying column model.
|
||||
/// </summary>
|
||||
public ColumnModel Model { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the column id.
|
||||
/// </summary>
|
||||
public long Id => Model.Id;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the column title.
|
||||
/// </summary>
|
||||
public string Title => Model.Title;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the column description.
|
||||
/// </summary>
|
||||
public string Description => Model.Description;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the cards in this column, already in display order.
|
||||
/// </summary>
|
||||
public ObservableCollection<CardViewModel> Cards { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the number of cards in this column.
|
||||
/// </summary>
|
||||
public int CardCount => Cards.Count;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the tooltip text: the column description when present, otherwise
|
||||
/// <see langword="null"/> so no tooltip is shown.
|
||||
/// </summary>
|
||||
public string? ToolTipText => Model.Description.Length > 0 ? Model.Description : null;
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the rendered column width in pixels, applied globally.
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private double width;
|
||||
|
||||
/// <summary>
|
||||
/// Opens the editor for a new card in this column.
|
||||
/// </summary>
|
||||
[RelayCommand]
|
||||
private void AddCard() => _ = _board.RequestAddCardAsync(this);
|
||||
|
||||
/// <summary>
|
||||
/// Opens the editor for this column.
|
||||
/// </summary>
|
||||
[RelayCommand]
|
||||
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];
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
using Avalonia.Media;
|
||||
|
||||
using YKanBan.Models;
|
||||
|
||||
namespace YKanBan.ViewModels.Board;
|
||||
|
||||
/// <summary>
|
||||
/// A read-only colored tag badge shown on a card: the tag name over a
|
||||
/// background taken directly from the tag color (user data, never themed) and
|
||||
/// an automatically contrasting text color.
|
||||
/// </summary>
|
||||
public sealed class TagBadgeViewModel {
|
||||
/// <summary>
|
||||
/// Initializes a badge from a tag.
|
||||
/// </summary>
|
||||
/// <param name="tag">The tag to render.</param>
|
||||
public TagBadgeViewModel(TagModel tag) {
|
||||
Tag = tag;
|
||||
Name = tag.Name;
|
||||
Color background = Color.FromRgb(tag.Color.R, tag.Color.G, tag.Color.B);
|
||||
Background = new SolidColorBrush(background);
|
||||
Foreground = new SolidColorBrush(ContrastingTextColor(background));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the underlying tag model.
|
||||
/// </summary>
|
||||
public TagModel Tag { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the tag name.
|
||||
/// </summary>
|
||||
public string Name { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the tooltip text: the tag description when present, otherwise
|
||||
/// <see langword="null"/> so no tooltip is shown.
|
||||
/// </summary>
|
||||
public string? ToolTipText => Tag.Description.Length > 0 ? Tag.Description : null;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the badge background brush.
|
||||
/// </summary>
|
||||
public IBrush Background { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the badge text brush.
|
||||
/// </summary>
|
||||
public IBrush Foreground { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Picks black or white text for readability against the given background.
|
||||
/// </summary>
|
||||
/// <param name="background">The badge background color.</param>
|
||||
/// <returns>The contrasting text color.</returns>
|
||||
private static Color ContrastingTextColor(Color background) {
|
||||
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>
|
||||
/// The about dialog: application name, version, repository link and license.
|
||||
/// </summary>
|
||||
public sealed class AboutDialogViewModel : ViewModelBase
|
||||
{
|
||||
public sealed class AboutDialogViewModel : ViewModelBase {
|
||||
/// <summary>
|
||||
/// Initializes the view model, reading the version from the assembly.
|
||||
/// </summary>
|
||||
public AboutDialogViewModel()
|
||||
{
|
||||
public AboutDialogViewModel() {
|
||||
string version = typeof(AboutDialogViewModel).Assembly.GetName().Version?.ToString(3) ?? "0.0.0";
|
||||
Version = string.Format(
|
||||
Resources.Culture ?? CultureInfo.CurrentCulture, Resources.About_Version, version);
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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; }
|
||||
}
|
||||
@@ -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; }
|
||||
}
|
||||
@@ -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,5 @@
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
|
||||
using YKanBan.Storage.AppData;
|
||||
|
||||
namespace YKanBan.ViewModels.Dialogs;
|
||||
@@ -8,8 +9,7 @@ namespace YKanBan.ViewModels.Dialogs;
|
||||
/// confirmation-dialog toggles. Nothing is applied until the user accepts;
|
||||
/// cancelling or closing the window discards the changes.
|
||||
/// </summary>
|
||||
public sealed partial class SettingsDialogViewModel : ViewModelBase
|
||||
{
|
||||
public sealed partial class SettingsDialogViewModel : ViewModelBase {
|
||||
private readonly AppConfig _config;
|
||||
private readonly string _startupLanguage;
|
||||
|
||||
@@ -18,8 +18,7 @@ public sealed partial class SettingsDialogViewModel : ViewModelBase
|
||||
/// </summary>
|
||||
/// <param name="config">The live application configuration.</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;
|
||||
_startupLanguage = startupLanguage;
|
||||
|
||||
@@ -101,14 +100,11 @@ public sealed partial class SettingsDialogViewModel : ViewModelBase
|
||||
/// <summary>
|
||||
/// Commits the working values into the live configuration.
|
||||
/// </summary>
|
||||
public void Accept()
|
||||
{
|
||||
if (SelectedLanguage is not null)
|
||||
{
|
||||
public void Accept() {
|
||||
if (SelectedLanguage is not null) {
|
||||
_config.Language = (string)SelectedLanguage.Value;
|
||||
}
|
||||
if (SelectedTheme is not null)
|
||||
{
|
||||
if (SelectedTheme is not null) {
|
||||
_config.Theme = (ThemeOption)SelectedTheme.Value;
|
||||
App.ApplyTheme(_config.Theme);
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -4,6 +4,5 @@ namespace YKanBan.ViewModels.ErrorPages;
|
||||
/// The full-window page shown when YKanBan is started without arguments or with
|
||||
/// invalid arguments. It has no operations.
|
||||
/// </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
|
||||
/// instance. It has no operations.
|
||||
/// </summary>
|
||||
public sealed class LockConflictPageViewModel : ViewModelBase
|
||||
{
|
||||
public sealed class LockConflictPageViewModel : ViewModelBase {
|
||||
/// <summary>
|
||||
/// Initializes the page for a locked workspace.
|
||||
/// </summary>
|
||||
/// <param name="folderPath">The locked workspace folder.</param>
|
||||
public LockConflictPageViewModel(string folderPath)
|
||||
{
|
||||
public LockConflictPageViewModel(string folderPath) {
|
||||
FolderPath = folderPath;
|
||||
Message = string.Format(
|
||||
Resources.Culture ?? CultureInfo.CurrentCulture, Resources.Error_LockConflict_Message, folderPath);
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
using System.Globalization;
|
||||
|
||||
using CommunityToolkit.Mvvm.Input;
|
||||
|
||||
namespace YKanBan.ViewModels.ErrorPages;
|
||||
@@ -8,8 +9,7 @@ namespace YKanBan.ViewModels.ErrorPages;
|
||||
/// structure. It is the only error page with an operation: initializing the
|
||||
/// workspace.
|
||||
/// </summary>
|
||||
public sealed partial class NotInitializedPageViewModel : ViewModelBase
|
||||
{
|
||||
public sealed partial class NotInitializedPageViewModel : ViewModelBase {
|
||||
private readonly Interaction<Unit> _initializeWorkspace;
|
||||
|
||||
/// <summary>
|
||||
@@ -17,8 +17,7 @@ public sealed partial class NotInitializedPageViewModel : ViewModelBase
|
||||
/// </summary>
|
||||
/// <param name="folderPath">The uninitialized folder path.</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;
|
||||
_initializeWorkspace = initializeWorkspace;
|
||||
Message = string.Format(
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
using System.Globalization;
|
||||
|
||||
using Microsoft.Data.Sqlite;
|
||||
|
||||
using YKanBan.Storage;
|
||||
|
||||
namespace YKanBan.ViewModels.ErrorPages;
|
||||
|
||||
/// <summary>
|
||||
/// The full-window page shown when a workspace cannot be opened or initialized:
|
||||
/// a schema newer than this build, a missing, unopenable or damaged database, an
|
||||
/// I/O or permission error, or any unrecognized failure. It shows a localized
|
||||
/// message chosen by exception type plus the read-only, copyable English
|
||||
/// exception details, and has no operations.
|
||||
/// </summary>
|
||||
public sealed class OpenFailedPageViewModel : ViewModelBase {
|
||||
/// <summary>
|
||||
/// Initializes the page for a failed open or initialization.
|
||||
/// </summary>
|
||||
/// <param name="folderPath">The workspace folder.</param>
|
||||
/// <param name="exception">The failure.</param>
|
||||
public OpenFailedPageViewModel(string folderPath, Exception exception) {
|
||||
FolderPath = folderPath;
|
||||
Message = BuildMessage(folderPath, exception);
|
||||
|
||||
// Exception texts are English: ours by convention, .NET and SQLite ones by design.
|
||||
Details = exception.ToString();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the workspace folder.
|
||||
/// </summary>
|
||||
public string FolderPath { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the localized explanatory message.
|
||||
/// </summary>
|
||||
public string Message { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the English exception details for diagnosis.
|
||||
/// </summary>
|
||||
public string Details { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Maps the exception type to its localized message; unrecognized types get the generic one.
|
||||
/// </summary>
|
||||
/// <param name="folderPath">The workspace folder.</param>
|
||||
/// <param name="exception">The failure.</param>
|
||||
/// <returns>The localized message.</returns>
|
||||
public static string BuildMessage(string folderPath, Exception exception) {
|
||||
CultureInfo culture = Resources.Culture ?? CultureInfo.CurrentCulture;
|
||||
return exception switch {
|
||||
SchemaVersionException schema => string.Format(
|
||||
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),
|
||||
UnauthorizedAccessException => string.Format(culture, Resources.Error_OpenFailed_AccessDenied, folderPath),
|
||||
IOException => string.Format(culture, Resources.Error_OpenFailed_Io, folderPath),
|
||||
_ => string.Format(culture, Resources.Error_OpenFailed_Generic, folderPath),
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -3,8 +3,7 @@ namespace YKanBan.ViewModels;
|
||||
/// <summary>
|
||||
/// Input placeholder for interactions that carry no meaningful payload.
|
||||
/// </summary>
|
||||
public readonly record struct Unit
|
||||
{
|
||||
public readonly record struct Unit {
|
||||
/// <summary>
|
||||
/// Gets the single unit value.
|
||||
/// </summary>
|
||||
@@ -18,8 +17,7 @@ public readonly record struct Unit
|
||||
/// The view model never holds a reference to a view.
|
||||
/// </summary>
|
||||
/// <typeparam name="TInput">The request payload.</typeparam>
|
||||
public sealed class Interaction<TInput>
|
||||
{
|
||||
public sealed class Interaction<TInput> {
|
||||
private Func<TInput, Task>? _handler;
|
||||
|
||||
/// <summary>
|
||||
@@ -46,8 +44,7 @@ public sealed class Interaction<TInput>
|
||||
/// </summary>
|
||||
/// <typeparam name="TInput">The request payload.</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;
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
using System.Diagnostics;
|
||||
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
|
||||
using YKanBan.Launching;
|
||||
using YKanBan.Services;
|
||||
using YKanBan.Storage;
|
||||
@@ -13,8 +15,7 @@ namespace YKanBan.ViewModels;
|
||||
/// normal workspace view or one of the full-window error pages, and owns the
|
||||
/// interactions that the view fulfils by opening dialogs.
|
||||
/// </summary>
|
||||
public sealed partial class MainWindowViewModel : ViewModelBase
|
||||
{
|
||||
public sealed partial class MainWindowViewModel : ViewModelBase {
|
||||
private readonly AppServices _services;
|
||||
|
||||
/// <summary>
|
||||
@@ -22,8 +23,7 @@ public sealed partial class MainWindowViewModel : ViewModelBase
|
||||
/// </summary>
|
||||
/// <param name="services">The process composition root.</param>
|
||||
/// <param name="arguments">The command-line arguments (excluding the executable).</param>
|
||||
public MainWindowViewModel(AppServices services, IReadOnlyList<string> arguments)
|
||||
{
|
||||
public MainWindowViewModel(AppServices services, IReadOnlyList<string> arguments) {
|
||||
_services = services;
|
||||
ShowSettings = new Interaction<Unit>();
|
||||
ShowAbout = new Interaction<Unit>();
|
||||
@@ -63,31 +63,22 @@ public sealed partial class MainWindowViewModel : ViewModelBase
|
||||
/// Resolves the launch arguments into a content view model.
|
||||
/// </summary>
|
||||
/// <param name="arguments">The command-line arguments.</param>
|
||||
private void Resolve(IReadOnlyList<string> arguments)
|
||||
{
|
||||
if (!LaunchArguments.TryParse(arguments, out string? folderPath))
|
||||
{
|
||||
private void Resolve(IReadOnlyList<string> arguments) {
|
||||
if (!LaunchArguments.TryParse(arguments, out string? folderPath)) {
|
||||
Content = new ArgumentErrorPageViewModel();
|
||||
return;
|
||||
}
|
||||
|
||||
if (!Directory.Exists(folderPath))
|
||||
{
|
||||
Content = new DirectoryMissingPageViewModel(folderPath);
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
try {
|
||||
OpenWorkspace(folderPath);
|
||||
}
|
||||
catch (WorkspaceNotInitializedException)
|
||||
{
|
||||
} catch (WorkspaceNotInitializedException) {
|
||||
Content = new NotInitializedPageViewModel(folderPath, InitializeWorkspace);
|
||||
}
|
||||
catch (WorkspaceLockException)
|
||||
{
|
||||
} catch (WorkspaceLockException) {
|
||||
Content = new LockConflictPageViewModel(folderPath);
|
||||
} catch (Exception exception) {
|
||||
// Newer schema, damaged database, I/O or permission errors, and anything unrecognized.
|
||||
Debug.WriteLine(exception);
|
||||
Content = new OpenFailedPageViewModel(folderPath, exception);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -95,10 +86,22 @@ public sealed partial class MainWindowViewModel : ViewModelBase
|
||||
/// Opens the workspace and switches the content to the normal view.
|
||||
/// </summary>
|
||||
/// <param name="folderPath">The workspace folder to open.</param>
|
||||
private void OpenWorkspace(string folderPath)
|
||||
{
|
||||
WorkspaceSession session = _services.OpenWorkspace(folderPath);
|
||||
Content = new WorkspaceViewModel(session, ShowSettings, ShowAbout);
|
||||
private void OpenWorkspace(string folderPath) => OpenWorkspace(folderPath, _services.OpenWorkspace(folderPath));
|
||||
|
||||
/// <summary>
|
||||
/// 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}";
|
||||
}
|
||||
|
||||
@@ -107,21 +110,14 @@ public sealed partial class MainWindowViewModel : ViewModelBase
|
||||
/// columns and opens the resulting workspace.
|
||||
/// </summary>
|
||||
/// <returns>A completed task once initialization has been attempted.</returns>
|
||||
private Task InitializeCurrentWorkspaceAsync()
|
||||
{
|
||||
if (Content is not NotInitializedPageViewModel page)
|
||||
{
|
||||
private Task InitializeCurrentWorkspaceAsync() {
|
||||
if (Content is not NotInitializedPageViewModel page) {
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
WorkspaceInitializer.Initialize(page.FolderPath);
|
||||
WorkspacePreset.AddPresetColumns(page.FolderPath);
|
||||
OpenWorkspace(page.FolderPath);
|
||||
}
|
||||
catch (Exception exception) when (exception is YKanBanException or IOException or UnauthorizedAccessException)
|
||||
{
|
||||
try {
|
||||
OpenWorkspace(page.FolderPath, _services.InitializeWorkspace(page.FolderPath));
|
||||
} catch (Exception exception) when (exception is YKanBanException or IOException or UnauthorizedAccessException) {
|
||||
// Initialization failed; the page remains so the user can retry.
|
||||
Debug.WriteLine(exception);
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
using System.Collections.ObjectModel;
|
||||
using System.Globalization;
|
||||
|
||||
using CommunityToolkit.Mvvm.Input;
|
||||
|
||||
using YKanBan.Models;
|
||||
using YKanBan.Storage.Workspace;
|
||||
|
||||
namespace YKanBan.ViewModels.Tags;
|
||||
|
||||
/// <summary>
|
||||
/// The tags tab: a manager for the workspace's tags (create, rename, recolor,
|
||||
/// re-describe and delete), showing each tag's color, name, description and
|
||||
/// usage count. Tag changes also refresh the board.
|
||||
/// </summary>
|
||||
public sealed partial class TagsViewModel : ViewModelBase {
|
||||
private readonly WorkspaceRepository _repository;
|
||||
private readonly Action _boardChanged;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes the manager, loading the current tags.
|
||||
/// </summary>
|
||||
/// <param name="repository">The workspace repository.</param>
|
||||
/// <param name="boardChanged">Invoked after a tag change so the board refreshes.</param>
|
||||
public TagsViewModel(WorkspaceRepository repository, Action boardChanged) {
|
||||
_repository = repository;
|
||||
_boardChanged = boardChanged;
|
||||
Reload();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the workspace repository used for tag access.
|
||||
/// </summary>
|
||||
public WorkspaceRepository Repository => _repository;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the tags in id order.
|
||||
/// </summary>
|
||||
public ObservableCollection<TagItemViewModel> Tags { get; } = [];
|
||||
|
||||
/// <summary>
|
||||
/// Gets a value indicating whether the workspace has any tags.
|
||||
/// </summary>
|
||||
public bool HasTags => Tags.Count > 0;
|
||||
|
||||
/// <summary>
|
||||
/// Gets a value indicating whether the workspace has no tags.
|
||||
/// </summary>
|
||||
public bool HasNoTags => Tags.Count == 0;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the localized total number of tags shown next to the add button.
|
||||
/// </summary>
|
||||
public string TagCountText => string.Format(
|
||||
Resources.Culture ?? CultureInfo.CurrentCulture, Resources.Tags_Count, Tags.Count);
|
||||
|
||||
/// <summary>
|
||||
/// 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>
|
||||
[RelayCommand]
|
||||
private Task AddNewTagAsync() => AddTag.Handle(Unit.Value);
|
||||
|
||||
/// <summary>
|
||||
/// Requests the editor for a tag.
|
||||
/// </summary>
|
||||
/// <param name="item">The tag to edit.</param>
|
||||
/// <returns>A task completing after the editor closes.</returns>
|
||||
public Task RequestEditAsync(TagItemViewModel item) => EditTag.Handle(item);
|
||||
|
||||
/// <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>
|
||||
/// Reloads the tags and refreshes the board after a tag change.
|
||||
/// </summary>
|
||||
public void RefreshAfterChange() {
|
||||
Reload();
|
||||
_boardChanged();
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,5 @@
|
||||
|
||||
namespace YKanBan.ViewModels;
|
||||
|
||||
public class ViewModelBase : ObservableObject
|
||||
{
|
||||
public class ViewModelBase : ObservableObject {
|
||||
}
|
||||
@@ -1,34 +1,41 @@
|
||||
using CommunityToolkit.Mvvm.Input;
|
||||
|
||||
using YKanBan.Services;
|
||||
using YKanBan.Storage.Workspace;
|
||||
using YKanBan.ViewModels.Board;
|
||||
using YKanBan.ViewModels.Tags;
|
||||
|
||||
namespace YKanBan.ViewModels;
|
||||
|
||||
/// <summary>
|
||||
/// The normal workspace view: the top display area (name, path and the export,
|
||||
/// settings and about buttons) plus the tags/board tabs. The tab contents are
|
||||
/// filled in by the board and tag features.
|
||||
/// settings and about buttons) plus the board and tags tabs.
|
||||
/// </summary>
|
||||
public sealed partial class WorkspaceViewModel : ViewModelBase
|
||||
{
|
||||
public sealed partial class WorkspaceViewModel : ViewModelBase {
|
||||
private readonly Interaction<Unit> _showSettings;
|
||||
private readonly Interaction<Unit> _showAbout;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes the view for an open workspace.
|
||||
/// </summary>
|
||||
/// <param name="services">The process composition root.</param>
|
||||
/// <param name="session">The open workspace session.</param>
|
||||
/// <param name="showSettings">The interaction that opens the settings dialog.</param>
|
||||
/// <param name="showAbout">The interaction that opens the about dialog.</param>
|
||||
public WorkspaceViewModel(
|
||||
AppServices services,
|
||||
WorkspaceSession session,
|
||||
Interaction<Unit> showSettings,
|
||||
Interaction<Unit> showAbout)
|
||||
{
|
||||
Interaction<Unit> showAbout) {
|
||||
Session = session;
|
||||
WorkspaceName = new DirectoryInfo(session.FolderPath).Name;
|
||||
WorkspacePath = session.FolderPath;
|
||||
_showSettings = showSettings;
|
||||
_showAbout = showAbout;
|
||||
|
||||
// Both tabs share the same repository; tag changes refresh the board.
|
||||
Board = new BoardViewModel(services, session);
|
||||
Tags = new TagsViewModel(session.Repository, Board.Reload);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -46,6 +53,21 @@ public sealed partial class WorkspaceViewModel : ViewModelBase
|
||||
/// </summary>
|
||||
public string WorkspacePath { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the board tab view model.
|
||||
/// </summary>
|
||||
public BoardViewModel Board { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the tags tab view model.
|
||||
/// </summary>
|
||||
public TagsViewModel Tags { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the interaction that runs the export flow.
|
||||
/// </summary>
|
||||
public Interaction<Unit> Export { get; } = new();
|
||||
|
||||
/// <summary>
|
||||
/// Opens the settings dialog through the registered interaction.
|
||||
/// </summary>
|
||||
@@ -59,11 +81,8 @@ public sealed partial class WorkspaceViewModel : ViewModelBase
|
||||
private async Task OpenAboutAsync() => await _showAbout.Handle(Unit.Value);
|
||||
|
||||
/// <summary>
|
||||
/// Raised by the export button; the export flow is wired up with the export
|
||||
/// feature.
|
||||
/// Runs the export flow through the registered interaction.
|
||||
/// </summary>
|
||||
[RelayCommand]
|
||||
private static void Export()
|
||||
{
|
||||
}
|
||||
private async Task RunExportAsync() => await Export.Handle(Unit.Value);
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
<UserControl xmlns="https://github.com/avaloniaui"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:vm="using:YKanBan.ViewModels.Board"
|
||||
xmlns:vmBase="using:YKanBan.ViewModels"
|
||||
xmlns:lang="using:YKanBan"
|
||||
xmlns:icons="using:IconPacks.Avalonia.Lucide"
|
||||
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
|
||||
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
|
||||
mc:Ignorable="d" d:DesignWidth="1000" d:DesignHeight="600"
|
||||
x:Class="YKanBan.Views.Board.BoardView"
|
||||
x:DataType="vm:BoardViewModel">
|
||||
|
||||
<Grid RowDefinitions="Auto,*">
|
||||
|
||||
<!-- Toolbar: search, add column and the combined display options. -->
|
||||
<Grid Grid.Row="0" Margin="8" ColumnDefinitions="Auto,*,Auto,Auto,Auto,Auto">
|
||||
<!-- Wrapped in a transparent-border hit area so the tooltip triggers across the whole 16x16 box. -->
|
||||
<Border Grid.Column="0" Background="Transparent" Padding="2" Margin="0,0,6,0"
|
||||
VerticalAlignment="Center"
|
||||
ToolTip.Tip="{Binding FilterStatusText}">
|
||||
<icons:PackIconLucide Kind="ListFilter" Width="16" Height="16"
|
||||
Opacity="{Binding FilterIconOpacity}"/>
|
||||
</Border>
|
||||
|
||||
<TextBox Grid.Column="1" Text="{Binding SearchText}" VerticalAlignment="Center"
|
||||
Watermark="{x:Static lang:Resources.Board_SearchPlaceholder}">
|
||||
<TextBox.KeyBindings>
|
||||
<KeyBinding Gesture="Enter" Command="{Binding SearchCommand}"/>
|
||||
</TextBox.KeyBindings>
|
||||
</TextBox>
|
||||
|
||||
<Button Grid.Column="2" Margin="4,0,0,0" Command="{Binding ClearSearchCommand}"
|
||||
ToolTip.Tip="{x:Static lang:Resources.Board_ClearSearch}">
|
||||
<icons:PackIconLucide Kind="X" Width="16" Height="16"/>
|
||||
</Button>
|
||||
|
||||
<Button Grid.Column="3" Margin="4,0,0,0" Command="{Binding SearchCommand}"
|
||||
ToolTip.Tip="{x:Static lang:Resources.Board_Search}">
|
||||
<icons:PackIconLucide Kind="Search" Width="16" Height="16"/>
|
||||
</Button>
|
||||
|
||||
<Button Grid.Column="4" Margin="12,0,0,0" Command="{Binding AddNewColumnCommand}">
|
||||
<StackPanel Orientation="Horizontal" Spacing="6">
|
||||
<icons:PackIconLucide Kind="Plus" Width="16" Height="16"/>
|
||||
<TextBlock Text="{x:Static lang:Resources.Board_AddColumn}"/>
|
||||
</StackPanel>
|
||||
</Button>
|
||||
|
||||
<Button Grid.Column="5" Margin="4,0,0,0">
|
||||
<StackPanel Orientation="Horizontal" Spacing="6">
|
||||
<icons:PackIconLucide Kind="SlidersHorizontal" Width="16" Height="16"/>
|
||||
<TextBlock Text="{x:Static lang:Resources.Board_Display}"/>
|
||||
</StackPanel>
|
||||
<Button.Flyout>
|
||||
<Flyout Placement="BottomEdgeAlignedRight">
|
||||
<StackPanel Width="280" Spacing="12" Margin="4">
|
||||
|
||||
<StackPanel Spacing="4">
|
||||
<TextBlock Text="{x:Static lang:Resources.Board_ColumnWidth}"/>
|
||||
<ComboBox ItemsSource="{Binding Display.Presets}"
|
||||
SelectedItem="{Binding Display.SelectedPreset}"
|
||||
HorizontalAlignment="Stretch">
|
||||
<ComboBox.ItemTemplate>
|
||||
<DataTemplate x:DataType="vmBase:OptionItem">
|
||||
<TextBlock Text="{Binding Label}"/>
|
||||
</DataTemplate>
|
||||
</ComboBox.ItemTemplate>
|
||||
</ComboBox>
|
||||
<StackPanel Orientation="Horizontal" Spacing="8"
|
||||
IsVisible="{Binding Display.IsCustom}">
|
||||
<TextBlock Text="{x:Static lang:Resources.WidthDialog_Pixels}"
|
||||
VerticalAlignment="Center"/>
|
||||
<NumericUpDown Value="{Binding Display.CustomPixels}"
|
||||
Minimum="160" Maximum="720" Width="120"/>
|
||||
</StackPanel>
|
||||
</StackPanel>
|
||||
|
||||
<StackPanel Spacing="4">
|
||||
<TextBlock Text="{x:Static lang:Resources.Board_SortCard}"/>
|
||||
<ComboBox ItemsSource="{Binding Display.SortOptions}"
|
||||
SelectedItem="{Binding Display.SelectedCardSort}"
|
||||
HorizontalAlignment="Stretch">
|
||||
<ComboBox.ItemTemplate>
|
||||
<DataTemplate x:DataType="vmBase:OptionItem">
|
||||
<TextBlock Text="{Binding Label}"/>
|
||||
</DataTemplate>
|
||||
</ComboBox.ItemTemplate>
|
||||
</ComboBox>
|
||||
</StackPanel>
|
||||
|
||||
<StackPanel Spacing="4">
|
||||
<TextBlock Text="{x:Static lang:Resources.Board_SortColumn}"/>
|
||||
<ComboBox ItemsSource="{Binding Display.SortOptions}"
|
||||
SelectedItem="{Binding Display.SelectedColumnSort}"
|
||||
HorizontalAlignment="Stretch">
|
||||
<ComboBox.ItemTemplate>
|
||||
<DataTemplate x:DataType="vmBase:OptionItem">
|
||||
<TextBlock Text="{Binding Label}"/>
|
||||
</DataTemplate>
|
||||
</ComboBox.ItemTemplate>
|
||||
</ComboBox>
|
||||
</StackPanel>
|
||||
|
||||
</StackPanel>
|
||||
</Flyout>
|
||||
</Button.Flyout>
|
||||
</Button>
|
||||
</Grid>
|
||||
|
||||
<!-- Board surface: columns horizontally, each scrolling its cards vertically. -->
|
||||
<ScrollViewer Grid.Row="1" HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Disabled">
|
||||
<ItemsControl ItemsSource="{Binding Columns}" Margin="8">
|
||||
<ItemsControl.ItemsPanel>
|
||||
<ItemsPanelTemplate>
|
||||
<StackPanel Orientation="Horizontal" Spacing="12"/>
|
||||
</ItemsPanelTemplate>
|
||||
</ItemsControl.ItemsPanel>
|
||||
</ItemsControl>
|
||||
</ScrollViewer>
|
||||
|
||||
<TextBlock Grid.Row="1" Text="{x:Static lang:Resources.Board_NoColumns}"
|
||||
IsVisible="{Binding HasNoColumns}" Classes="Secondary"
|
||||
HorizontalAlignment="Center" VerticalAlignment="Center"/>
|
||||
|
||||
</Grid>
|
||||
</UserControl>
|
||||
@@ -0,0 +1,147 @@
|
||||
using Avalonia.Controls;
|
||||
|
||||
using YKanBan.ViewModels.Board;
|
||||
using YKanBan.ViewModels.Dialogs;
|
||||
using YKanBan.Views.Dialogs;
|
||||
|
||||
namespace YKanBan.Views.Board;
|
||||
|
||||
public partial class BoardView : UserControl {
|
||||
private bool _registered;
|
||||
|
||||
public BoardView() {
|
||||
InitializeComponent();
|
||||
}
|
||||
|
||||
protected override void OnDataContextChanged(EventArgs e) {
|
||||
base.OnDataContextChanged(e);
|
||||
if (DataContext is BoardViewModel board && !_registered) {
|
||||
_registered = true;
|
||||
board.AddColumn.RegisterHandler(_ => EditColumnAsync(board, null));
|
||||
board.EditColumn.RegisterHandler(column => EditColumnAsync(board, column));
|
||||
board.DeleteColumn.RegisterHandler(column => DeleteColumnAsync(board, column));
|
||||
board.AddCard.RegisterHandler(column => EditCardAsync(board, column, null));
|
||||
board.EditCard.RegisterHandler(card => EditCardAsync(board, null, card));
|
||||
board.DeleteCard.RegisterHandler(card => DeleteCardAsync(board, card));
|
||||
board.MoveCard.RegisterHandler(card => MoveCardAsync(board, card));
|
||||
board.ShowSearchError.RegisterHandler(ShowSearchErrorAsync);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the window that owns this board, used as the dialog owner.
|
||||
/// </summary>
|
||||
private Window? OwningWindow => TopLevel.GetTopLevel(this) as Window;
|
||||
|
||||
/// <summary>
|
||||
/// Shows the add/edit column dialog and reloads on success.
|
||||
/// </summary>
|
||||
private async Task EditColumnAsync(BoardViewModel board, ColumnViewModel? column) {
|
||||
if (OwningWindow is not Window owner) {
|
||||
return;
|
||||
}
|
||||
|
||||
var dialog = new ColumnEditorDialog {
|
||||
DataContext = new ColumnEditorViewModel(board.Repository, column?.Model),
|
||||
};
|
||||
if (await ModalWindow.ShowAsync<bool>(owner, dialog)) {
|
||||
board.Reload();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Confirms and deletes a column, then reloads.
|
||||
/// </summary>
|
||||
private async Task DeleteColumnAsync(BoardViewModel board, ColumnViewModel column) {
|
||||
if (OwningWindow is not Window owner) {
|
||||
return;
|
||||
}
|
||||
|
||||
bool confirmed = true;
|
||||
if (board.Config.Confirmations.DeleteColumn) {
|
||||
var dialog = new DeleteColumnConfirmDialog {
|
||||
DataContext = new DeleteColumnConfirmViewModel(column.Title, column.CardCount),
|
||||
};
|
||||
confirmed = await ModalWindow.ShowAsync<bool>(owner, dialog);
|
||||
}
|
||||
|
||||
if (!confirmed) {
|
||||
return;
|
||||
}
|
||||
|
||||
board.Repository.DeleteColumn(column.Id);
|
||||
board.Reload();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Shows the add/edit card dialog and reloads on success.
|
||||
/// </summary>
|
||||
private async Task EditCardAsync(BoardViewModel board, ColumnViewModel? column, CardViewModel? card) {
|
||||
if (OwningWindow is not Window owner) {
|
||||
return;
|
||||
}
|
||||
|
||||
long columnId = card?.ColumnId ?? column!.Id;
|
||||
var dialog = new CardEditorDialog {
|
||||
DataContext = new CardEditorViewModel(board.Repository, columnId, card?.Model),
|
||||
};
|
||||
if (await ModalWindow.ShowAsync<bool>(owner, dialog)) {
|
||||
board.Reload();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Confirms and deletes a card, then reloads.
|
||||
/// </summary>
|
||||
private async Task DeleteCardAsync(BoardViewModel board, CardViewModel card) {
|
||||
if (OwningWindow is not Window owner) {
|
||||
return;
|
||||
}
|
||||
|
||||
bool confirmed = true;
|
||||
if (board.Config.Confirmations.DeleteCard) {
|
||||
var dialog = new DeleteCardConfirmDialog {
|
||||
DataContext = new DeleteCardConfirmViewModel(card.Id),
|
||||
};
|
||||
confirmed = await ModalWindow.ShowAsync<bool>(owner, dialog);
|
||||
}
|
||||
|
||||
if (!confirmed) {
|
||||
return;
|
||||
}
|
||||
|
||||
board.Repository.DeleteCard(card.Id);
|
||||
board.Reload();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Shows the move-card dialog and reloads when a destination is chosen.
|
||||
/// </summary>
|
||||
private async Task MoveCardAsync(BoardViewModel board, CardViewModel card) {
|
||||
if (OwningWindow is not Window owner) {
|
||||
return;
|
||||
}
|
||||
|
||||
var dialog = new MoveCardDialog {
|
||||
DataContext = new MoveCardViewModel(board.Repository.GetColumns(), card.ColumnId),
|
||||
};
|
||||
if (await ModalWindow.ShowAsync<long?>(owner, dialog) is long targetColumnId) {
|
||||
board.Repository.MoveCard(card.Id, targetColumnId);
|
||||
board.Reload();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Shows the search syntax error dialog.
|
||||
/// </summary>
|
||||
private async Task ShowSearchErrorAsync(string detail) {
|
||||
if (OwningWindow is not Window owner) {
|
||||
return;
|
||||
}
|
||||
|
||||
var dialog = new SearchErrorDialog {
|
||||
DataContext = new SearchErrorViewModel(detail),
|
||||
};
|
||||
await ModalWindow.ShowAsync(owner, dialog);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
<UserControl xmlns="https://github.com/avaloniaui"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:vm="using:YKanBan.ViewModels.Board"
|
||||
xmlns:lang="using:YKanBan"
|
||||
xmlns:icons="using:IconPacks.Avalonia.Lucide"
|
||||
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
|
||||
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
|
||||
mc:Ignorable="d" d:DesignWidth="320" d:DesignHeight="120"
|
||||
x:Class="YKanBan.Views.Board.CardView"
|
||||
x:DataType="vm:CardViewModel">
|
||||
|
||||
<Border Background="{DynamicResource CardBackgroundBrush}"
|
||||
BorderBrush="{DynamicResource CardBorderBrush}"
|
||||
BorderThickness="1" CornerRadius="6" Padding="8"
|
||||
Cursor="Hand" Tapped="OnCardTapped">
|
||||
|
||||
<Grid RowDefinitions="Auto,Auto,Auto">
|
||||
|
||||
<!-- Row 1: id, title and the corner menu. -->
|
||||
<Grid Grid.Row="0" ColumnDefinitions="Auto,*,Auto">
|
||||
<TextBlock Grid.Column="0" Text="{Binding IdText}" FontWeight="Bold" VerticalAlignment="Center"/>
|
||||
<TextBlock Grid.Column="1" Text="{Binding TitleText}" IsVisible="{Binding HasTitle}"
|
||||
VerticalAlignment="Center" Margin="4,0"
|
||||
TextWrapping="NoWrap" TextTrimming="CharacterEllipsis"
|
||||
ToolTip.Tip="{Binding TitleText}"/>
|
||||
<Button Grid.Column="2" Padding="4,2" VerticalAlignment="Center"
|
||||
Tapped="OnMenuButtonTapped">
|
||||
<icons:PackIconLucide Kind="EllipsisVertical" Width="16" Height="16"/>
|
||||
<Button.Flyout>
|
||||
<MenuFlyout>
|
||||
<MenuItem Header="{x:Static lang:Resources.Card_Move}" Command="{Binding MoveCommand}"/>
|
||||
<MenuItem Header="{x:Static lang:Resources.Card_Delete}" Command="{Binding DeleteCommand}"/>
|
||||
</MenuFlyout>
|
||||
</Button.Flyout>
|
||||
</Button>
|
||||
</Grid>
|
||||
|
||||
<!-- Row 2: content preview. -->
|
||||
<TextBlock Grid.Row="1" Text="{Binding PreviewContent}" IsVisible="{Binding HasContent}"
|
||||
TextWrapping="Wrap" FontSize="12" Margin="0,4,0,0"/>
|
||||
|
||||
<!-- Row 3: tag badges. -->
|
||||
<ItemsControl Grid.Row="2" ItemsSource="{Binding TagBadges}" IsVisible="{Binding HasTags}"
|
||||
Margin="0,4,0,0">
|
||||
<ItemsControl.ItemsPanel>
|
||||
<ItemsPanelTemplate>
|
||||
<WrapPanel/>
|
||||
</ItemsPanelTemplate>
|
||||
</ItemsControl.ItemsPanel>
|
||||
<ItemsControl.ItemTemplate>
|
||||
<DataTemplate x:DataType="vm:TagBadgeViewModel">
|
||||
<Border Background="{Binding Background}" CornerRadius="8"
|
||||
Padding="6,2" Margin="0,0,4,4"
|
||||
ToolTip.Tip="{Binding ToolTipText}">
|
||||
<TextBlock Text="{Binding Name}" Foreground="{Binding Foreground}" FontSize="11"/>
|
||||
</Border>
|
||||
</DataTemplate>
|
||||
</ItemsControl.ItemTemplate>
|
||||
</ItemsControl>
|
||||
|
||||
</Grid>
|
||||
</Border>
|
||||
</UserControl>
|
||||
@@ -0,0 +1,26 @@
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Input;
|
||||
|
||||
using YKanBan.ViewModels.Board;
|
||||
|
||||
namespace YKanBan.Views.Board;
|
||||
|
||||
public partial class CardView : UserControl {
|
||||
public CardView() {
|
||||
InitializeComponent();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Clicking the card body opens the card editor.
|
||||
/// </summary>
|
||||
private void OnCardTapped(object? sender, TappedEventArgs e) {
|
||||
if (DataContext is CardViewModel card) {
|
||||
card.EditCommand.Execute(null);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Stops the corner menu button's tap from bubbling to the card body.
|
||||
/// </summary>
|
||||
private void OnMenuButtonTapped(object? sender, TappedEventArgs e) => e.Handled = true;
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
<UserControl xmlns="https://github.com/avaloniaui"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:vm="using:YKanBan.ViewModels.Board"
|
||||
xmlns:lang="using:YKanBan"
|
||||
xmlns:icons="using:IconPacks.Avalonia.Lucide"
|
||||
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
|
||||
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
|
||||
mc:Ignorable="d" d:DesignWidth="320" d:DesignHeight="600"
|
||||
x:Class="YKanBan.Views.Board.ColumnView"
|
||||
x:DataType="vm:ColumnViewModel">
|
||||
|
||||
<Border Width="{Binding Width}" MinWidth="160" MaxWidth="720"
|
||||
Background="{DynamicResource BoardColumnBackgroundBrush}"
|
||||
BorderBrush="{DynamicResource BoardColumnBorderBrush}"
|
||||
BorderThickness="1" CornerRadius="8" VerticalAlignment="Stretch">
|
||||
|
||||
<Grid RowDefinitions="Auto,*" Margin="10">
|
||||
|
||||
<Grid Grid.Row="0" ColumnDefinitions="*,Auto,Auto">
|
||||
<StackPanel Grid.Column="0" Orientation="Horizontal" Spacing="6" VerticalAlignment="Center">
|
||||
<TextBlock Text="{Binding Title}" FontWeight="SemiBold"
|
||||
TextTrimming="CharacterEllipsis" ToolTip.Tip="{Binding ToolTipText}"/>
|
||||
<TextBlock Text="{Binding CardCount}" Classes="Secondary" VerticalAlignment="Center"/>
|
||||
</StackPanel>
|
||||
|
||||
<Button Grid.Column="1" Margin="4,0,0,0" Padding="4,2"
|
||||
Command="{Binding AddCardCommand}"
|
||||
ToolTip.Tip="{x:Static lang:Resources.Column_AddCard}">
|
||||
<icons:PackIconLucide Kind="Plus" Width="16" Height="16"/>
|
||||
</Button>
|
||||
|
||||
<Button Grid.Column="2" Margin="2,0,0,0" Padding="4,2">
|
||||
<icons:PackIconLucide Kind="EllipsisVertical" Width="16" Height="16"/>
|
||||
<Button.Flyout>
|
||||
<MenuFlyout>
|
||||
<MenuItem Header="{x:Static lang:Resources.Column_Edit}" Command="{Binding EditCommand}"/>
|
||||
<MenuItem Header="{x:Static lang:Resources.Column_Delete}" Command="{Binding DeleteCommand}"/>
|
||||
</MenuFlyout>
|
||||
</Button.Flyout>
|
||||
</Button>
|
||||
</Grid>
|
||||
|
||||
<ScrollViewer Grid.Row="1" VerticalScrollBarVisibility="Auto" Margin="0,8,0,0">
|
||||
<ItemsControl ItemsSource="{Binding Cards}">
|
||||
<ItemsControl.ItemsPanel>
|
||||
<ItemsPanelTemplate>
|
||||
<StackPanel Spacing="8"/>
|
||||
</ItemsPanelTemplate>
|
||||
</ItemsControl.ItemsPanel>
|
||||
</ItemsControl>
|
||||
</ScrollViewer>
|
||||
|
||||
</Grid>
|
||||
</Border>
|
||||
</UserControl>
|
||||
@@ -0,0 +1,9 @@
|
||||
using Avalonia.Controls;
|
||||
|
||||
namespace YKanBan.Views.Board;
|
||||
|
||||
public partial class ColumnView : UserControl {
|
||||
public ColumnView() {
|
||||
InitializeComponent();
|
||||
}
|
||||
}
|
||||
@@ -31,7 +31,8 @@
|
||||
|
||||
<Button Grid.Row="1" Content="{x:Static lang:Resources.Common_Ok}"
|
||||
Click="OnCloseClick" HorizontalAlignment="Right" MinWidth="90"
|
||||
IsDefault="True" IsCancel="True"/>
|
||||
IsDefault="True" IsCancel="True"
|
||||
Theme="{DynamicResource SolidButton}" Classes="Primary"/>
|
||||
|
||||
</Grid>
|
||||
</Window>
|
||||
@@ -3,13 +3,13 @@ using Avalonia.Interactivity;
|
||||
|
||||
namespace YKanBan.Views.Dialogs;
|
||||
|
||||
public partial class AboutDialog : Window
|
||||
{
|
||||
public AboutDialog()
|
||||
{
|
||||
public partial class AboutDialog : Window {
|
||||
public AboutDialog() {
|
||||
InitializeComponent();
|
||||
}
|
||||
|
||||
/// <summary>Closes the dialog.</summary>
|
||||
/// <summary>
|
||||
/// Closes the dialog.
|
||||
/// </summary>
|
||||
private void OnCloseClick(object? sender, RoutedEventArgs e) => Close();
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
<Window xmlns="https://github.com/avaloniaui"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:vm="using:YKanBan.ViewModels.Dialogs"
|
||||
xmlns:lang="using:YKanBan"
|
||||
xmlns:icons="using:IconPacks.Avalonia.Lucide"
|
||||
xmlns:conv="using:Avalonia.Data.Converters"
|
||||
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
|
||||
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
|
||||
mc:Ignorable="d" d:DesignWidth="520" d:DesignHeight="560"
|
||||
x:Class="YKanBan.Views.Dialogs.CardEditorDialog"
|
||||
x:DataType="vm:CardEditorViewModel"
|
||||
Title="{Binding WindowTitle}"
|
||||
Width="520" Height="560" MinWidth="520" MinHeight="560" CanResize="True"
|
||||
WindowStartupLocation="CenterOwner"
|
||||
ShowInTaskbar="False">
|
||||
|
||||
<Grid RowDefinitions="*,Auto" Margin="20">
|
||||
<ScrollViewer Grid.Row="0" VerticalScrollBarVisibility="Auto">
|
||||
<StackPanel Spacing="6">
|
||||
|
||||
<TextBlock Text="{x:Static lang:Resources.CardDialog_Title}"/>
|
||||
<TextBox Text="{Binding Title}"/>
|
||||
|
||||
<TextBlock Text="{x:Static lang:Resources.CardDialog_Content}" Margin="0,6,0,0"/>
|
||||
<TextBox Text="{Binding Content}" AcceptsReturn="True" TextWrapping="Wrap"
|
||||
VerticalContentAlignment="Top" Height="160"/>
|
||||
|
||||
<TextBlock Text="{x:Static lang:Resources.CardDialog_Tags}" Margin="0,6,0,0"/>
|
||||
<ItemsControl ItemsSource="{Binding AssignedTags}">
|
||||
<ItemsControl.ItemsPanel>
|
||||
<ItemsPanelTemplate>
|
||||
<WrapPanel/>
|
||||
</ItemsPanelTemplate>
|
||||
</ItemsControl.ItemsPanel>
|
||||
<ItemsControl.ItemTemplate>
|
||||
<DataTemplate x:DataType="vm:AssignedTagViewModel">
|
||||
<Border Background="{Binding Background}" CornerRadius="8"
|
||||
Padding="6,2" Margin="0,0,4,4">
|
||||
<StackPanel Orientation="Horizontal" Spacing="4">
|
||||
<TextBlock Text="{Binding Name}" Foreground="{Binding Foreground}"
|
||||
FontSize="11" VerticalAlignment="Center"/>
|
||||
<Button Command="{Binding RemoveCommand}" Padding="0"
|
||||
Background="Transparent" BorderThickness="0">
|
||||
<icons:PackIconLucide Kind="X" Width="10" Height="10"
|
||||
Foreground="{Binding Foreground}"/>
|
||||
</Button>
|
||||
</StackPanel>
|
||||
</Border>
|
||||
</DataTemplate>
|
||||
</ItemsControl.ItemTemplate>
|
||||
</ItemsControl>
|
||||
<Button Content="{x:Static lang:Resources.CardDialog_AddTag}"
|
||||
Command="{Binding AddTagCommand}" HorizontalAlignment="Left"/>
|
||||
|
||||
<StackPanel Spacing="2" IsVisible="{Binding !IsNew}" Margin="0,8,0,0">
|
||||
<TextBlock Text="{Binding IdLine}" Classes="Secondary"/>
|
||||
<TextBlock Text="{Binding CreatedLine}" Classes="Secondary"/>
|
||||
<TextBlock Text="{Binding ModifiedLine}" Classes="Secondary"/>
|
||||
</StackPanel>
|
||||
|
||||
<TextBlock Text="{Binding ErrorMessage}"
|
||||
IsVisible="{Binding ErrorMessage, Converter={x:Static conv:ObjectConverters.IsNotNull}}"
|
||||
Foreground="{DynamicResource ErrorTextBrush}" TextWrapping="Wrap" Margin="0,4,0,0"/>
|
||||
</StackPanel>
|
||||
</ScrollViewer>
|
||||
|
||||
<StackPanel Grid.Row="1" Orientation="Horizontal" HorizontalAlignment="Right"
|
||||
Spacing="8" Margin="0,16,0,0">
|
||||
<Button Content="{x:Static lang:Resources.Common_Ok}" Click="OnOkClick" MinWidth="90" IsDefault="True"
|
||||
Theme="{DynamicResource SolidButton}" Classes="Primary"/>
|
||||
<Button Content="{x:Static lang:Resources.Common_Cancel}" Click="OnCancelClick" MinWidth="90"
|
||||
IsCancel="True"/>
|
||||
</StackPanel>
|
||||
</Grid>
|
||||
</Window>
|
||||
@@ -0,0 +1,97 @@
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Interactivity;
|
||||
using Avalonia.Threading;
|
||||
|
||||
using YKanBan.Models;
|
||||
using YKanBan.ViewModels;
|
||||
using YKanBan.ViewModels.Dialogs;
|
||||
|
||||
namespace YKanBan.Views.Dialogs;
|
||||
|
||||
public partial class CardEditorDialog : Window {
|
||||
private bool _allowClose;
|
||||
|
||||
public CardEditorDialog() {
|
||||
InitializeComponent();
|
||||
}
|
||||
|
||||
protected override void OnDataContextChanged(EventArgs e) {
|
||||
base.OnDataContextChanged(e);
|
||||
if (DataContext is CardEditorViewModel viewModel) {
|
||||
viewModel.ShowTagPicker.RegisterHandler(ShowTagPickerAsync);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Shows the nested tag picker, owned by this dialog.
|
||||
/// </summary>
|
||||
private async Task<TagModel?> ShowTagPickerAsync(Unit input) {
|
||||
if (DataContext is not CardEditorViewModel viewModel) {
|
||||
return null;
|
||||
}
|
||||
|
||||
var dialog = new TagPickerDialog {
|
||||
DataContext = new TagPickerViewModel(
|
||||
viewModel.Repository,
|
||||
viewModel.AssignedTags.Select(row => row.Tag.Id).ToList()),
|
||||
};
|
||||
return await ModalWindow.ShowAsync<TagModel?>(this, dialog);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writes the card and closes when accepted.
|
||||
/// </summary>
|
||||
private void OnOkClick(object? sender, RoutedEventArgs e) {
|
||||
if (DataContext is CardEditorViewModel viewModel && viewModel.TryAccept()) {
|
||||
_allowClose = true;
|
||||
Close(true);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Requests a close, confirming the discard first when needed.
|
||||
/// </summary>
|
||||
private void OnCancelClick(object? sender, RoutedEventArgs e) => _ = RequestCloseAsync();
|
||||
|
||||
/// <summary>
|
||||
/// Intercepts the window close button to run the discard confirmation.
|
||||
/// </summary>
|
||||
protected override void OnClosing(WindowClosingEventArgs e) {
|
||||
base.OnClosing(e);
|
||||
if (_allowClose) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (HasUnsavedChanges && DiscardConfirmEnabled) {
|
||||
e.Cancel = true;
|
||||
Dispatcher.UIThread.Post(() => _ = RequestCloseAsync());
|
||||
} else {
|
||||
_allowClose = true;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Confirms the discard and closes, or stays open when declined.
|
||||
/// </summary>
|
||||
private async Task RequestCloseAsync() {
|
||||
if (HasUnsavedChanges && DiscardConfirmEnabled) {
|
||||
var dialog = new DiscardEditConfirmDialog { DataContext = new DiscardEditConfirmViewModel() };
|
||||
if (!await ModalWindow.ShowAsync<bool>(this, dialog)) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
_allowClose = true;
|
||||
Close(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets whether the editor has unsaved changes.
|
||||
/// </summary>
|
||||
private bool HasUnsavedChanges => DataContext is CardEditorViewModel viewModel && viewModel.HasChanges;
|
||||
|
||||
/// <summary>
|
||||
/// Gets whether the discard confirmation setting is enabled.
|
||||
/// </summary>
|
||||
private static bool DiscardConfirmEnabled => App.Services?.Config.Confirmations.DiscardEdit == true;
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
<Window xmlns="https://github.com/avaloniaui"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:vm="using:YKanBan.ViewModels.Dialogs"
|
||||
xmlns:lang="using:YKanBan"
|
||||
xmlns:conv="using:Avalonia.Data.Converters"
|
||||
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
|
||||
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
|
||||
mc:Ignorable="d" d:DesignWidth="420" d:DesignHeight="300"
|
||||
x:Class="YKanBan.Views.Dialogs.ColumnEditorDialog"
|
||||
x:DataType="vm:ColumnEditorViewModel"
|
||||
Title="{Binding WindowTitle}"
|
||||
Width="420" Height="300" MinWidth="420" MinHeight="300" CanResize="True"
|
||||
WindowStartupLocation="CenterOwner"
|
||||
ShowInTaskbar="False">
|
||||
|
||||
<Grid RowDefinitions="*,Auto" Margin="20">
|
||||
<StackPanel Grid.Row="0" Spacing="6">
|
||||
<TextBlock Text="{x:Static lang:Resources.ColumnDialog_Title}"/>
|
||||
<TextBox Text="{Binding Title}"/>
|
||||
|
||||
<TextBlock Text="{x:Static lang:Resources.ColumnDialog_Description}" Margin="0,6,0,0"/>
|
||||
<TextBox Text="{Binding Description}" AcceptsReturn="True" TextWrapping="Wrap"
|
||||
VerticalContentAlignment="Top" Height="80"/>
|
||||
|
||||
<TextBlock Text="{Binding ErrorMessage}"
|
||||
IsVisible="{Binding ErrorMessage, Converter={x:Static conv:ObjectConverters.IsNotNull}}"
|
||||
Foreground="{DynamicResource ErrorTextBrush}" TextWrapping="Wrap" Margin="0,4,0,0"/>
|
||||
</StackPanel>
|
||||
|
||||
<StackPanel Grid.Row="1" Orientation="Horizontal" HorizontalAlignment="Right"
|
||||
Spacing="8" Margin="0,16,0,0">
|
||||
<Button Content="{x:Static lang:Resources.Common_Ok}" Click="OnOkClick" MinWidth="90" IsDefault="True"
|
||||
Theme="{DynamicResource SolidButton}" Classes="Primary"/>
|
||||
<Button Content="{x:Static lang:Resources.Common_Cancel}" Click="OnCancelClick" MinWidth="90" IsCancel="True"/>
|
||||
</StackPanel>
|
||||
</Grid>
|
||||
</Window>
|
||||
@@ -0,0 +1,26 @@
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Interactivity;
|
||||
|
||||
using YKanBan.ViewModels.Dialogs;
|
||||
|
||||
namespace YKanBan.Views.Dialogs;
|
||||
|
||||
public partial class ColumnEditorDialog : Window {
|
||||
public ColumnEditorDialog() {
|
||||
InitializeComponent();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writes the column and closes when accepted.
|
||||
/// </summary>
|
||||
private void OnOkClick(object? sender, RoutedEventArgs e) {
|
||||
if (DataContext is ColumnEditorViewModel viewModel && viewModel.TryAccept()) {
|
||||
Close(true);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Closes without writing.
|
||||
/// </summary>
|
||||
private void OnCancelClick(object? sender, RoutedEventArgs e) => Close(false);
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
<Window xmlns="https://github.com/avaloniaui"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:vm="using:YKanBan.ViewModels.Dialogs"
|
||||
xmlns:lang="using:YKanBan"
|
||||
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
|
||||
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
|
||||
mc:Ignorable="d" d:DesignWidth="420" d:DesignHeight="200"
|
||||
x:Class="YKanBan.Views.Dialogs.DeleteCardConfirmDialog"
|
||||
x:DataType="vm:DeleteCardConfirmViewModel"
|
||||
Title="{x:Static lang:Resources.Confirm_DeleteCard_Title}"
|
||||
Width="420" Height="200" MinWidth="420" MinHeight="200" CanResize="True"
|
||||
WindowStartupLocation="CenterOwner"
|
||||
ShowInTaskbar="False">
|
||||
|
||||
<Grid RowDefinitions="*,Auto" Margin="20">
|
||||
<TextBlock Grid.Row="0" Text="{Binding Message}" TextWrapping="Wrap" VerticalAlignment="Top"/>
|
||||
<StackPanel Grid.Row="1" Orientation="Horizontal" HorizontalAlignment="Right" Spacing="8">
|
||||
<Button Content="{x:Static lang:Resources.Common_Delete}" Click="OnConfirmClick"
|
||||
MinWidth="90" Classes="Danger"/>
|
||||
<Button Content="{x:Static lang:Resources.Common_Cancel}" Click="OnCancelClick"
|
||||
MinWidth="90" IsDefault="True" IsCancel="True"/>
|
||||
</StackPanel>
|
||||
</Grid>
|
||||
</Window>
|
||||
@@ -0,0 +1,20 @@
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Interactivity;
|
||||
|
||||
namespace YKanBan.Views.Dialogs;
|
||||
|
||||
public partial class DeleteCardConfirmDialog : Window {
|
||||
public DeleteCardConfirmDialog() {
|
||||
InitializeComponent();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Confirms the deletion.
|
||||
/// </summary>
|
||||
private void OnConfirmClick(object? sender, RoutedEventArgs e) => Close(true);
|
||||
|
||||
/// <summary>
|
||||
/// Cancels the deletion.
|
||||
/// </summary>
|
||||
private void OnCancelClick(object? sender, RoutedEventArgs e) => Close(false);
|
||||
}
|
||||
Loaded 100 of 136 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user