Compare commits
14
Commits
v0.2.0
...
8347445f51
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8347445f51 | ||
|
|
bd8472f232 | ||
|
|
6ea0df43e3 | ||
|
|
e3f58ce150 | ||
|
|
84d08c6768 | ||
|
|
433f204c81 | ||
|
|
6743e1572e | ||
|
|
cde9e8e20c | ||
|
|
4b56297135 | ||
|
|
bb4f96a9c5 | ||
|
|
27b507e439 | ||
|
|
632339ea42 | ||
|
|
33757f6cbc | ||
|
|
4230bd02d2 |
No files matched your search
@@ -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,69 @@
|
||||
# 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-x64
|
||||
os: macos-15-intel
|
||||
- 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
|
||||
@@ -2,4 +2,30 @@
|
||||
|
||||
My personal used local/offline kanban.
|
||||
|
||||
WIP.
|
||||
- Cross-platform desktop app (Windows / Linux / macOS) built with Avalonia.
|
||||
- Git-like storage: the board lives in a `.ykanban` folder inside the project
|
||||
folder it manages; start it with `ykanban <path>`.
|
||||
- One board per workspace with columns, cards and colored tags; strict search
|
||||
expressions (`tag:bug OR title:login`); Markdown export.
|
||||
- English and Simplified Chinese interface; light, dark or system theme.
|
||||
|
||||
See **[USAGE.md](USAGE.md)** for installing, starting YKanBan, backups and
|
||||
Git, and the full search syntax.
|
||||
|
||||
## Building
|
||||
|
||||
Requires the .NET 10 SDK.
|
||||
|
||||
```sh
|
||||
dotnet build
|
||||
dotnet test
|
||||
dotnet run --project YKanBan -- <path>
|
||||
```
|
||||
|
||||
Release archives for win-x64, linux-x64, osx-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
|
||||
@@ -0,0 +1,246 @@
|
||||
# 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](#installing)
|
||||
- [Starting YKanBan](#starting-ykanban)
|
||||
- [macOS](#macos)
|
||||
- [Workspaces, Git and backups](#workspaces-git-and-backups)
|
||||
- [Search syntax](#search-syntax)
|
||||
- [Settings file](#settings-file)
|
||||
|
||||
## 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 Intel | `YKanBan-<version>-osx-x64.tar.gz` | `YKanBan.app` (see [macOS](#macos)) |
|
||||
| macOS Apple silicon | `YKanBan-<version>-osx-arm64.tar.gz` | `YKanBan.app` (see [macOS](#macos)) |
|
||||
|
||||
Extract the archive anywhere. To type `ykanban <path>` as shown below, put the
|
||||
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.
|
||||
- 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`.
|
||||
|
||||
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 argument, or an argument starting with `-` (including `--help`). Shows the usage line. |
|
||||
| Folder not found | `<path>` does not exist or is not a folder. |
|
||||
| No workspace here | `<path>` exists but has no `.ykanban`. The **Initialize workspace** button creates one, with the columns To Do / In Progress / Done (named in the current interface language). |
|
||||
| Workspace locked | Another YKanBan window already has this workspace open. Close that window first. |
|
||||
| Cannot open workspace | The database was created by a newer YKanBan, is damaged or cannot be opened, or a file-system or permission error occurred (also when initializing fails). The English error details can be selected and copied. |
|
||||
|
||||
The window title is `<workspace name> - YKanBan` while a workspace is open and
|
||||
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 -a YKanBan --args /path/to/project
|
||||
/Applications/YKanBan.app/Contents/MacOS/YKanBan /path/to/project
|
||||
```
|
||||
|
||||
`open -a YKanBan` finds the app once it is in `/Applications` (or another
|
||||
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.
|
||||
|
||||
## 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.
|
||||
- After any change (adding, editing, moving or deleting cards, columns or
|
||||
tags), the board re-runs the **last expression that searched successfully**,
|
||||
not whatever is in the box at that moment. Cards that stop matching
|
||||
disappear; new cards that do not match are not shown.
|
||||
|
||||
### Examples
|
||||
|
||||
| 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 := '"' any text '"' -- 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"`.
|
||||
|
||||
### 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 be unique ignoring case for the letters A–Z
|
||||
only. Two tags such as `Ä` and `ä` can therefore both exist, and `tag:ä`
|
||||
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 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, and only if a setting was changed in
|
||||
that session. With several windows open, the last one closed after changing
|
||||
a setting wins.
|
||||
- A language change takes effect after restarting YKanBan; a theme change
|
||||
applies immediately.
|
||||
- If the file cannot be parsed, it is saved as `app.json.bak` and the defaults
|
||||
are used. A single invalid value falls back to its default; the other
|
||||
values are kept.
|
||||
@@ -0,0 +1,60 @@
|
||||
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));
|
||||
}
|
||||
}
|
||||
@@ -84,8 +84,8 @@ public class MarkdownExporterTests
|
||||
/// <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);
|
||||
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();
|
||||
|
||||
@@ -196,7 +196,117 @@ 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;
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[DataRow("plain", "`plain`")]
|
||||
[DataRow("a`b", "``a`b``")]
|
||||
[DataRow("a``b`c", "```a``b`c```")]
|
||||
[DataRow("`x", "`` `x ``")]
|
||||
[DataRow("x`", "`` x` ``")]
|
||||
[DataRow("`", "`` ` ``")]
|
||||
public void TagNamesUseLongEnoughBacktickFence(string name, string expected)
|
||||
{
|
||||
CultureInfo? original = Resources.Culture;
|
||||
try
|
||||
{
|
||||
Resources.Culture = new CultureInfo("en");
|
||||
var tag = new TagModel(1, name, 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, string.Format(Resources.Culture, Resources.Export_TagsLine, expected) + Environment.NewLine);
|
||||
}
|
||||
finally
|
||||
{
|
||||
Resources.Culture = original;
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CardBodyAndColumnDescriptionAreVerbatim()
|
||||
{
|
||||
CultureInfo? original = Resources.Culture;
|
||||
try
|
||||
{
|
||||
Resources.Culture = new CultureInfo("en");
|
||||
string markdown = Normalize(MarkdownExporter.Export(
|
||||
"W",
|
||||
[new ColumnModel(1, "C", "line one\n# not a heading | pipe", 1, 1)],
|
||||
[new CardModel(1, 1, "T", "body\n\n## raw | `md`", 1, 1, [])],
|
||||
[],
|
||||
ExportedAt));
|
||||
|
||||
StringAssert.Contains(markdown, "\nline one\n# not a heading | pipe\n");
|
||||
StringAssert.Contains(markdown, "\nbody\n\n## raw | `md`\n");
|
||||
}
|
||||
finally
|
||||
{
|
||||
Resources.Culture = original;
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void ColumnsAndCardsAreExportedInIdOrder()
|
||||
{
|
||||
CultureInfo? original = Resources.Culture;
|
||||
try
|
||||
{
|
||||
Resources.Culture = new CultureInfo("en");
|
||||
string markdown = MarkdownExporter.Export(
|
||||
"W",
|
||||
[new ColumnModel(2, "Second", string.Empty, 1, 1), new ColumnModel(1, "First", string.Empty, 1, 1)],
|
||||
[
|
||||
new CardModel(9, 1, "Nine", string.Empty, 1, 1, []),
|
||||
new CardModel(3, 2, "Three", string.Empty, 1, 1, []),
|
||||
new CardModel(4, 1, "Four", string.Empty, 1, 1, []),
|
||||
],
|
||||
[],
|
||||
ExportedAt);
|
||||
|
||||
int first = markdown.IndexOf(string.Format(Resources.Culture, Resources.Export_ColumnHeading, "First", 2), StringComparison.Ordinal);
|
||||
int second = markdown.IndexOf(string.Format(Resources.Culture, Resources.Export_ColumnHeading, "Second", 1), StringComparison.Ordinal);
|
||||
int four = markdown.IndexOf("### #4 Four", StringComparison.Ordinal);
|
||||
int nine = markdown.IndexOf("### #9 Nine", StringComparison.Ordinal);
|
||||
int three = markdown.IndexOf("### #3 Three", StringComparison.Ordinal);
|
||||
Assert.IsTrue(first >= 0 && first < four && four < nine && nine < second && second < three, markdown);
|
||||
}
|
||||
finally
|
||||
{
|
||||
Resources.Culture = original;
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[DataRow("en", "2026-09-30 14:25:37", "2026-09-01 10:00:05")]
|
||||
[DataRow("zh-Hans", "2026年9月30日 14:25", "2026年9月1日 10:00")]
|
||||
public void TimestampsUseThePlannedPerLanguageFormat(string language, string exportedAt, string cardTime)
|
||||
{
|
||||
CultureInfo? original = Resources.Culture;
|
||||
try
|
||||
{
|
||||
Resources.Culture = new CultureInfo(language);
|
||||
long cardSeconds = new DateTimeOffset(new DateTime(2026, 9, 1, 10, 0, 5)).ToUnixTimeSeconds();
|
||||
var exportMoment = new DateTimeOffset(new DateTime(2026, 9, 30, 14, 25, 37));
|
||||
string markdown = MarkdownExporter.Export(
|
||||
"W",
|
||||
[new ColumnModel(1, "C", string.Empty, 1, 1)],
|
||||
[new CardModel(1, 1, "T", string.Empty, cardSeconds, cardSeconds, [])],
|
||||
[],
|
||||
exportMoment);
|
||||
|
||||
StringAssert.Contains(markdown, string.Format(Resources.Culture, Resources.Export_ExportedAtLine, exportedAt));
|
||||
StringAssert.Contains(markdown, string.Format(Resources.Culture, Resources.Export_CreatedModifiedLine, cardTime, cardTime));
|
||||
}
|
||||
finally
|
||||
{
|
||||
|
||||
@@ -31,10 +31,46 @@ public class LaunchArgumentsTests
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void SinglePathIsAccepted()
|
||||
public void SingleAbsolutePathIsAccepted()
|
||||
{
|
||||
bool parsed = LaunchArguments.TryParse([@"C:\Repo\MyProject"], out string? path);
|
||||
string absolute = Path.Combine(Path.GetTempPath(), "Repo", "MyProject");
|
||||
bool parsed = LaunchArguments.TryParse([absolute], out string? path);
|
||||
Assert.IsTrue(parsed);
|
||||
Assert.AreEqual(@"C:\Repo\MyProject", path);
|
||||
Assert.AreEqual(absolute, path);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void RelativePathResolvesAgainstCurrentDirectory()
|
||||
{
|
||||
Assert.IsTrue(LaunchArguments.TryParse(["MyProject"], out string? path));
|
||||
Assert.AreEqual(Path.Combine(Environment.CurrentDirectory, "MyProject"), path);
|
||||
|
||||
Assert.IsTrue(LaunchArguments.TryParse(["."], out path));
|
||||
Assert.AreEqual(Path.GetFullPath(Environment.CurrentDirectory), path);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[DataRow("-")]
|
||||
[DataRow("-x")]
|
||||
[DataRow("--help")]
|
||||
[DataRow("--path=foo")]
|
||||
public void OptionLikeArgumentIsRejected(string argument)
|
||||
{
|
||||
Assert.IsFalse(LaunchArguments.TryParse([argument], out string? path));
|
||||
Assert.IsNull(path);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void OptionAlongsidePathIsRejected()
|
||||
{
|
||||
Assert.IsFalse(LaunchArguments.TryParse(["--help", "MyProject"], out string? path));
|
||||
Assert.IsNull(path);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void MalformedPathIsRejected()
|
||||
{
|
||||
Assert.IsFalse(LaunchArguments.TryParse(["a\0b"], out string? path));
|
||||
Assert.IsNull(path);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
using YKanBan.Models;
|
||||
using YKanBan.Storage.AppData;
|
||||
|
||||
namespace YKanBan.Tests.Models;
|
||||
|
||||
/// <summary>
|
||||
/// Tests for the in-column card display order: each sort option plus the id
|
||||
/// ascending tie-breaker.
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
public class CardOrderingTests
|
||||
{
|
||||
private static CardModel Card(long id, string title = "", long updatedAt = 0) =>
|
||||
new(id, 1, title, string.Empty, 0, updatedAt, []);
|
||||
|
||||
private static long[] Ids(IEnumerable<CardModel> cards, CardSortOption option) =>
|
||||
CardOrdering.Sort(cards, option).Select(card => card.Id).ToArray();
|
||||
|
||||
[TestMethod]
|
||||
public void IdSortsAscending()
|
||||
{
|
||||
CollectionAssert.AreEqual(new[] { 1L, 2L, 3L }, Ids([Card(3), Card(1), Card(2)], CardSortOption.Id));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void UpdatedAtSortsMostRecentFirstThenById()
|
||||
{
|
||||
CardModel[] cards = [Card(1, updatedAt: 10), Card(2, updatedAt: 30), Card(3, updatedAt: 10), Card(4, updatedAt: 20)];
|
||||
CollectionAssert.AreEqual(new[] { 2L, 4L, 1L, 3L }, Ids(cards, CardSortOption.UpdatedAt));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TitleSortsByCodePointWithEmptyFirstThenById()
|
||||
{
|
||||
CardModel[] cards = [Card(1, "b"), Card(2, "B"), Card(3, ""), Card(4, "a"), Card(5, "b")];
|
||||
CollectionAssert.AreEqual(new[] { 3L, 2L, 4L, 1L, 5L }, Ids(cards, CardSortOption.Title));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TitleSortsSupplementaryCharactersAfterBmpPrivateUse()
|
||||
{
|
||||
// U+1F600 is a surrogate pair in UTF-16, so ordinal comparison would put it before U+E000.
|
||||
CardModel[] cards = [Card(1, "\U0001F600"), Card(2, "")];
|
||||
CollectionAssert.AreEqual(new[] { 2L, 1L }, Ids(cards, CardSortOption.Title));
|
||||
}
|
||||
}
|
||||
@@ -147,9 +147,10 @@ public class SearchQueryParserTests
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void QualifierValueMayContainColons()
|
||||
public void QuotedQualifierValueMayContainColonsAndOperators()
|
||||
{
|
||||
AssertParsesTo(new SearchNode.TagName("a:b"), "tag:a:b");
|
||||
AssertParsesTo(new SearchNode.TagName("a:b"), "tag:\"a:b\"");
|
||||
AssertParsesTo(new SearchNode.TagName("AND"), "tag:\"AND\"");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
@@ -169,13 +170,20 @@ public class SearchQueryParserTests
|
||||
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()
|
||||
public void QuotedTextWithColonIsFreeText()
|
||||
{
|
||||
AssertParsesTo(new SearchNode.FreeText(":foo"), ":foo");
|
||||
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
|
||||
@@ -262,9 +270,58 @@ public class SearchQueryParserTests
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void NonNumericIdIsAnError()
|
||||
[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("id:12x");
|
||||
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]
|
||||
|
||||
@@ -169,10 +169,25 @@ public class SearchSqlCompilerTests
|
||||
{
|
||||
CompiledSearch compiled = SearchSqlCompiler.Compile(new SearchNode.FreeText("x"));
|
||||
|
||||
// One folded parameter shared by the title and content tests.
|
||||
StringAssert.Contains(compiled.Predicate, "$p0");
|
||||
StringAssert.Contains(compiled.Predicate, "$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);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void MatchingFoldsNonAsciiCase()
|
||||
{
|
||||
using var fixture = new SearchFixture();
|
||||
SqliteTestHelper.Exec(fixture.Connection, "INSERT INTO columns (title, description, created_at, updated_at) VALUES ('Érable', '', 1, 1);");
|
||||
SqliteTestHelper.Exec(fixture.Connection, "INSERT INTO cards (column_id, title, content, created_at, updated_at) VALUES (3, 'Ärger', 'Straße ΣΟΦΙΑ', 1, 1);");
|
||||
SqliteTestHelper.Exec(fixture.Connection, "INSERT INTO tags (name, color, description) VALUES ('Äpfel', '#123456', '');");
|
||||
SqliteTestHelper.Exec(fixture.Connection, "INSERT INTO card_tags (card_id, tag_id) VALUES (5, 4);");
|
||||
|
||||
CollectionAssert.AreEqual(new[] { 5L }, fixture.Search("ärger"));
|
||||
CollectionAssert.AreEqual(new[] { 5L }, fixture.Search("title:ÄRGER"));
|
||||
CollectionAssert.AreEqual(new[] { 5L }, fixture.Search("content:σοφια"));
|
||||
CollectionAssert.AreEqual(new[] { 5L }, fixture.Search("tag:äpfel"));
|
||||
CollectionAssert.AreEqual(new[] { 5L }, fixture.Search("column:érable"));
|
||||
}
|
||||
}
|
||||
@@ -145,7 +145,7 @@ public class AppConfigStoreTests
|
||||
{
|
||||
Language = "zh-Hans",
|
||||
Theme = ThemeOption.Light,
|
||||
Sort = new SortSettings { Card = CardSortOption.CreatedAt },
|
||||
Sort = new SortSettings { Card = CardSortOption.Title },
|
||||
ColumnWidth = new ColumnWidthSettings { Preset = ColumnWidthPreset.Wide },
|
||||
Confirmations = new ConfirmationSettings { DiscardEdit = false },
|
||||
};
|
||||
@@ -158,4 +158,148 @@ public class AppConfigStoreTests
|
||||
Assert.AreEqual(config.ColumnWidth.Preset, reloaded.ColumnWidth.Preset);
|
||||
Assert.AreEqual(config.Confirmations.DiscardEdit, reloaded.Confirmations.DiscardEdit);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void LoadNonObjectRootBacksUpAndReturnsDefaults()
|
||||
{
|
||||
using var directory = new TempDirectory();
|
||||
string path = Path.Combine(directory.FullPath, "app.json");
|
||||
File.WriteAllText(path, "[1, 2]");
|
||||
var store = new AppConfigStore(path);
|
||||
|
||||
Assert.AreEqual(AppConfig.DefaultLanguage, store.Load().Language);
|
||||
Assert.AreEqual("[1, 2]", File.ReadAllText(path + ".bak"));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[DataRow("\"theme\": \"sepia\"")]
|
||||
[DataRow("\"theme\": 1")]
|
||||
[DataRow("\"theme\": {}")]
|
||||
[DataRow("\"language\": \"fr\"")]
|
||||
[DataRow("\"language\": \"zh-hans\"")]
|
||||
[DataRow("\"language\": 5")]
|
||||
[DataRow("\"sort\": { \"card\": \"created-at\" }")]
|
||||
[DataRow("\"sort\": 7")]
|
||||
[DataRow("\"column-width\": { \"preset\": \"huge\", \"custom-pixels\": 159 }")]
|
||||
[DataRow("\"column-width\": { \"custom-pixels\": 721 }")]
|
||||
[DataRow("\"column-width\": { \"custom-pixels\": \"wide\" }")]
|
||||
[DataRow("\"confirmations\": { \"delete-card\": \"nope\" }")]
|
||||
[DataRow("\"version\": \"one\"")]
|
||||
public void InvalidFieldFallsBackAloneWithoutBackup(string invalidMember)
|
||||
{
|
||||
using var directory = new TempDirectory();
|
||||
string path = Path.Combine(directory.FullPath, "app.json");
|
||||
|
||||
// The valid fields are non-defaults, so any whole-file fallback would show.
|
||||
File.WriteAllText(path, $$"""
|
||||
{
|
||||
"theme": "dark",
|
||||
"confirmations": { "discard-edit": false },
|
||||
{{invalidMember}}
|
||||
}
|
||||
""");
|
||||
var store = new AppConfigStore(path);
|
||||
|
||||
AppConfig config = store.Load();
|
||||
|
||||
Assert.IsFalse(File.Exists(path + ".bak"));
|
||||
AppConfig defaults = new();
|
||||
Assert.AreEqual(invalidMember.Contains("theme") ? defaults.Theme : ThemeOption.Dark, config.Theme);
|
||||
if (!invalidMember.Contains("confirmations"))
|
||||
{
|
||||
Assert.IsFalse(config.Confirmations.DiscardEdit);
|
||||
}
|
||||
Assert.AreEqual(defaults.Language, config.Language);
|
||||
Assert.AreEqual(defaults.Sort.Card, config.Sort.Card);
|
||||
Assert.AreEqual(defaults.ColumnWidth.Preset, config.ColumnWidth.Preset);
|
||||
Assert.AreEqual(defaults.ColumnWidth.CustomPixels, config.ColumnWidth.CustomPixels);
|
||||
Assert.AreEqual(defaults.Confirmations.DeleteCard, config.Confirmations.DeleteCard);
|
||||
Assert.AreEqual(defaults.Version, config.Version);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void InvalidNestedFieldKeepsItsSiblings()
|
||||
{
|
||||
using var directory = new TempDirectory();
|
||||
string path = Path.Combine(directory.FullPath, "app.json");
|
||||
File.WriteAllText(path, """{ "column-width": { "preset": "bogus", "custom-pixels": 500 } }""");
|
||||
|
||||
AppConfig config = new AppConfigStore(path).Load();
|
||||
|
||||
Assert.AreEqual(ColumnWidthPreset.Standard, config.ColumnWidth.Preset);
|
||||
Assert.AreEqual(500, config.ColumnWidth.CustomPixels);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void ColumnWidthBoundsAreInclusive()
|
||||
{
|
||||
using var directory = new TempDirectory();
|
||||
string path = Path.Combine(directory.FullPath, "app.json");
|
||||
|
||||
File.WriteAllText(path, """{ "column-width": { "custom-pixels": 160 } }""");
|
||||
Assert.AreEqual(160, new AppConfigStore(path).Load().ColumnWidth.CustomPixels);
|
||||
|
||||
File.WriteAllText(path, """{ "column-width": { "custom-pixels": 720 } }""");
|
||||
Assert.AreEqual(720, new AppConfigStore(path).Load().ColumnWidth.CustomPixels);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void UnchangedConfigurationIsNotWritten()
|
||||
{
|
||||
using var directory = new TempDirectory();
|
||||
string path = Path.Combine(directory.FullPath, "app.json");
|
||||
var store = new AppConfigStore(path);
|
||||
|
||||
AppConfig config = store.Load();
|
||||
|
||||
Assert.IsFalse(store.SaveIfChanged(config));
|
||||
Assert.IsFalse(File.Exists(path));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void FieldFallbackAloneDoesNotRewriteTheFile()
|
||||
{
|
||||
using var directory = new TempDirectory();
|
||||
string path = Path.Combine(directory.FullPath, "app.json");
|
||||
const string original = """{ "theme": "sepia" }""";
|
||||
File.WriteAllText(path, original);
|
||||
var store = new AppConfigStore(path);
|
||||
|
||||
AppConfig config = store.Load();
|
||||
|
||||
Assert.IsFalse(store.SaveIfChanged(config));
|
||||
Assert.AreEqual(original, File.ReadAllText(path));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void ChangedConfigurationIsWrittenOnce()
|
||||
{
|
||||
using var directory = new TempDirectory();
|
||||
string path = Path.Combine(directory.FullPath, "app.json");
|
||||
var store = new AppConfigStore(path);
|
||||
AppConfig config = store.Load();
|
||||
|
||||
config.Sort.Card = CardSortOption.UpdatedAt;
|
||||
|
||||
Assert.IsTrue(store.SaveIfChanged(config));
|
||||
Assert.AreEqual(CardSortOption.UpdatedAt, new AppConfigStore(path).Load().Sort.Card);
|
||||
|
||||
// Saved state is the new baseline.
|
||||
Assert.IsFalse(store.SaveIfChanged(config));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void ChangeRevertedWithinSessionIsNotWritten()
|
||||
{
|
||||
using var directory = new TempDirectory();
|
||||
string path = Path.Combine(directory.FullPath, "app.json");
|
||||
var store = new AppConfigStore(path);
|
||||
AppConfig config = store.Load();
|
||||
|
||||
config.Theme = ThemeOption.Dark;
|
||||
config.Theme = ThemeOption.FollowSystem;
|
||||
|
||||
Assert.IsFalse(store.SaveIfChanged(config));
|
||||
Assert.IsFalse(File.Exists(path));
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,7 @@
|
||||
using Microsoft.Data.Sqlite;
|
||||
using YKanBan.Models;
|
||||
using YKanBan.Search;
|
||||
using YKanBan.Storage;
|
||||
using YKanBan.Storage.Workspace;
|
||||
using YKanBan.Tests.TestUtilities;
|
||||
|
||||
@@ -253,8 +255,87 @@ public class WorkspaceRepositoryTests
|
||||
public void AddTagWithDuplicateNameIsRejected()
|
||||
{
|
||||
using var fixture = new RepositoryFixture();
|
||||
Assert.ThrowsExactly<SqliteException>(() =>
|
||||
fixture.Repository.AddTag("bug", RgbColor.Parse("#123456"), ""));
|
||||
DuplicateNameException exception = Assert.ThrowsExactly<DuplicateNameException>(() =>
|
||||
fixture.Repository.AddTag("BUG", RgbColor.Parse("#123456"), ""));
|
||||
Assert.AreEqual(NamedEntity.Tag, exception.Entity);
|
||||
Assert.AreEqual("BUG", exception.Name);
|
||||
Assert.AreEqual(2, fixture.Repository.GetTags().Count);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void AddTagWithEmptyNameIsRejected()
|
||||
{
|
||||
using var fixture = new RepositoryFixture();
|
||||
NameRequiredException exception = Assert.ThrowsExactly<NameRequiredException>(() =>
|
||||
fixture.Repository.AddTag("", RgbColor.Parse("#123456"), ""));
|
||||
Assert.AreEqual(NamedEntity.Tag, exception.Entity);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void UpdateTagToExistingNameIsRejectedAndKeepsTheRow()
|
||||
{
|
||||
using var fixture = new RepositoryFixture();
|
||||
Assert.ThrowsExactly<DuplicateNameException>(() =>
|
||||
fixture.Repository.UpdateTag(fixture.UiTagId, "Bug", RgbColor.Parse("#00ff00"), ""));
|
||||
Assert.AreEqual("ui", fixture.Repository.GetTags().Single(tag => tag.Id == fixture.UiTagId).Name);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void AddColumnWithDuplicateTitleIsRejectedCaseInsensitively()
|
||||
{
|
||||
using var fixture = new RepositoryFixture();
|
||||
DuplicateNameException exception = Assert.ThrowsExactly<DuplicateNameException>(() =>
|
||||
fixture.Repository.AddColumn("COL", ""));
|
||||
Assert.AreEqual(NamedEntity.Column, exception.Entity);
|
||||
Assert.AreEqual(1, fixture.Repository.GetColumns().Count);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void AddColumnWithEmptyTitleIsRejected()
|
||||
{
|
||||
using var fixture = new RepositoryFixture();
|
||||
NameRequiredException exception = Assert.ThrowsExactly<NameRequiredException>(() =>
|
||||
fixture.Repository.AddColumn("", "description"));
|
||||
Assert.AreEqual(NamedEntity.Column, exception.Entity);
|
||||
Assert.AreEqual(1, fixture.Repository.GetColumns().Count);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void UpdateColumnConstraintViolationsAreTyped()
|
||||
{
|
||||
using var fixture = new RepositoryFixture();
|
||||
ColumnModel other = fixture.Repository.AddColumn("Other", "");
|
||||
|
||||
Assert.ThrowsExactly<DuplicateNameException>(() => fixture.Repository.UpdateColumn(other.Id, "col", ""));
|
||||
Assert.ThrowsExactly<NameRequiredException>(() => fixture.Repository.UpdateColumn(other.Id, "", ""));
|
||||
Assert.AreEqual("Other", fixture.Repository.GetColumn(other.Id)!.Title);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void GetCardsWithFilterReturnsMatchesWithAllOfTheirTags()
|
||||
{
|
||||
using var fixture = new RepositoryFixture();
|
||||
fixture.Repository.AddCard(fixture.ColumnId, "Other", "", []);
|
||||
|
||||
// Filtering by one tag must still load both tags of the matching card.
|
||||
CompiledSearch filter = SearchSqlCompiler.Compile(SearchQueryParser.Parse("tag:ui")!);
|
||||
IReadOnlyList<CardModel> cards = fixture.Repository.GetCards(filter);
|
||||
|
||||
Assert.AreEqual(1, cards.Count);
|
||||
Assert.AreEqual(fixture.CardId, cards[0].Id);
|
||||
CollectionAssert.AreEqual(new[] { "bug", "ui" }, cards[0].Tags.Select(tag => tag.Name).ToArray());
|
||||
Assert.AreEqual(2, fixture.Repository.GetCards(null).Count);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CountCardsCountsPerColumn()
|
||||
{
|
||||
using var fixture = new RepositoryFixture();
|
||||
ColumnModel empty = fixture.Repository.AddColumn("Empty", "");
|
||||
fixture.Repository.AddCard(fixture.ColumnId, "", "", []);
|
||||
|
||||
Assert.AreEqual(2L, fixture.Repository.CountCards(fixture.ColumnId));
|
||||
Assert.AreEqual(0L, fixture.Repository.CountCards(empty.Id));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
|
||||
@@ -65,15 +65,44 @@ public class WorkspaceSchemaTests
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void ColumnTitlesCompareCaseSensitively()
|
||||
public void ColumnTitlesDifferingOnlyInAsciiCaseAreRejected()
|
||||
{
|
||||
using var db = new FreshDatabase();
|
||||
// BINARY collation: 'Foo' and 'foo' are distinct titles.
|
||||
// NOCASE uniqueness: 'Foo' and 'foo' cannot coexist.
|
||||
SqliteTestHelper.Exec(db.Connection, "INSERT INTO columns (title, created_at, updated_at) VALUES ('Foo', 1, 1);");
|
||||
SqliteTestHelper.Exec(db.Connection, "INSERT INTO columns (title, created_at, updated_at) VALUES ('foo', 1, 1);");
|
||||
Assert.ThrowsExactly<SqliteException>(() =>
|
||||
SqliteTestHelper.Exec(db.Connection, "INSERT INTO columns (title, created_at, updated_at) VALUES ('foo', 1, 1);"));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void ColumnTitlesDifferingOnlyInNonAsciiCaseAreAccepted()
|
||||
{
|
||||
using var db = new FreshDatabase();
|
||||
// NOCASE folds ASCII only: 'Ä' and 'ä' remain distinct titles.
|
||||
SqliteTestHelper.Exec(db.Connection, "INSERT INTO columns (title, created_at, updated_at) VALUES ('Ä', 1, 1);");
|
||||
SqliteTestHelper.Exec(db.Connection, "INSERT INTO columns (title, created_at, updated_at) VALUES ('ä', 1, 1);");
|
||||
Assert.AreEqual(2L, SqliteTestHelper.ScalarLong(db.Connection, "SELECT COUNT(*) FROM columns;"));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void ColumnTitleCaseOnlyRenameOfSameRowIsAccepted()
|
||||
{
|
||||
using var db = new FreshDatabase();
|
||||
SqliteTestHelper.Exec(db.Connection, "INSERT INTO columns (title, created_at, updated_at) VALUES ('Foo', 1, 1);");
|
||||
int affected = SqliteTestHelper.Exec(db.Connection, "UPDATE columns SET title = 'foo' WHERE id = 1;");
|
||||
Assert.AreEqual(1, affected);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void ColumnTitlesStillOrderByCodePoint()
|
||||
{
|
||||
using var db = new FreshDatabase();
|
||||
// Uniqueness is NOCASE, but the column collation stays BINARY: 'B' (0x42) sorts before 'a' (0x61).
|
||||
SqliteTestHelper.Exec(db.Connection, "INSERT INTO columns (title, created_at, updated_at) VALUES ('a', 1, 1);");
|
||||
SqliteTestHelper.Exec(db.Connection, "INSERT INTO columns (title, created_at, updated_at) VALUES ('B', 1, 1);");
|
||||
Assert.AreEqual("B", SqliteTestHelper.ScalarString(db.Connection, "SELECT title FROM columns ORDER BY title LIMIT 1;"));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void EmptyTagNameIsRejected()
|
||||
{
|
||||
@@ -103,6 +132,24 @@ public class WorkspaceSchemaTests
|
||||
SqliteTestHelper.Exec(db.Connection, "INSERT INTO tags (name, color) VALUES ('bug', '#445566');"));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TagNamesDifferingOnlyInAsciiCaseAreRejected()
|
||||
{
|
||||
using var db = new FreshDatabase();
|
||||
SqliteTestHelper.Exec(db.Connection, "INSERT INTO tags (name, color) VALUES ('bug', '#112233');");
|
||||
Assert.ThrowsExactly<SqliteException>(() =>
|
||||
SqliteTestHelper.Exec(db.Connection, "INSERT INTO tags (name, color) VALUES ('BUG', '#445566');"));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TagNamesDifferingOnlyInNonAsciiCaseAreAccepted()
|
||||
{
|
||||
using var db = new FreshDatabase();
|
||||
SqliteTestHelper.Exec(db.Connection, "INSERT INTO tags (name, color) VALUES ('Ä', '#112233');");
|
||||
SqliteTestHelper.Exec(db.Connection, "INSERT INTO tags (name, color) VALUES ('ä', '#445566');");
|
||||
Assert.AreEqual(2L, SqliteTestHelper.ScalarLong(db.Connection, "SELECT COUNT(*) FROM tags;"));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[DataRow("#000000")]
|
||||
[DataRow("#FFFFFF")]
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
using YKanBan.ViewModels.Dialogs;
|
||||
|
||||
namespace YKanBan.Tests.TestUtilities;
|
||||
|
||||
/// <summary>
|
||||
/// Records every dialog shown and lets a test script answer it. The result
|
||||
/// is whatever the dialog closed with; a dialog the script leaves open
|
||||
/// counts as dismissed. The save-file dialog answers with
|
||||
/// <see cref="SaveFilePath"/>.
|
||||
/// </summary>
|
||||
internal sealed class ScriptedDialogService : IDialogService
|
||||
{
|
||||
public List<DialogViewModelBase> Shown { get; } = [];
|
||||
|
||||
public Func<DialogViewModelBase, Task> Script { get; set; } = _ => Task.CompletedTask;
|
||||
|
||||
public string? SaveFilePath { get; set; }
|
||||
|
||||
public List<string> SuggestedFileNames { get; } = [];
|
||||
|
||||
public async Task<bool> ShowAsync(DialogViewModelBase dialog)
|
||||
{
|
||||
Shown.Add(dialog);
|
||||
bool? result = null;
|
||||
dialog.CloseRequested += (_, closed) => result ??= closed;
|
||||
await Script(dialog);
|
||||
return result ?? false;
|
||||
}
|
||||
|
||||
public Task<string?> PickSaveFilePathAsync(string suggestedFileName)
|
||||
{
|
||||
SuggestedFileNames.Add(suggestedFileName);
|
||||
return Task.FromResult(SaveFilePath);
|
||||
}
|
||||
|
||||
/// <summary>Answers every confirmation dialog with the given choice.</summary>
|
||||
public static Func<DialogViewModelBase, Task> AnswerConfirmations(bool confirm) => dialog =>
|
||||
{
|
||||
if (dialog is ConfirmDialogViewModel confirmation)
|
||||
{
|
||||
if (confirm)
|
||||
{
|
||||
confirmation.ConfirmCommand.Execute(null);
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
return confirmation.CancelCommand.ExecuteAsync(null);
|
||||
}
|
||||
return Task.CompletedTask;
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,357 @@
|
||||
using YKanBan.Models;
|
||||
using YKanBan.Search;
|
||||
using YKanBan.Storage;
|
||||
using YKanBan.Storage.AppData;
|
||||
using YKanBan.Storage.Workspace;
|
||||
using YKanBan.Tests.TestUtilities;
|
||||
using YKanBan.ViewModels.Board;
|
||||
using YKanBan.ViewModels.Dialogs;
|
||||
|
||||
namespace YKanBan.Tests.ViewModels;
|
||||
|
||||
/// <summary>
|
||||
/// View-model tests of the board and its dialogs against a real temporary
|
||||
/// workspace, with a scripted dialog service standing in for the modal windows.
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
public class BoardViewModelTests
|
||||
{
|
||||
private sealed class Fixture : IDisposable
|
||||
{
|
||||
public TempDirectory Directory { get; } = new();
|
||||
|
||||
public WorkspaceRepository Repository { get; }
|
||||
|
||||
public AppConfig Config { get; } = new();
|
||||
|
||||
public ScriptedDialogService Dialogs { get; } = new();
|
||||
|
||||
public Fixture()
|
||||
{
|
||||
WorkspaceInitializer.Initialize(Directory.FullPath);
|
||||
Repository = new WorkspaceRepository(Directory.FullPath);
|
||||
}
|
||||
|
||||
public BoardViewModel CreateBoard() => new(Repository, Config, Dialogs);
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
Repository.Dispose();
|
||||
Directory.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void RefreshListsColumnsInIdOrderAndSortsCardsWithinEachColumn()
|
||||
{
|
||||
using var fixture = new Fixture();
|
||||
ColumnModel first = fixture.Repository.AddColumn("A", "");
|
||||
ColumnModel second = fixture.Repository.AddColumn("B", "");
|
||||
fixture.Repository.AddCard(first.Id, "zeta", "", []);
|
||||
fixture.Repository.AddCard(first.Id, "alpha", "", []);
|
||||
fixture.Repository.AddCard(second.Id, "x", "", []);
|
||||
|
||||
fixture.Config.Sort.Card = CardSortOption.Title;
|
||||
BoardViewModel board = fixture.CreateBoard();
|
||||
|
||||
CollectionAssert.AreEqual(new[] { "A", "B" }, board.Columns.Select(column => column.Title).ToArray());
|
||||
CollectionAssert.AreEqual(new[] { "alpha", "zeta" }, board.Columns[0].Cards.Select(card => card.Title).ToArray());
|
||||
Assert.AreEqual(1, board.Columns[1].CardCount);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void ChangingTheSortPersistsItToTheConfigurationAndResorts()
|
||||
{
|
||||
using var fixture = new Fixture();
|
||||
ColumnModel column = fixture.Repository.AddColumn("A", "");
|
||||
fixture.Repository.AddCard(column.Id, "b", "", []);
|
||||
fixture.Repository.AddCard(column.Id, "a", "", []);
|
||||
BoardViewModel board = fixture.CreateBoard();
|
||||
CollectionAssert.AreEqual(new[] { "b", "a" }, board.Columns[0].Cards.Select(card => card.Title).ToArray());
|
||||
|
||||
board.SelectedSort = board.SortOptions.Single(option => (CardSortOption)option.Value == CardSortOption.Title);
|
||||
|
||||
Assert.AreEqual(CardSortOption.Title, fixture.Config.Sort.Card);
|
||||
CollectionAssert.AreEqual(new[] { "a", "b" }, board.Columns[0].Cards.Select(card => card.Title).ToArray());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task WritesRefreshWithTheActiveFilterAndKeepEmptyColumns()
|
||||
{
|
||||
using var fixture = new Fixture();
|
||||
ColumnModel todo = fixture.Repository.AddColumn("Todo", "");
|
||||
ColumnModel done = fixture.Repository.AddColumn("Done", "");
|
||||
CardModel match = fixture.Repository.AddCard(todo.Id, "match me", "", []);
|
||||
fixture.Repository.AddCard(todo.Id, "other", "", []);
|
||||
|
||||
BoardViewModel board = fixture.CreateBoard();
|
||||
board.ActiveFilter = SearchSqlCompiler.Compile(SearchQueryParser.Parse("match")!);
|
||||
board.Refresh();
|
||||
Assert.AreEqual(1, board.Columns[0].CardCount);
|
||||
|
||||
// A move is a write: the board re-queries with the active filter.
|
||||
CardViewModel card = board.Columns[0].Cards.Single();
|
||||
MoveTargetViewModel target = card.MoveTargets.Single(entry => entry.ColumnId == done.Id);
|
||||
Assert.IsFalse(card.MoveTargets.Single(entry => entry.ColumnId == todo.Id).IsEnabled);
|
||||
await target.Command.ExecuteAsync(target.ColumnId);
|
||||
|
||||
Assert.AreEqual(2, board.Columns.Count, "Columns emptied by the filter stay on the board.");
|
||||
Assert.AreEqual(0, board.Columns[0].CardCount);
|
||||
Assert.AreEqual(match.Id, board.Columns[1].Cards.Single().Card.Id);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task DeclinedColumnDeletionKeepsTheColumnAndShowsItsCardCount()
|
||||
{
|
||||
using var fixture = new Fixture();
|
||||
ColumnModel column = fixture.Repository.AddColumn("A", "");
|
||||
fixture.Repository.AddCard(column.Id, "", "", []);
|
||||
fixture.Repository.AddCard(column.Id, "", "", []);
|
||||
BoardViewModel board = fixture.CreateBoard();
|
||||
fixture.Dialogs.Script = ScriptedDialogService.AnswerConfirmations(false);
|
||||
|
||||
await board.Columns[0].DeleteCommand.ExecuteAsync(null);
|
||||
|
||||
var confirmation = (ConfirmDialogViewModel)fixture.Dialogs.Shown.Single();
|
||||
StringAssert.Contains(confirmation.Message, "2");
|
||||
Assert.AreEqual(1, fixture.Repository.GetColumns().Count);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task ColumnDeletionWithoutConfirmationDeletesImmediately()
|
||||
{
|
||||
using var fixture = new Fixture();
|
||||
fixture.Repository.AddColumn("A", "");
|
||||
fixture.Config.Confirmations.DeleteColumn = false;
|
||||
BoardViewModel board = fixture.CreateBoard();
|
||||
|
||||
await board.Columns[0].DeleteCommand.ExecuteAsync(null);
|
||||
|
||||
Assert.AreEqual(0, fixture.Dialogs.Shown.Count);
|
||||
Assert.AreEqual(0, board.Columns.Count);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task ConfirmedCardDeletionDeletesTheCard()
|
||||
{
|
||||
using var fixture = new Fixture();
|
||||
ColumnModel column = fixture.Repository.AddColumn("A", "");
|
||||
fixture.Repository.AddCard(column.Id, "gone", "", []);
|
||||
BoardViewModel board = fixture.CreateBoard();
|
||||
fixture.Dialogs.Script = ScriptedDialogService.AnswerConfirmations(true);
|
||||
|
||||
await board.Columns[0].Cards[0].DeleteCommand.ExecuteAsync(null);
|
||||
|
||||
Assert.AreEqual(0, board.Columns[0].CardCount);
|
||||
Assert.AreEqual(0, fixture.Repository.GetCards().Count);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task DuplicateColumnTitleIsReportedInsideTheDialog()
|
||||
{
|
||||
using var fixture = new Fixture();
|
||||
fixture.Repository.AddColumn("Todo", "");
|
||||
BoardViewModel board = fixture.CreateBoard();
|
||||
ColumnEditorDialogViewModel? editor = null;
|
||||
bool closed = false;
|
||||
fixture.Dialogs.Script = dialog =>
|
||||
{
|
||||
editor = (ColumnEditorDialogViewModel)dialog;
|
||||
editor.CloseRequested += (_, _) => closed = true;
|
||||
editor.ColumnTitle = "TODO";
|
||||
editor.ConfirmCommand.Execute(null);
|
||||
return Task.CompletedTask;
|
||||
};
|
||||
|
||||
await board.AddColumnCommand.ExecuteAsync(null);
|
||||
|
||||
Assert.IsNotNull(editor);
|
||||
Assert.IsFalse(closed, "The dialog stays open on a constraint violation.");
|
||||
Assert.IsTrue(editor.HasError);
|
||||
StringAssert.Contains(editor.ErrorMessage, "TODO");
|
||||
Assert.AreEqual(1, fixture.Repository.GetColumns().Count);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task NewCardIsWrittenWithItsTagsOnConfirmation()
|
||||
{
|
||||
using var fixture = new Fixture();
|
||||
ColumnModel column = fixture.Repository.AddColumn("A", "");
|
||||
TagModel bug = fixture.Repository.AddTag("bug", new RgbColor(255, 0, 0), "");
|
||||
BoardViewModel board = fixture.CreateBoard();
|
||||
fixture.Dialogs.Script = async dialog =>
|
||||
{
|
||||
switch (dialog)
|
||||
{
|
||||
case CardEditorDialogViewModel editor:
|
||||
editor.CardTitle = "Fix it";
|
||||
editor.Content = "Details";
|
||||
await editor.AddTagCommand.ExecuteAsync(null);
|
||||
editor.ConfirmCommand.Execute(null);
|
||||
break;
|
||||
case TagPickerDialogViewModel picker:
|
||||
picker.PickCommand.Execute(picker.FilteredTags.Single());
|
||||
break;
|
||||
}
|
||||
};
|
||||
|
||||
await board.Columns[0].AddCardCommand.ExecuteAsync(null);
|
||||
|
||||
CardModel card = fixture.Repository.GetCards().Single();
|
||||
Assert.AreEqual("Fix it", card.Title);
|
||||
Assert.AreEqual("Details", card.Content);
|
||||
Assert.AreEqual(bug.Id, card.Tags.Single().Id);
|
||||
Assert.AreEqual(card.Id, board.Columns[0].Cards.Single().Card.Id);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void UnchangedEditConfirmationWritesNothing()
|
||||
{
|
||||
using var fixture = new Fixture();
|
||||
ColumnModel column = fixture.Repository.AddColumn("A", "");
|
||||
CardModel card = fixture.Repository.AddCard(column.Id, "t", "c", []);
|
||||
using (var connection = SqliteTestHelper.OpenWorkspace(fixture.Directory.FullPath))
|
||||
{
|
||||
SqliteTestHelper.Exec(connection, "UPDATE cards SET updated_at = 100;");
|
||||
}
|
||||
card = fixture.Repository.GetCard(card.Id)!;
|
||||
|
||||
var editor = CardEditorDialogViewModel.ForExistingCard(fixture.Repository, fixture.Dialogs, card, confirmDiscard: true);
|
||||
editor.CardTitle = "changed";
|
||||
editor.CardTitle = "t";
|
||||
Assert.IsFalse(editor.IsDirty);
|
||||
editor.ConfirmCommand.Execute(null);
|
||||
|
||||
Assert.AreEqual(100, fixture.Repository.GetCard(card.Id)!.UpdatedAt);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task DirtyCancelAsksAndStaysOpenWhenDeclined()
|
||||
{
|
||||
using var fixture = new Fixture();
|
||||
ColumnModel column = fixture.Repository.AddColumn("A", "");
|
||||
var editor = CardEditorDialogViewModel.ForNewCard(fixture.Repository, fixture.Dialogs, column.Id, confirmDiscard: true);
|
||||
bool? closedWith = null;
|
||||
editor.CloseRequested += (_, result) => closedWith = result;
|
||||
editor.Content = "draft";
|
||||
|
||||
fixture.Dialogs.Script = ScriptedDialogService.AnswerConfirmations(false);
|
||||
await editor.RequestCancelAsync();
|
||||
Assert.IsNull(closedWith, "Declining the discard keeps the editor open.");
|
||||
|
||||
fixture.Dialogs.Script = ScriptedDialogService.AnswerConfirmations(true);
|
||||
await editor.RequestCancelAsync();
|
||||
Assert.IsFalse(closedWith);
|
||||
Assert.AreEqual(0, fixture.Repository.GetCards().Count);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task CleanCancelClosesWithoutAsking()
|
||||
{
|
||||
using var fixture = new Fixture();
|
||||
ColumnModel column = fixture.Repository.AddColumn("A", "");
|
||||
var editor = CardEditorDialogViewModel.ForNewCard(fixture.Repository, fixture.Dialogs, column.Id, confirmDiscard: true);
|
||||
bool? closedWith = null;
|
||||
editor.CloseRequested += (_, result) => closedWith = result;
|
||||
|
||||
await editor.RequestCancelAsync();
|
||||
|
||||
Assert.IsFalse(closedWith);
|
||||
Assert.AreEqual(0, fixture.Dialogs.Shown.Count);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task TagCreatedInThePickerSurvivesACancelledCardEdit()
|
||||
{
|
||||
using var fixture = new Fixture();
|
||||
ColumnModel column = fixture.Repository.AddColumn("A", "");
|
||||
var editor = CardEditorDialogViewModel.ForNewCard(fixture.Repository, fixture.Dialogs, column.Id, confirmDiscard: false);
|
||||
fixture.Dialogs.Script = dialog =>
|
||||
{
|
||||
if (dialog is TagPickerDialogViewModel picker)
|
||||
{
|
||||
picker.NewName = "fresh";
|
||||
picker.NewColor = "#123456";
|
||||
picker.CreateCommand.Execute(null);
|
||||
}
|
||||
return Task.CompletedTask;
|
||||
};
|
||||
|
||||
await editor.AddTagCommand.ExecuteAsync(null);
|
||||
Assert.AreEqual("fresh", editor.Tags.Single().Name);
|
||||
await editor.RequestCancelAsync();
|
||||
|
||||
Assert.AreEqual("fresh", fixture.Repository.GetTags().Single().Name);
|
||||
Assert.AreEqual(0, fixture.Repository.GetCards().Count);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TagPickerReportsInvalidColorAndDuplicateNameWithoutClosing()
|
||||
{
|
||||
using var fixture = new Fixture();
|
||||
fixture.Repository.AddTag("bug", new RgbColor(1, 2, 3), "");
|
||||
var picker = new TagPickerDialogViewModel(fixture.Repository, []);
|
||||
bool closed = false;
|
||||
picker.CloseRequested += (_, _) => closed = true;
|
||||
|
||||
picker.NewName = "new";
|
||||
picker.NewColor = "red";
|
||||
picker.CreateCommand.Execute(null);
|
||||
Assert.AreEqual(YKanBan.Resources.Error_Tag_InvalidColor, picker.ErrorMessage);
|
||||
|
||||
picker.NewName = "BUG";
|
||||
picker.NewColor = "#ff0000";
|
||||
picker.CreateCommand.Execute(null);
|
||||
StringAssert.Contains(picker.ErrorMessage, "BUG");
|
||||
|
||||
Assert.IsFalse(closed);
|
||||
Assert.AreEqual(1, fixture.Repository.GetTags().Count);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TagPickerHidesAssignedTagsAndFiltersCaseInsensitively()
|
||||
{
|
||||
using var fixture = new Fixture();
|
||||
TagModel bug = fixture.Repository.AddTag("Bug", new RgbColor(1, 2, 3), "");
|
||||
fixture.Repository.AddTag("UI", new RgbColor(1, 2, 3), "");
|
||||
fixture.Repository.AddTag("Build", new RgbColor(1, 2, 3), "");
|
||||
var picker = new TagPickerDialogViewModel(fixture.Repository, [bug.Id]);
|
||||
|
||||
picker.FilterText = "bu";
|
||||
CollectionAssert.AreEqual(new[] { "Build" }, picker.FilteredTags.Select(tag => tag.Name).ToArray());
|
||||
|
||||
picker.FilterText = "zzz";
|
||||
Assert.IsTrue(picker.NoMatches);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void ColumnWidthDialogCommitsPresetsAndClampsCustomPixels()
|
||||
{
|
||||
var settings = new ColumnWidthSettings();
|
||||
var dialog = new ColumnWidthDialogViewModel(settings) { IsStandard = false, IsCustom = true, CustomPixels = 5000 };
|
||||
dialog.ConfirmCommand.Execute(null);
|
||||
Assert.AreEqual(ColumnWidthPreset.Custom, settings.Preset);
|
||||
Assert.AreEqual(AppConfig.MaxColumnPixels, settings.CustomPixels);
|
||||
Assert.AreEqual(AppConfig.MaxColumnPixels, ColumnWidths.Resolve(settings));
|
||||
|
||||
dialog = new ColumnWidthDialogViewModel(settings) { IsCustom = false, IsWide = true };
|
||||
dialog.ConfirmCommand.Execute(null);
|
||||
Assert.AreEqual(ColumnWidthPreset.Wide, settings.Preset);
|
||||
Assert.AreEqual(ColumnWidths.Wide, ColumnWidths.Resolve(settings));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CardHeaderAndExcerptFollowTheDisplayRules()
|
||||
{
|
||||
var untitled = new CardModel(61, 1, "", "", 0, 0, []);
|
||||
var titled = untitled with { Title = "Foo bar" };
|
||||
Assert.AreEqual("#61", CardViewModel.FormatHeader(untitled));
|
||||
Assert.AreEqual("#61 Foo bar", CardViewModel.FormatHeader(titled));
|
||||
|
||||
Assert.AreEqual("short", CardViewModel.MakeExcerpt(" short \n"));
|
||||
string longContent = string.Concat(Enumerable.Repeat("😀", CardViewModel.ExcerptLength + 5));
|
||||
string excerpt = CardViewModel.MakeExcerpt(longContent);
|
||||
Assert.IsTrue(excerpt.EndsWith('…'));
|
||||
Assert.AreEqual((CardViewModel.ExcerptLength * 2) + 1, excerpt.Length, "Surrogate pairs are kept whole.");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
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_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);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,400 @@
|
||||
using YKanBan.Models;
|
||||
using YKanBan.Storage.AppData;
|
||||
using YKanBan.Storage.Workspace;
|
||||
using YKanBan.Tests.TestUtilities;
|
||||
using YKanBan.ViewModels;
|
||||
using YKanBan.ViewModels.Board;
|
||||
using YKanBan.ViewModels.Dialogs;
|
||||
using YKanBan.ViewModels.Tags;
|
||||
|
||||
namespace YKanBan.Tests.ViewModels;
|
||||
|
||||
/// <summary>
|
||||
/// View-model tests of the search bar, the tags tab, the cross-tab refresh and
|
||||
/// the export wiring, against a real temporary workspace with a scripted
|
||||
/// dialog service.
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
public class TagsAndSearchViewModelTests
|
||||
{
|
||||
private sealed class Fixture : IDisposable
|
||||
{
|
||||
public TempDirectory Directory { get; } = new();
|
||||
|
||||
public WorkspaceSession Session { get; }
|
||||
|
||||
public WorkspaceRepository Repository => Session.Repository;
|
||||
|
||||
public AppConfig Config { get; } = new();
|
||||
|
||||
public ScriptedDialogService Dialogs { get; } = new();
|
||||
|
||||
public Fixture()
|
||||
{
|
||||
WorkspaceInitializer.Initialize(Directory.FullPath);
|
||||
Session = WorkspaceSession.Open(Directory.FullPath);
|
||||
}
|
||||
|
||||
public BoardViewModel CreateBoard() => new(Repository, Config, Dialogs);
|
||||
|
||||
public TagsViewModel CreateTags() => new(Repository, Config, Dialogs);
|
||||
|
||||
public WorkspaceViewModel CreateWorkspace() =>
|
||||
new(Session, new Interaction<Unit>(), new Interaction<Unit>(), Config, Dialogs);
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
Session.Dispose();
|
||||
Directory.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
private static string[] VisibleTitles(BoardViewModel board) =>
|
||||
board.Columns.SelectMany(column => column.Cards).Select(card => card.Title).Order(StringComparer.Ordinal).ToArray();
|
||||
|
||||
/// <summary>Moves a visible card through its menu command.</summary>
|
||||
private static Task MoveAsync(BoardViewModel board, long cardId, long columnId) =>
|
||||
board.Columns.SelectMany(column => column.Cards).Single(card => card.Card.Id == cardId)
|
||||
.MoveToCommand.ExecuteAsync(columnId);
|
||||
|
||||
#region Search
|
||||
|
||||
[TestMethod]
|
||||
public async Task SearchFiltersCardsAndKeepsEmptyColumns()
|
||||
{
|
||||
using var fixture = new Fixture();
|
||||
ColumnModel first = fixture.Repository.AddColumn("A", "");
|
||||
ColumnModel second = fixture.Repository.AddColumn("B", "");
|
||||
TagModel bug = fixture.Repository.AddTag("bug", new RgbColor(1, 2, 3), "");
|
||||
fixture.Repository.AddCard(first.Id, "crash", "", [bug.Id]);
|
||||
fixture.Repository.AddCard(second.Id, "idea", "", []);
|
||||
BoardViewModel board = fixture.CreateBoard();
|
||||
|
||||
board.SearchText = "tag:BUG";
|
||||
await board.SearchCommand.ExecuteAsync(null);
|
||||
|
||||
CollectionAssert.AreEqual(new[] { "crash" }, VisibleTitles(board));
|
||||
Assert.AreEqual(2, board.Columns.Count);
|
||||
Assert.AreEqual(0, board.Columns[1].CardCount);
|
||||
Assert.IsNotNull(board.ActiveFilter);
|
||||
Assert.AreEqual(0, fixture.Dialogs.Shown.Count);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task InvalidSearchShowsTheErrorAndKeepsTextAndPreviousResult()
|
||||
{
|
||||
using var fixture = new Fixture();
|
||||
ColumnModel column = fixture.Repository.AddColumn("A", "");
|
||||
fixture.Repository.AddCard(column.Id, "alpha", "", []);
|
||||
fixture.Repository.AddCard(column.Id, "beta", "", []);
|
||||
BoardViewModel board = fixture.CreateBoard();
|
||||
board.SearchText = "alpha";
|
||||
await board.SearchCommand.ExecuteAsync(null);
|
||||
|
||||
board.SearchText = "alpha AND";
|
||||
await board.SearchCommand.ExecuteAsync(null);
|
||||
|
||||
var error = (MessageDialogViewModel)fixture.Dialogs.Shown.Single();
|
||||
Assert.AreEqual(Resources.Search_Error_Title, error.Title);
|
||||
Assert.AreEqual("alpha AND", board.SearchText);
|
||||
CollectionAssert.AreEqual(new[] { "alpha" }, VisibleTitles(board));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task WritesRefreshWithTheLastSuccessfulExpressionNotTheBoxText()
|
||||
{
|
||||
using var fixture = new Fixture();
|
||||
ColumnModel first = fixture.Repository.AddColumn("A", "");
|
||||
ColumnModel second = fixture.Repository.AddColumn("B", "");
|
||||
CardModel alpha = fixture.Repository.AddCard(first.Id, "alpha", "", []);
|
||||
fixture.Repository.AddCard(first.Id, "beta", "", []);
|
||||
BoardViewModel board = fixture.CreateBoard();
|
||||
board.SearchText = "alpha";
|
||||
await board.SearchCommand.ExecuteAsync(null);
|
||||
|
||||
board.SearchText = "beta";
|
||||
await MoveAsync(board, alpha.Id, second.Id);
|
||||
|
||||
CollectionAssert.AreEqual(new[] { "alpha" }, VisibleTitles(board));
|
||||
Assert.AreEqual(1, board.Columns[1].CardCount);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task BlankSearchAndClearShowEveryCard()
|
||||
{
|
||||
using var fixture = new Fixture();
|
||||
ColumnModel column = fixture.Repository.AddColumn("A", "");
|
||||
fixture.Repository.AddCard(column.Id, "alpha", "", []);
|
||||
fixture.Repository.AddCard(column.Id, "beta", "", []);
|
||||
BoardViewModel board = fixture.CreateBoard();
|
||||
|
||||
board.SearchText = "alpha";
|
||||
await board.SearchCommand.ExecuteAsync(null);
|
||||
board.SearchText = " ";
|
||||
await board.SearchCommand.ExecuteAsync(null);
|
||||
Assert.IsNull(board.ActiveFilter);
|
||||
CollectionAssert.AreEqual(new[] { "alpha", "beta" }, VisibleTitles(board));
|
||||
|
||||
board.SearchText = "alpha";
|
||||
await board.SearchCommand.ExecuteAsync(null);
|
||||
Assert.IsTrue(board.HasSearchText);
|
||||
board.ClearSearchCommand.Execute(null);
|
||||
|
||||
Assert.AreEqual("", board.SearchText);
|
||||
Assert.IsFalse(board.HasSearchText);
|
||||
Assert.IsNull(board.ActiveFilter);
|
||||
CollectionAssert.AreEqual(new[] { "alpha", "beta" }, VisibleTitles(board));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task DataWrittenIsRaisedForWritesButNotForSearchOrSort()
|
||||
{
|
||||
using var fixture = new Fixture();
|
||||
ColumnModel first = fixture.Repository.AddColumn("A", "");
|
||||
ColumnModel second = fixture.Repository.AddColumn("B", "");
|
||||
CardModel card = fixture.Repository.AddCard(first.Id, "x", "", []);
|
||||
BoardViewModel board = fixture.CreateBoard();
|
||||
int raised = 0;
|
||||
board.DataWritten += (_, _) => raised++;
|
||||
|
||||
board.SearchText = "x";
|
||||
await board.SearchCommand.ExecuteAsync(null);
|
||||
board.SelectedSort = board.SortOptions[1];
|
||||
Assert.AreEqual(0, raised);
|
||||
|
||||
await MoveAsync(board, card.Id, second.Id);
|
||||
Assert.AreEqual(1, raised);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Tags tab
|
||||
|
||||
[TestMethod]
|
||||
public void TagsListInIdOrderWithUsageCounts()
|
||||
{
|
||||
using var fixture = new Fixture();
|
||||
ColumnModel column = fixture.Repository.AddColumn("A", "");
|
||||
TagModel bug = fixture.Repository.AddTag("bug", new RgbColor(1, 2, 3), "Broken");
|
||||
TagModel unused = fixture.Repository.AddTag("unused", new RgbColor(4, 5, 6), "");
|
||||
fixture.Repository.AddCard(column.Id, "a", "", [bug.Id]);
|
||||
fixture.Repository.AddCard(column.Id, "b", "", [bug.Id]);
|
||||
|
||||
TagsViewModel tags = fixture.CreateTags();
|
||||
|
||||
CollectionAssert.AreEqual(new[] { bug.Id, unused.Id }, tags.Tags.Select(row => row.Tag.Id).ToArray());
|
||||
CollectionAssert.AreEqual(new long[] { 2, 0 }, tags.Tags.Select(row => row.UsageCount).ToArray());
|
||||
Assert.IsTrue(tags.Tags[0].HasDescription);
|
||||
Assert.AreEqual("#010203", tags.Tags[0].ColorText);
|
||||
Assert.IsFalse(tags.IsEmpty);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task NewTagIsWrittenAndAnnounced()
|
||||
{
|
||||
using var fixture = new Fixture();
|
||||
TagsViewModel tags = fixture.CreateTags();
|
||||
int changed = 0;
|
||||
tags.TagsChanged += (_, _) => changed++;
|
||||
fixture.Dialogs.Script = dialog =>
|
||||
{
|
||||
var editor = (TagEditorDialogViewModel)dialog;
|
||||
editor.Name = "ui";
|
||||
editor.PickSwatchCommand.Execute(TagColors.Palette[2].ToString());
|
||||
editor.Description = "Looks";
|
||||
editor.ConfirmCommand.Execute(null);
|
||||
return Task.CompletedTask;
|
||||
};
|
||||
|
||||
await tags.AddTagCommand.ExecuteAsync(null);
|
||||
|
||||
TagModel created = fixture.Repository.GetTags().Single();
|
||||
Assert.AreEqual("ui", created.Name);
|
||||
Assert.AreEqual(TagColors.Palette[2], created.Color);
|
||||
Assert.AreEqual("Looks", created.Description);
|
||||
Assert.AreEqual(1, tags.Tags.Count);
|
||||
Assert.AreEqual(1, changed);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task TagEditorKeepsTheDialogOpenOnDuplicateNameOrInvalidColor()
|
||||
{
|
||||
using var fixture = new Fixture();
|
||||
fixture.Repository.AddTag("Bug", new RgbColor(1, 2, 3), "");
|
||||
TagsViewModel tags = fixture.CreateTags();
|
||||
TagEditorDialogViewModel? editor = null;
|
||||
bool closed = false;
|
||||
fixture.Dialogs.Script = dialog =>
|
||||
{
|
||||
editor = (TagEditorDialogViewModel)dialog;
|
||||
editor.CloseRequested += (_, _) => closed = true;
|
||||
editor.Name = "bug";
|
||||
editor.ConfirmCommand.Execute(null);
|
||||
return Task.CompletedTask;
|
||||
};
|
||||
|
||||
await tags.AddTagCommand.ExecuteAsync(null);
|
||||
|
||||
Assert.IsNotNull(editor);
|
||||
Assert.IsTrue(editor.HasError);
|
||||
Assert.IsFalse(closed);
|
||||
Assert.AreEqual("bug", editor.Name);
|
||||
|
||||
editor.Name = "other";
|
||||
editor.Color = "red";
|
||||
editor.ConfirmCommand.Execute(null);
|
||||
Assert.AreEqual(Resources.Error_Tag_InvalidColor, editor.ErrorMessage);
|
||||
Assert.IsFalse(closed);
|
||||
Assert.AreEqual(1, fixture.Repository.GetTags().Count);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task EditingATagRenamesRecolorsAndDescribesIt()
|
||||
{
|
||||
using var fixture = new Fixture();
|
||||
TagModel tag = fixture.Repository.AddTag("bug", new RgbColor(1, 2, 3), "");
|
||||
TagsViewModel tags = fixture.CreateTags();
|
||||
fixture.Dialogs.Script = dialog =>
|
||||
{
|
||||
var editor = (TagEditorDialogViewModel)dialog;
|
||||
Assert.AreEqual("bug", editor.Name);
|
||||
Assert.AreEqual("#010203", editor.Color);
|
||||
editor.Name = "defect";
|
||||
editor.Color = "#ABCDEF";
|
||||
editor.Description = "Broken";
|
||||
editor.ConfirmCommand.Execute(null);
|
||||
return Task.CompletedTask;
|
||||
};
|
||||
|
||||
await tags.Tags[0].EditCommand.ExecuteAsync(null);
|
||||
|
||||
TagModel updated = fixture.Repository.GetTags().Single();
|
||||
Assert.AreEqual(tag.Id, updated.Id);
|
||||
Assert.AreEqual("defect", updated.Name);
|
||||
Assert.AreEqual(new RgbColor(0xab, 0xcd, 0xef), updated.Color);
|
||||
Assert.AreEqual("Broken", updated.Description);
|
||||
Assert.AreEqual("defect", tags.Tags[0].Badge.Name);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task DeletingATagAsksFirstAndKeepsTheCards()
|
||||
{
|
||||
using var fixture = new Fixture();
|
||||
ColumnModel column = fixture.Repository.AddColumn("A", "");
|
||||
TagModel bug = fixture.Repository.AddTag("bug", new RgbColor(1, 2, 3), "");
|
||||
CardModel card = fixture.Repository.AddCard(column.Id, "a", "", [bug.Id]);
|
||||
TagsViewModel tags = fixture.CreateTags();
|
||||
|
||||
fixture.Dialogs.Script = ScriptedDialogService.AnswerConfirmations(false);
|
||||
await tags.Tags[0].DeleteCommand.ExecuteAsync(null);
|
||||
Assert.AreEqual(1, fixture.Repository.GetTags().Count);
|
||||
|
||||
fixture.Dialogs.Script = ScriptedDialogService.AnswerConfirmations(true);
|
||||
await tags.Tags[0].DeleteCommand.ExecuteAsync(null);
|
||||
|
||||
Assert.AreEqual(0, fixture.Repository.GetTags().Count);
|
||||
Assert.IsTrue(tags.IsEmpty);
|
||||
CardModel kept = fixture.Repository.GetCard(card.Id)!;
|
||||
Assert.AreEqual(0, kept.Tags.Count);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task DeletingATagWithoutConfirmationShowsNoDialog()
|
||||
{
|
||||
using var fixture = new Fixture();
|
||||
fixture.Repository.AddTag("bug", new RgbColor(1, 2, 3), "");
|
||||
fixture.Config.Confirmations.DeleteTag = false;
|
||||
TagsViewModel tags = fixture.CreateTags();
|
||||
|
||||
await tags.Tags[0].DeleteCommand.ExecuteAsync(null);
|
||||
|
||||
Assert.AreEqual(0, fixture.Dialogs.Shown.Count);
|
||||
Assert.AreEqual(0, fixture.Repository.GetTags().Count);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Workspace wiring and export
|
||||
|
||||
[TestMethod]
|
||||
public async Task TagWritesRefreshTheBoardAndBoardWritesRefreshTheTags()
|
||||
{
|
||||
using var fixture = new Fixture();
|
||||
ColumnModel first = fixture.Repository.AddColumn("A", "");
|
||||
ColumnModel second = fixture.Repository.AddColumn("B", "");
|
||||
TagModel bug = fixture.Repository.AddTag("bug", new RgbColor(1, 2, 3), "");
|
||||
CardModel card = fixture.Repository.AddCard(first.Id, "a", "", [bug.Id]);
|
||||
WorkspaceViewModel workspace = fixture.CreateWorkspace();
|
||||
|
||||
// A filtered board drops the card once the tag is gone.
|
||||
workspace.Board.SearchText = "tag:bug";
|
||||
await workspace.Board.SearchCommand.ExecuteAsync(null);
|
||||
fixture.Dialogs.Script = ScriptedDialogService.AnswerConfirmations(true);
|
||||
await workspace.Tags.Tags[0].DeleteCommand.ExecuteAsync(null);
|
||||
Assert.AreEqual(0, workspace.Board.Columns.Sum(column => column.CardCount));
|
||||
|
||||
// Re-tag through the repository, then a board write updates the usage count.
|
||||
workspace.Board.ClearSearchCommand.Execute(null);
|
||||
TagModel ui = fixture.Repository.AddTag("ui", new RgbColor(4, 5, 6), "");
|
||||
fixture.Repository.UpdateCard(card.Id, "a", "", [ui.Id]);
|
||||
Assert.AreEqual(0, workspace.Tags.Tags.Count);
|
||||
await MoveAsync(workspace.Board, card.Id, second.Id);
|
||||
Assert.AreEqual(1, workspace.Tags.Tags.Single().UsageCount);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task ExportWritesTheWholeWorkspaceIgnoringTheSearch()
|
||||
{
|
||||
using var fixture = new Fixture();
|
||||
ColumnModel column = fixture.Repository.AddColumn("A", "");
|
||||
fixture.Repository.AddCard(column.Id, "alpha", "", []);
|
||||
fixture.Repository.AddCard(column.Id, "beta", "", []);
|
||||
WorkspaceViewModel workspace = fixture.CreateWorkspace();
|
||||
workspace.Board.SearchText = "alpha";
|
||||
await workspace.Board.SearchCommand.ExecuteAsync(null);
|
||||
|
||||
string path = Path.Combine(fixture.Directory.FullPath, "out.md");
|
||||
fixture.Dialogs.SaveFilePath = path;
|
||||
await workspace.ExportCommand.ExecuteAsync(null);
|
||||
|
||||
string suggested = fixture.Dialogs.SuggestedFileNames.Single();
|
||||
StringAssert.StartsWith(suggested, workspace.WorkspaceName);
|
||||
StringAssert.EndsWith(suggested, ".md");
|
||||
string markdown = File.ReadAllText(path);
|
||||
StringAssert.Contains(markdown, "alpha");
|
||||
StringAssert.Contains(markdown, "beta");
|
||||
byte[] bytes = File.ReadAllBytes(path);
|
||||
Assert.AreNotEqual(0xEF, bytes[0], "The export must not start with a UTF-8 BOM.");
|
||||
Assert.AreEqual(0, fixture.Dialogs.Shown.Count);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task CancelledExportWritesNothing()
|
||||
{
|
||||
using var fixture = new Fixture();
|
||||
WorkspaceViewModel workspace = fixture.CreateWorkspace();
|
||||
fixture.Dialogs.SaveFilePath = null;
|
||||
|
||||
await workspace.ExportCommand.ExecuteAsync(null);
|
||||
|
||||
Assert.AreEqual(1, fixture.Dialogs.SuggestedFileNames.Count);
|
||||
Assert.AreEqual(0, fixture.Dialogs.Shown.Count);
|
||||
Assert.AreEqual(0, System.IO.Directory.GetFiles(fixture.Directory.FullPath, "*.md").Length);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task ExportWriteFailureIsReportedInAMessageDialog()
|
||||
{
|
||||
using var fixture = new Fixture();
|
||||
WorkspaceViewModel workspace = fixture.CreateWorkspace();
|
||||
fixture.Dialogs.SaveFilePath = Path.Combine(fixture.Directory.FullPath, "missing-folder", "out.md");
|
||||
|
||||
await workspace.ExportCommand.ExecuteAsync(null);
|
||||
|
||||
var message = (MessageDialogViewModel)fixture.Dialogs.Shown.Single();
|
||||
Assert.AreEqual(Resources.Export_Failed_Title, message.Title);
|
||||
Assert.IsTrue(message.HasDetails);
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
@@ -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>
|
||||
|
||||
@@ -26,10 +26,20 @@
|
||||
<ResourceDictionary x:Key="Light">
|
||||
<SolidColorBrush x:Key="TopBarBackgroundBrush" Color="#F6F7F9"/>
|
||||
<SolidColorBrush x:Key="TopBarBorderBrush" Color="#E2E4EA"/>
|
||||
<SolidColorBrush x:Key="PanelBorderBrush" Color="#E2E4EA"/>
|
||||
<SolidColorBrush x:Key="ColumnBackgroundBrush" Color="#F3F4F7"/>
|
||||
<SolidColorBrush x:Key="CardBackgroundBrush" Color="#FFFFFF"/>
|
||||
<SolidColorBrush x:Key="CardForegroundBrush" Color="#1C1F23"/>
|
||||
<SolidColorBrush x:Key="ErrorTextBrush" Color="#D52515"/>
|
||||
</ResourceDictionary>
|
||||
<ResourceDictionary x:Key="Dark">
|
||||
<SolidColorBrush x:Key="TopBarBackgroundBrush" Color="#1C1E24"/>
|
||||
<SolidColorBrush x:Key="TopBarBorderBrush" Color="#2C2F37"/>
|
||||
<SolidColorBrush x:Key="PanelBorderBrush" Color="#33363F"/>
|
||||
<SolidColorBrush x:Key="ColumnBackgroundBrush" Color="#1A1C21"/>
|
||||
<SolidColorBrush x:Key="CardBackgroundBrush" Color="#25282F"/>
|
||||
<SolidColorBrush x:Key="CardForegroundBrush" Color="#E6E8EC"/>
|
||||
<SolidColorBrush x:Key="ErrorTextBrush" Color="#FC725A"/>
|
||||
</ResourceDictionary>
|
||||
</ResourceDictionary.ThemeDictionaries>
|
||||
</ResourceDictionary>
|
||||
|
||||
+19
-9
@@ -26,6 +26,12 @@ public partial class App : Application
|
||||
/// </summary>
|
||||
public static string StartupLanguage { get; private set; } = AppConfig.DefaultLanguage;
|
||||
|
||||
/// <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);
|
||||
@@ -43,20 +49,24 @@ public partial class App : Application
|
||||
CultureInfo culture = ResolveCulture(Services.Config.Language);
|
||||
StartupLanguage = Services.Config.Language;
|
||||
Resx.Culture = culture;
|
||||
ApplyTheme(Services.Config.Theme);
|
||||
|
||||
var viewModel = new MainWindowViewModel(Services, desktop.Args ?? []);
|
||||
desktop.MainWindow = new MainWindow
|
||||
{
|
||||
DataContext = viewModel,
|
||||
|
||||
// RTL detection drives the whole window flow direction; the two
|
||||
// RTL detection drives the flow direction of every window; the two
|
||||
// supported languages are LTR, but the infrastructure stays in
|
||||
// place for future languages.
|
||||
FlowDirection = culture.TextInfo.IsRightToLeft
|
||||
UiFlowDirection = culture.TextInfo.IsRightToLeft
|
||||
? FlowDirection.RightToLeft
|
||||
: FlowDirection.LeftToRight,
|
||||
: FlowDirection.LeftToRight;
|
||||
ApplyTheme(Services.Config.Theme);
|
||||
|
||||
var dialogs = new DialogService();
|
||||
var viewModel = new MainWindowViewModel(Services, dialogs, desktop.Args ?? []);
|
||||
var mainWindow = new MainWindow
|
||||
{
|
||||
DataContext = viewModel,
|
||||
FlowDirection = UiFlowDirection,
|
||||
};
|
||||
dialogs.Attach(mainWindow);
|
||||
desktop.MainWindow = mainWindow;
|
||||
}
|
||||
|
||||
base.OnFrameworkInitializationCompleted();
|
||||
|
||||
@@ -70,6 +70,27 @@
|
||||
<data name="Error_LockConflict_Message" xml:space="preserve">
|
||||
<value>The workspace is already open in another instance: {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_AccessDenied" xml:space="preserve">
|
||||
<value>Access to the workspace was denied: {0}</value>
|
||||
</data>
|
||||
<data name="Error_OpenFailed_Io" xml:space="preserve">
|
||||
<value>A file system error occurred while opening the workspace: {0}</value>
|
||||
</data>
|
||||
<data name="Error_OpenFailed_Generic" xml:space="preserve">
|
||||
<value>An unexpected error occurred while opening the workspace: {0}</value>
|
||||
</data>
|
||||
<data name="Error_OpenFailed_Details" xml:space="preserve">
|
||||
<value>Details</value>
|
||||
</data>
|
||||
<data name="Settings_Title" xml:space="preserve">
|
||||
<value>Settings</value>
|
||||
</data>
|
||||
@@ -142,9 +163,6 @@
|
||||
<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 +184,208 @@
|
||||
<data name="Export_TagsTableHeader" xml:space="preserve">
|
||||
<value>| Name | Color | Description | Usage |</value>
|
||||
</data>
|
||||
<data name="Common_Delete" xml:space="preserve">
|
||||
<value>Delete</value>
|
||||
</data>
|
||||
<data name="Common_Discard" xml:space="preserve">
|
||||
<value>Discard</value>
|
||||
</data>
|
||||
<data name="Common_TimePattern" xml:space="preserve">
|
||||
<value>yyyy-MM-dd HH:mm</value>
|
||||
</data>
|
||||
<data name="Board_AddColumn" xml:space="preserve">
|
||||
<value>New column</value>
|
||||
</data>
|
||||
<data name="Board_ColumnWidth" xml:space="preserve">
|
||||
<value>Column width</value>
|
||||
</data>
|
||||
<data name="Board_Sort" xml:space="preserve">
|
||||
<value>Card order</value>
|
||||
</data>
|
||||
<data name="Board_AddCard" xml:space="preserve">
|
||||
<value>New card</value>
|
||||
</data>
|
||||
<data name="Sort_Id" xml:space="preserve">
|
||||
<value>By id</value>
|
||||
</data>
|
||||
<data name="Sort_UpdatedAt" xml:space="preserve">
|
||||
<value>Recently modified</value>
|
||||
</data>
|
||||
<data name="Sort_Title" xml:space="preserve">
|
||||
<value>By title</value>
|
||||
</data>
|
||||
<data name="Menu_More" xml:space="preserve">
|
||||
<value>More</value>
|
||||
</data>
|
||||
<data name="Menu_Edit" xml:space="preserve">
|
||||
<value>Edit</value>
|
||||
</data>
|
||||
<data name="Menu_Delete" xml:space="preserve">
|
||||
<value>Delete</value>
|
||||
</data>
|
||||
<data name="Menu_MoveTo" xml:space="preserve">
|
||||
<value>Move to column</value>
|
||||
</data>
|
||||
<data name="Field_Title" xml:space="preserve">
|
||||
<value>Title</value>
|
||||
</data>
|
||||
<data name="Field_Description" xml:space="preserve">
|
||||
<value>Description</value>
|
||||
</data>
|
||||
<data name="Field_Content" xml:space="preserve">
|
||||
<value>Content</value>
|
||||
</data>
|
||||
<data name="Field_Tags" xml:space="preserve">
|
||||
<value>Tags</value>
|
||||
</data>
|
||||
<data name="Field_Name" xml:space="preserve">
|
||||
<value>Name</value>
|
||||
</data>
|
||||
<data name="Field_Color" xml:space="preserve">
|
||||
<value>#RRGGBB</value>
|
||||
</data>
|
||||
<data name="ColumnEditor_TitleNew" xml:space="preserve">
|
||||
<value>New column</value>
|
||||
</data>
|
||||
<data name="ColumnEditor_TitleEdit" xml:space="preserve">
|
||||
<value>Edit column</value>
|
||||
</data>
|
||||
<data name="ColumnWidth_Title" xml:space="preserve">
|
||||
<value>Column width</value>
|
||||
</data>
|
||||
<data name="ColumnWidth_Narrow" xml:space="preserve">
|
||||
<value>Narrow ({0} px)</value>
|
||||
</data>
|
||||
<data name="ColumnWidth_Standard" xml:space="preserve">
|
||||
<value>Standard ({0} px)</value>
|
||||
</data>
|
||||
<data name="ColumnWidth_Wide" xml:space="preserve">
|
||||
<value>Wide ({0} px)</value>
|
||||
</data>
|
||||
<data name="ColumnWidth_Custom" xml:space="preserve">
|
||||
<value>Custom</value>
|
||||
</data>
|
||||
<data name="ColumnWidth_Range" xml:space="preserve">
|
||||
<value>{0}–{1} px</value>
|
||||
</data>
|
||||
<data name="CardEditor_TitleNew" xml:space="preserve">
|
||||
<value>New card</value>
|
||||
</data>
|
||||
<data name="CardEditor_TitleEdit" xml:space="preserve">
|
||||
<value>Edit card</value>
|
||||
</data>
|
||||
<data name="CardEditor_TitleWatermark" xml:space="preserve">
|
||||
<value>No title</value>
|
||||
</data>
|
||||
<data name="CardEditor_Created" xml:space="preserve">
|
||||
<value>Created {0}</value>
|
||||
</data>
|
||||
<data name="CardEditor_Modified" xml:space="preserve">
|
||||
<value>Modified {0}</value>
|
||||
</data>
|
||||
<data name="CardEditor_AddTag" xml:space="preserve">
|
||||
<value>Add tag</value>
|
||||
</data>
|
||||
<data name="CardEditor_RemoveTag" xml:space="preserve">
|
||||
<value>Remove tag</value>
|
||||
</data>
|
||||
<data name="TagPicker_Title" xml:space="preserve">
|
||||
<value>Add tag</value>
|
||||
</data>
|
||||
<data name="TagPicker_FilterWatermark" xml:space="preserve">
|
||||
<value>Filter tags</value>
|
||||
</data>
|
||||
<data name="TagPicker_NoMatches" xml:space="preserve">
|
||||
<value>No matching tags</value>
|
||||
</data>
|
||||
<data name="TagPicker_NewTag" xml:space="preserve">
|
||||
<value>New tag</value>
|
||||
</data>
|
||||
<data name="TagPicker_Create" xml:space="preserve">
|
||||
<value>Create and add</value>
|
||||
</data>
|
||||
<data name="Confirm_Title" xml:space="preserve">
|
||||
<value>Confirm</value>
|
||||
</data>
|
||||
<data name="Confirm_DeleteCard" xml:space="preserve">
|
||||
<value>Delete card "{0}"?</value>
|
||||
</data>
|
||||
<data name="Confirm_DeleteColumn" xml:space="preserve">
|
||||
<value>Delete column "{0}" and its {1} card(s)?</value>
|
||||
</data>
|
||||
<data name="Confirm_DiscardEdit" xml:space="preserve">
|
||||
<value>Discard the unsaved changes?</value>
|
||||
</data>
|
||||
<data name="Error_Column_TitleRequired" xml:space="preserve">
|
||||
<value>The column title is required.</value>
|
||||
</data>
|
||||
<data name="Error_Column_Duplicate" xml:space="preserve">
|
||||
<value>A column named "{0}" already exists (names are case-insensitive).</value>
|
||||
</data>
|
||||
<data name="Error_Tag_NameRequired" xml:space="preserve">
|
||||
<value>The tag name is required.</value>
|
||||
</data>
|
||||
<data name="Error_Tag_Duplicate" xml:space="preserve">
|
||||
<value>A tag named "{0}" already exists (names are case-insensitive).</value>
|
||||
</data>
|
||||
<data name="Error_Tag_InvalidColor" xml:space="preserve">
|
||||
<value>The color must be written as #RRGGBB.</value>
|
||||
</data>
|
||||
<data name="Error_SaveFailed" xml:space="preserve">
|
||||
<value>Saving failed: {0}</value>
|
||||
</data>
|
||||
<data name="Error_Operation_Title" xml:space="preserve">
|
||||
<value>Operation failed</value>
|
||||
</data>
|
||||
<data name="Error_Operation_Message" xml:space="preserve">
|
||||
<value>The change could not be written to the workspace. The board shows the stored state.</value>
|
||||
</data>
|
||||
<data name="TagEditor_TitleNew" xml:space="preserve">
|
||||
<value>New tag</value>
|
||||
</data>
|
||||
<data name="TagEditor_TitleEdit" xml:space="preserve">
|
||||
<value>Edit tag</value>
|
||||
</data>
|
||||
<data name="TagEditor_ColorLabel" xml:space="preserve">
|
||||
<value>Color</value>
|
||||
</data>
|
||||
<data name="Tags_AddTag" xml:space="preserve">
|
||||
<value>New tag</value>
|
||||
</data>
|
||||
<data name="Tags_Summary" xml:space="preserve">
|
||||
<value>{0} tag(s)</value>
|
||||
</data>
|
||||
<data name="Tags_UsageCount" xml:space="preserve">
|
||||
<value>{0} card(s)</value>
|
||||
</data>
|
||||
<data name="Tags_Empty" xml:space="preserve">
|
||||
<value>No tags yet.</value>
|
||||
</data>
|
||||
<data name="Confirm_DeleteTag" xml:space="preserve">
|
||||
<value>Delete tag "{0}"? It will be removed from {1} card(s).</value>
|
||||
</data>
|
||||
<data name="Board_SearchWatermark" xml:space="preserve">
|
||||
<value>Search, e.g. tag:bug OR title:login</value>
|
||||
</data>
|
||||
<data name="Board_Search" xml:space="preserve">
|
||||
<value>Search</value>
|
||||
</data>
|
||||
<data name="Board_ClearSearch" xml:space="preserve">
|
||||
<value>Clear</value>
|
||||
</data>
|
||||
<data name="Search_Error_Title" xml:space="preserve">
|
||||
<value>Invalid search</value>
|
||||
</data>
|
||||
<data name="Search_Error_Message" xml:space="preserve">
|
||||
<value>The query expression is invalid. Details: {0}</value>
|
||||
</data>
|
||||
<data name="Export_FileTypeMarkdown" xml:space="preserve">
|
||||
<value>Markdown document</value>
|
||||
</data>
|
||||
<data name="Export_Failed_Title" xml:space="preserve">
|
||||
<value>Export failed</value>
|
||||
</data>
|
||||
<data name="Export_Failed_Message" xml:space="preserve">
|
||||
<value>The export file could not be written.</value>
|
||||
</data>
|
||||
</root>
|
||||
@@ -70,6 +70,27 @@
|
||||
<data name="Error_LockConflict_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_AccessDenied" xml:space="preserve">
|
||||
<value>没有访问该工作区的权限:{0}</value>
|
||||
</data>
|
||||
<data name="Error_OpenFailed_Io" xml:space="preserve">
|
||||
<value>打开工作区时发生文件系统错误:{0}</value>
|
||||
</data>
|
||||
<data name="Error_OpenFailed_Generic" xml:space="preserve">
|
||||
<value>打开工作区时发生意外错误:{0}</value>
|
||||
</data>
|
||||
<data name="Error_OpenFailed_Details" xml:space="preserve">
|
||||
<value>详细信息</value>
|
||||
</data>
|
||||
<data name="Settings_Title" xml:space="preserve">
|
||||
<value>设置</value>
|
||||
</data>
|
||||
@@ -142,9 +163,6 @@
|
||||
<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 +184,208 @@
|
||||
<data name="Export_TagsTableHeader" xml:space="preserve">
|
||||
<value>| 名称 | 颜色 | 描述 | 使用数 |</value>
|
||||
</data>
|
||||
<data name="Common_Delete" xml:space="preserve">
|
||||
<value>删除</value>
|
||||
</data>
|
||||
<data name="Common_Discard" xml:space="preserve">
|
||||
<value>丢弃</value>
|
||||
</data>
|
||||
<data name="Common_TimePattern" xml:space="preserve">
|
||||
<value>yyyy年M月d日 HH:mm</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_Sort" xml:space="preserve">
|
||||
<value>卡片排序</value>
|
||||
</data>
|
||||
<data name="Board_AddCard" xml:space="preserve">
|
||||
<value>新建卡片</value>
|
||||
</data>
|
||||
<data name="Sort_Id" xml:space="preserve">
|
||||
<value>按 ID</value>
|
||||
</data>
|
||||
<data name="Sort_UpdatedAt" xml:space="preserve">
|
||||
<value>最近修改</value>
|
||||
</data>
|
||||
<data name="Sort_Title" xml:space="preserve">
|
||||
<value>按标题</value>
|
||||
</data>
|
||||
<data name="Menu_More" xml:space="preserve">
|
||||
<value>更多</value>
|
||||
</data>
|
||||
<data name="Menu_Edit" xml:space="preserve">
|
||||
<value>编辑</value>
|
||||
</data>
|
||||
<data name="Menu_Delete" xml:space="preserve">
|
||||
<value>删除</value>
|
||||
</data>
|
||||
<data name="Menu_MoveTo" xml:space="preserve">
|
||||
<value>移动到列</value>
|
||||
</data>
|
||||
<data name="Field_Title" xml:space="preserve">
|
||||
<value>标题</value>
|
||||
</data>
|
||||
<data name="Field_Description" xml:space="preserve">
|
||||
<value>描述</value>
|
||||
</data>
|
||||
<data name="Field_Content" xml:space="preserve">
|
||||
<value>内容</value>
|
||||
</data>
|
||||
<data name="Field_Tags" xml:space="preserve">
|
||||
<value>标签</value>
|
||||
</data>
|
||||
<data name="Field_Name" xml:space="preserve">
|
||||
<value>名称</value>
|
||||
</data>
|
||||
<data name="Field_Color" xml:space="preserve">
|
||||
<value>#RRGGBB</value>
|
||||
</data>
|
||||
<data name="ColumnEditor_TitleNew" xml:space="preserve">
|
||||
<value>新建列</value>
|
||||
</data>
|
||||
<data name="ColumnEditor_TitleEdit" xml:space="preserve">
|
||||
<value>编辑列</value>
|
||||
</data>
|
||||
<data name="ColumnWidth_Title" xml:space="preserve">
|
||||
<value>列宽</value>
|
||||
</data>
|
||||
<data name="ColumnWidth_Narrow" xml:space="preserve">
|
||||
<value>窄({0} px)</value>
|
||||
</data>
|
||||
<data name="ColumnWidth_Standard" xml:space="preserve">
|
||||
<value>标准({0} px)</value>
|
||||
</data>
|
||||
<data name="ColumnWidth_Wide" xml:space="preserve">
|
||||
<value>宽({0} px)</value>
|
||||
</data>
|
||||
<data name="ColumnWidth_Custom" xml:space="preserve">
|
||||
<value>自定义</value>
|
||||
</data>
|
||||
<data name="ColumnWidth_Range" xml:space="preserve">
|
||||
<value>{0}–{1} px</value>
|
||||
</data>
|
||||
<data name="CardEditor_TitleNew" xml:space="preserve">
|
||||
<value>新建卡片</value>
|
||||
</data>
|
||||
<data name="CardEditor_TitleEdit" xml:space="preserve">
|
||||
<value>编辑卡片</value>
|
||||
</data>
|
||||
<data name="CardEditor_TitleWatermark" xml:space="preserve">
|
||||
<value>无标题</value>
|
||||
</data>
|
||||
<data name="CardEditor_Created" xml:space="preserve">
|
||||
<value>创建于 {0}</value>
|
||||
</data>
|
||||
<data name="CardEditor_Modified" xml:space="preserve">
|
||||
<value>修改于 {0}</value>
|
||||
</data>
|
||||
<data name="CardEditor_AddTag" xml:space="preserve">
|
||||
<value>添加标签</value>
|
||||
</data>
|
||||
<data name="CardEditor_RemoveTag" xml:space="preserve">
|
||||
<value>移除标签</value>
|
||||
</data>
|
||||
<data name="TagPicker_Title" xml:space="preserve">
|
||||
<value>添加标签</value>
|
||||
</data>
|
||||
<data name="TagPicker_FilterWatermark" xml:space="preserve">
|
||||
<value>筛选标签</value>
|
||||
</data>
|
||||
<data name="TagPicker_NoMatches" xml:space="preserve">
|
||||
<value>没有匹配的标签</value>
|
||||
</data>
|
||||
<data name="TagPicker_NewTag" xml:space="preserve">
|
||||
<value>新建标签</value>
|
||||
</data>
|
||||
<data name="TagPicker_Create" xml:space="preserve">
|
||||
<value>新建并添加</value>
|
||||
</data>
|
||||
<data name="Confirm_Title" xml:space="preserve">
|
||||
<value>确认</value>
|
||||
</data>
|
||||
<data name="Confirm_DeleteCard" xml:space="preserve">
|
||||
<value>删除卡片“{0}”?</value>
|
||||
</data>
|
||||
<data name="Confirm_DeleteColumn" xml:space="preserve">
|
||||
<value>删除列“{0}”及其中的 {1} 张卡片?</value>
|
||||
</data>
|
||||
<data name="Confirm_DiscardEdit" xml:space="preserve">
|
||||
<value>放弃未保存的更改?</value>
|
||||
</data>
|
||||
<data name="Error_Column_TitleRequired" xml:space="preserve">
|
||||
<value>列标题不能为空。</value>
|
||||
</data>
|
||||
<data name="Error_Column_Duplicate" xml:space="preserve">
|
||||
<value>已存在名为“{0}”的列(名称不区分大小写)。</value>
|
||||
</data>
|
||||
<data name="Error_Tag_NameRequired" xml:space="preserve">
|
||||
<value>标签名称不能为空。</value>
|
||||
</data>
|
||||
<data name="Error_Tag_Duplicate" xml:space="preserve">
|
||||
<value>已存在名为“{0}”的标签(名称不区分大小写)。</value>
|
||||
</data>
|
||||
<data name="Error_Tag_InvalidColor" xml:space="preserve">
|
||||
<value>颜色须为 #RRGGBB 格式。</value>
|
||||
</data>
|
||||
<data name="Error_SaveFailed" xml:space="preserve">
|
||||
<value>保存失败:{0}</value>
|
||||
</data>
|
||||
<data name="Error_Operation_Title" xml:space="preserve">
|
||||
<value>操作失败</value>
|
||||
</data>
|
||||
<data name="Error_Operation_Message" xml:space="preserve">
|
||||
<value>更改未能写入工作区,看板显示的是已保存的状态。</value>
|
||||
</data>
|
||||
<data name="TagEditor_TitleNew" xml:space="preserve">
|
||||
<value>新建标签</value>
|
||||
</data>
|
||||
<data name="TagEditor_TitleEdit" xml:space="preserve">
|
||||
<value>编辑标签</value>
|
||||
</data>
|
||||
<data name="TagEditor_ColorLabel" xml:space="preserve">
|
||||
<value>颜色</value>
|
||||
</data>
|
||||
<data name="Tags_AddTag" xml:space="preserve">
|
||||
<value>新建标签</value>
|
||||
</data>
|
||||
<data name="Tags_Summary" xml:space="preserve">
|
||||
<value>共 {0} 个标签</value>
|
||||
</data>
|
||||
<data name="Tags_UsageCount" xml:space="preserve">
|
||||
<value>{0} 张卡片</value>
|
||||
</data>
|
||||
<data name="Tags_Empty" xml:space="preserve">
|
||||
<value>还没有标签。</value>
|
||||
</data>
|
||||
<data name="Confirm_DeleteTag" xml:space="preserve">
|
||||
<value>删除标签“{0}”?将从 {1} 张卡片移除该标签。</value>
|
||||
</data>
|
||||
<data name="Board_SearchWatermark" xml:space="preserve">
|
||||
<value>搜索,例如 tag:bug OR title:登录</value>
|
||||
</data>
|
||||
<data name="Board_Search" xml:space="preserve">
|
||||
<value>搜索</value>
|
||||
</data>
|
||||
<data name="Board_ClearSearch" xml:space="preserve">
|
||||
<value>清空</value>
|
||||
</data>
|
||||
<data name="Search_Error_Title" xml:space="preserve">
|
||||
<value>搜索表达式错误</value>
|
||||
</data>
|
||||
<data name="Search_Error_Message" xml:space="preserve">
|
||||
<value>查询表达式有误,详情:{0}</value>
|
||||
</data>
|
||||
<data name="Export_FileTypeMarkdown" xml:space="preserve">
|
||||
<value>Markdown 文档</value>
|
||||
</data>
|
||||
<data name="Export_Failed_Title" xml:space="preserve">
|
||||
<value>导出失败</value>
|
||||
</data>
|
||||
<data name="Export_Failed_Message" xml:space="preserve">
|
||||
<value>无法写入导出文件。</value>
|
||||
</data>
|
||||
</root>
|
||||
@@ -6,10 +6,12 @@ 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 time format come from the ResX resources in the current
|
||||
/// UI language; every timestamp (export time and card created/modified times)
|
||||
/// uses that one per-language pattern. Card bodies and column descriptions are
|
||||
/// emitted verbatim; tag names become inline code with a long enough backtick
|
||||
/// fence; tag table cells escape '|' and turn line breaks into <br>. The
|
||||
/// output is meant for reading only — there is no re-import.
|
||||
/// </summary>
|
||||
public static class MarkdownExporter
|
||||
{
|
||||
@@ -17,7 +19,7 @@ public static class MarkdownExporter
|
||||
/// Renders the whole board to Markdown.
|
||||
/// </summary>
|
||||
/// <param name="workspaceName">Workspace display name (the folder name).</param>
|
||||
/// <param name="columns">All columns, in id order; empty columns are kept.</param>
|
||||
/// <param name="columns">All columns; emitted in id order, empty columns kept.</param>
|
||||
/// <param name="cards">All cards; grouped by column, id order within a column.</param>
|
||||
/// <param name="tags">All tags with usage counts, in id order.</param>
|
||||
/// <param name="exportedAt">Export moment in local time.</param>
|
||||
@@ -39,14 +41,16 @@ public static class MarkdownExporter
|
||||
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)
|
||||
// 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).ToArray();
|
||||
IReadOnlyList<CardModel> cardsInColumn =
|
||||
cards.Where(card => card.ColumnId == column.Id).OrderBy(card => card.Id).ToArray();
|
||||
builder.AppendLine(string.Format(culture, Resources.Export_ColumnHeading, column.Title, cardsInColumn.Count));
|
||||
if (column.Description.Length > 0)
|
||||
{
|
||||
builder.AppendLine(SingleLine(column.Description));
|
||||
builder.AppendLine(column.Description);
|
||||
}
|
||||
builder.AppendLine();
|
||||
|
||||
@@ -93,12 +97,12 @@ public static class MarkdownExporter
|
||||
|
||||
if (card.Tags.Count > 0)
|
||||
{
|
||||
string names = string.Join(" ", card.Tags.Select(tag => $"`{tag.Name}`"));
|
||||
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();
|
||||
}
|
||||
@@ -125,11 +129,34 @@ public static class MarkdownExporter
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Formats a table cell: single line with escaped pipe characters.
|
||||
/// Formats a table cell: escaped 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) =>
|
||||
text.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.
|
||||
|
||||
@@ -5,8 +5,11 @@ 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.
|
||||
/// more than one argument, a blank argument, an argument starting with
|
||||
/// <c>-</c> (any option form, <c>--help</c> included) or a malformed path is
|
||||
/// rejected as an argument error. A relative path is resolved against the
|
||||
/// process's current directory; the path itself is not checked for existence
|
||||
/// here.
|
||||
/// </summary>
|
||||
public static class LaunchArguments
|
||||
{
|
||||
@@ -15,17 +18,25 @@ public static class LaunchArguments
|
||||
/// <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>
|
||||
/// <param name="folderPath">The absolute workspace path 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)
|
||||
{
|
||||
if (arguments.Count == 1 && !string.IsNullOrWhiteSpace(arguments[0]))
|
||||
{
|
||||
folderPath = arguments[0];
|
||||
return true;
|
||||
}
|
||||
|
||||
folderPath = null;
|
||||
if (arguments.Count != 1 || string.IsNullOrWhiteSpace(arguments[0]) || arguments[0].StartsWith('-'))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
folderPath = Path.GetFullPath(arguments[0]);
|
||||
return true;
|
||||
}
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
using System.Text;
|
||||
using YKanBan.Storage.AppData;
|
||||
|
||||
namespace YKanBan.Models;
|
||||
|
||||
/// <summary>
|
||||
/// Computes the in-column card display order for a <see cref="CardSortOption"/>.
|
||||
/// Columns are not affected: they always stay in id order. Every option falls
|
||||
/// back to id ascending as the final tie-breaker, so the order is total.
|
||||
/// </summary>
|
||||
public static class CardOrdering
|
||||
{
|
||||
/// <summary>
|
||||
/// Orders cards for display.
|
||||
/// </summary>
|
||||
/// <param name="cards">The cards to order, typically those of one column.</param>
|
||||
/// <param name="option">The selected sort option.</param>
|
||||
/// <returns>The cards in display order.</returns>
|
||||
public static IReadOnlyList<CardModel> Sort(IEnumerable<CardModel> cards, CardSortOption option)
|
||||
{
|
||||
IOrderedEnumerable<CardModel> ordered = option switch
|
||||
{
|
||||
CardSortOption.Id => cards.OrderBy(card => card.Id),
|
||||
|
||||
// Most recently modified first.
|
||||
CardSortOption.UpdatedAt => cards.OrderByDescending(card => card.UpdatedAt).ThenBy(card => card.Id),
|
||||
|
||||
// Code point order, matching SQLite's BINARY collation; the empty title sorts first.
|
||||
CardSortOption.Title => cards.OrderBy(card => card.Title, CodePointComparer.Instance).ThenBy(card => card.Id),
|
||||
|
||||
_ => throw new ArgumentOutOfRangeException(nameof(option), option, "Unknown card sort option."),
|
||||
};
|
||||
return ordered.ToList();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Compares strings by Unicode code points. Unlike ordinal UTF-16 comparison
|
||||
/// it orders supplementary characters after U+E000–U+FFFF, as BINARY does on UTF-8.
|
||||
/// </summary>
|
||||
private sealed class CodePointComparer : IComparer<string>
|
||||
{
|
||||
public static readonly CodePointComparer Instance = new();
|
||||
|
||||
public int Compare(string? x, string? y)
|
||||
{
|
||||
if (x is null || y is null)
|
||||
{
|
||||
return x is null ? (y is null ? 0 : -1) : 1;
|
||||
}
|
||||
|
||||
StringRuneEnumerator left = x.EnumerateRunes();
|
||||
StringRuneEnumerator right = y.EnumerateRunes();
|
||||
while (true)
|
||||
{
|
||||
bool hasLeft = left.MoveNext();
|
||||
bool hasRight = right.MoveNext();
|
||||
if (!hasLeft || !hasRight)
|
||||
{
|
||||
return hasLeft.CompareTo(hasRight);
|
||||
}
|
||||
|
||||
int result = left.Current.Value.CompareTo(right.Current.Value);
|
||||
if (result != 0)
|
||||
{
|
||||
return result;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -35,8 +35,8 @@ 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
|
||||
/// escapes, a bare backslash or an unknown escape is rejected, a backslash in a
|
||||
/// bare word is rejected, and an unterminated phrase is rejected. Any input not covered by the token rules
|
||||
/// is rejected rather than silently ignored.
|
||||
/// </summary>
|
||||
public static class SearchLexer
|
||||
@@ -62,9 +62,11 @@ 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())));
|
||||
|
||||
|
||||
@@ -6,8 +6,10 @@ 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
|
||||
@@ -131,55 +133,86 @@ public static class SearchQueryParser
|
||||
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}'.");
|
||||
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(text => TextAtom(kind, text));
|
||||
}
|
||||
|
||||
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>
|
||||
@@ -201,25 +234,6 @@ 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>
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
using YKanBan.Storage;
|
||||
|
||||
namespace YKanBan.Search;
|
||||
|
||||
/// <summary>
|
||||
@@ -10,10 +12,11 @@ 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
|
||||
{
|
||||
@@ -48,29 +51,28 @@ public static class SearchSqlCompiler
|
||||
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 '\\')";
|
||||
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 '\\'";
|
||||
string param = AddParameter(parameters, SqliteDatabase.Fold(field.Text));
|
||||
return Contains(column, param);
|
||||
}
|
||||
|
||||
case SearchNode.TagName tag:
|
||||
{
|
||||
string param = AddParameter(parameters, tag.Name);
|
||||
string param = AddParameter(parameters, SqliteDatabase.Fold(tag.Name));
|
||||
return "EXISTS (SELECT 1 FROM card_tags ct JOIN tags t ON t.id = ct.tag_id " +
|
||||
$"WHERE ct.card_id = c.id AND t.name COLLATE NOCASE = {param})";
|
||||
$"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})";
|
||||
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:
|
||||
@@ -98,10 +100,17 @@ public static class SearchSqlCompiler
|
||||
}
|
||||
|
||||
/// <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,7 +6,7 @@ namespace YKanBan.Services;
|
||||
/// <summary>
|
||||
/// Composition root for the whole process: owns the loaded configuration and
|
||||
/// the single open workspace session. The configuration is persisted once at
|
||||
/// shutdown; the session (lock plus connection) lives until disposal.
|
||||
/// shutdown, and only when this session changed it; the session (lock plus connection) lives until disposal.
|
||||
/// </summary>
|
||||
public sealed class AppServices : IDisposable
|
||||
{
|
||||
@@ -49,9 +49,9 @@ public sealed class AppServices : IDisposable
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Persists the configuration; called once at shutdown.
|
||||
/// Persists the configuration when this session changed a setting; called once at shutdown.
|
||||
/// </summary>
|
||||
public void SaveConfiguration() => ConfigStore.Save(Config);
|
||||
public void SaveConfiguration() => ConfigStore.SaveIfChanged(Config);
|
||||
|
||||
/// <summary>
|
||||
/// Releases the workspace session, if any.
|
||||
|
||||
@@ -13,10 +13,6 @@ public enum CardSortOption
|
||||
[EnumMember(Value = "id")]
|
||||
Id,
|
||||
|
||||
/// <summary>Creation time, oldest first.</summary>
|
||||
[EnumMember(Value = "created-at")]
|
||||
CreatedAt,
|
||||
|
||||
/// <summary>Last modification time, most recently modified first.</summary>
|
||||
[EnumMember(Value = "updated-at")]
|
||||
UpdatedAt,
|
||||
@@ -145,6 +141,26 @@ public sealed class AppConfig
|
||||
/// </summary>
|
||||
public const string DefaultLanguage = "en";
|
||||
|
||||
/// <summary>
|
||||
/// Simplified Chinese UI language code.
|
||||
/// </summary>
|
||||
public const string SimplifiedChineseLanguage = "zh-Hans";
|
||||
|
||||
/// <summary>
|
||||
/// Gets the supported UI language codes; any other stored value falls back to <see cref="DefaultLanguage"/>.
|
||||
/// </summary>
|
||||
public static IReadOnlyList<string> SupportedLanguages { get; } = [DefaultLanguage, SimplifiedChineseLanguage];
|
||||
|
||||
/// <summary>
|
||||
/// Smallest accepted custom column width in pixels.
|
||||
/// </summary>
|
||||
public const int MinColumnPixels = 160;
|
||||
|
||||
/// <summary>
|
||||
/// Largest accepted custom column width in pixels.
|
||||
/// </summary>
|
||||
public const int MaxColumnPixels = 720;
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the configuration format version of this file.
|
||||
/// </summary>
|
||||
|
||||
@@ -1,13 +1,17 @@
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json.Converters;
|
||||
using Newtonsoft.Json.Linq;
|
||||
|
||||
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.
|
||||
/// defaults; a file that is not a JSON object is backed up to app.json.bak and
|
||||
/// then defaults are used; an individual invalid field (unknown enum value or
|
||||
/// language, out-of-range width, wrong type) falls back to its own default while
|
||||
/// the other fields are kept. Saving happens only when the configuration differs
|
||||
/// from what was loaded, and writes the file directly (no atomic replace) —
|
||||
/// losing the last session's settings to a crash is an accepted trade-off.
|
||||
/// </summary>
|
||||
public sealed class AppConfigStore
|
||||
{
|
||||
@@ -16,10 +20,24 @@ public sealed class AppConfigStore
|
||||
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.
|
||||
Converters = { new StringEnumConverter { AllowIntegerValues = false } },
|
||||
};
|
||||
|
||||
private static readonly JsonSerializer FieldTolerantSerializer = JsonSerializer.Create(new JsonSerializerSettings
|
||||
{
|
||||
NullValueHandling = NullValueHandling.Ignore,
|
||||
Converters = { new StringEnumConverter { AllowIntegerValues = false } },
|
||||
|
||||
// The JSON text is already known to be well formed here, so every error is a
|
||||
// single member that fails to convert: skip it and keep that member's default.
|
||||
Error = (_, args) => args.ErrorContext.Handled = true,
|
||||
});
|
||||
|
||||
/// <summary>The serialized form of the configuration as last loaded or saved.</summary>
|
||||
private string _persistedSnapshot = Serialize(new AppConfig());
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a store bound to a specific app.json path.
|
||||
/// </summary>
|
||||
@@ -32,12 +50,57 @@ public sealed class AppConfigStore
|
||||
public string FilePath { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Loads the configuration. A missing file yields defaults; a corrupt file
|
||||
/// is backed up to app.json.bak and then defaults are used.
|
||||
/// Loads the configuration and records it as the persisted baseline for
|
||||
/// <see cref="SaveIfChanged"/>. A missing file yields defaults; a file that
|
||||
/// is not a JSON object is backed up to app.json.bak and then defaults are
|
||||
/// used; invalid fields fall back to their defaults individually.
|
||||
/// </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()
|
||||
{
|
||||
AppConfig config = Read();
|
||||
|
||||
// The baseline is the effective configuration, so field fallbacks alone never trigger a write.
|
||||
_persistedSnapshot = Serialize(config);
|
||||
return config;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writes the configuration only when it differs from the loaded or last
|
||||
/// saved one, i.e. when this session changed a setting.
|
||||
/// </summary>
|
||||
/// <param name="config">The live configuration.</param>
|
||||
/// <returns><see langword="true"/> when the file was written.</returns>
|
||||
public bool SaveIfChanged(AppConfig config)
|
||||
{
|
||||
string json = Serialize(config);
|
||||
if (json == _persistedSnapshot)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
Write(json);
|
||||
_persistedSnapshot = json;
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writes the configuration directly to disk (no atomic replace), unconditionally.
|
||||
/// </summary>
|
||||
/// <param name="config">The configuration to serialize.</param>
|
||||
public void Save(AppConfig config)
|
||||
{
|
||||
string json = Serialize(config);
|
||||
Write(json);
|
||||
_persistedSnapshot = json;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads and sanitizes the file.
|
||||
/// </summary>
|
||||
/// <returns>The effective configuration.</returns>
|
||||
private AppConfig Read()
|
||||
{
|
||||
// Missing file is a normal first-run state: run with defaults.
|
||||
if (!File.Exists(FilePath))
|
||||
@@ -46,42 +109,98 @@ public sealed class AppConfigStore
|
||||
}
|
||||
|
||||
string json = File.ReadAllText(FilePath);
|
||||
JToken root;
|
||||
try
|
||||
{
|
||||
// A JSON null literal deserializes to null; treat it like defaults.
|
||||
AppConfig? config = JsonConvert.DeserializeObject<AppConfig>(json, SerializerSettings);
|
||||
if (config is null)
|
||||
root = JToken.Parse(json);
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
return BackUpAndUseDefaults();
|
||||
}
|
||||
|
||||
// A JSON null literal carries no settings at all; treat it like a missing file.
|
||||
if (root.Type == JTokenType.Null)
|
||||
{
|
||||
return new AppConfig();
|
||||
}
|
||||
|
||||
// Well-formed JSON of the wrong shape has no field to keep: handle it like corrupt text.
|
||||
if (root is not JObject rootObject)
|
||||
{
|
||||
return BackUpAndUseDefaults();
|
||||
}
|
||||
|
||||
AppConfig config = rootObject.ToObject<AppConfig>(FieldTolerantSerializer) ?? new AppConfig();
|
||||
Sanitize(config);
|
||||
return config;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Keeps a copy of an unusable file for inspection, then continues with defaults.
|
||||
/// </summary>
|
||||
/// <returns>The default configuration.</returns>
|
||||
private AppConfig BackUpAndUseDefaults()
|
||||
{
|
||||
File.Copy(FilePath, FilePath + ".bak", overwrite: true);
|
||||
return new AppConfig();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Replaces every value that converted but is outside its domain with the field default.
|
||||
/// </summary>
|
||||
/// <param name="config">The freshly deserialized configuration.</param>
|
||||
private static void Sanitize(AppConfig config)
|
||||
{
|
||||
var defaults = new AppConfig();
|
||||
|
||||
// Older or hand-edited files may miss whole sections; each falls back to its defaults.
|
||||
config.Sort ??= new SortSettings();
|
||||
config.ColumnWidth ??= new ColumnWidthSettings();
|
||||
config.Confirmations ??= new ConfirmationSettings();
|
||||
return config;
|
||||
}
|
||||
catch (JsonException)
|
||||
|
||||
if (config.Language is null || !AppConfig.SupportedLanguages.Contains(config.Language, StringComparer.Ordinal))
|
||||
{
|
||||
// Corrupt: keep a copy for inspection, then continue with defaults.
|
||||
File.Copy(FilePath, FilePath + ".bak", overwrite: true);
|
||||
return new AppConfig();
|
||||
config.Language = defaults.Language;
|
||||
}
|
||||
if (!Enum.IsDefined(config.Theme))
|
||||
{
|
||||
config.Theme = defaults.Theme;
|
||||
}
|
||||
if (!Enum.IsDefined(config.Sort.Card))
|
||||
{
|
||||
config.Sort.Card = defaults.Sort.Card;
|
||||
}
|
||||
if (!Enum.IsDefined(config.ColumnWidth.Preset))
|
||||
{
|
||||
config.ColumnWidth.Preset = defaults.ColumnWidth.Preset;
|
||||
}
|
||||
if (config.ColumnWidth.CustomPixels is < AppConfig.MinColumnPixels or > AppConfig.MaxColumnPixels)
|
||||
{
|
||||
config.ColumnWidth.CustomPixels = defaults.ColumnWidth.CustomPixels;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writes the configuration directly to disk (no atomic replace).
|
||||
/// Writes the serialized configuration, creating the parent folder on demand.
|
||||
/// </summary>
|
||||
/// <param name="config">The configuration to serialize.</param>
|
||||
public void Save(AppConfig config)
|
||||
/// <param name="json">The serialized configuration.</param>
|
||||
private void Write(string json)
|
||||
{
|
||||
// Create the parent folder on demand; normally it already exists.
|
||||
// Normally the folder already exists.
|
||||
string? directory = Path.GetDirectoryName(FilePath);
|
||||
if (!string.IsNullOrEmpty(directory))
|
||||
{
|
||||
Directory.CreateDirectory(directory);
|
||||
}
|
||||
|
||||
File.WriteAllText(FilePath, JsonConvert.SerializeObject(config, SerializerSettings));
|
||||
File.WriteAllText(FilePath, json);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Serializes a configuration in the on-disk format.
|
||||
/// </summary>
|
||||
/// <param name="config">The configuration.</param>
|
||||
/// <returns>The JSON text.</returns>
|
||||
private static string Serialize(AppConfig config) => JsonConvert.SerializeObject(config, SerializerSettings);
|
||||
}
|
||||
@@ -5,10 +5,25 @@ namespace YKanBan.Storage;
|
||||
/// <summary>
|
||||
/// Shared SQLite plumbing for workspace databases: opens a connection with
|
||||
/// the mandated PRAGMA configuration (WAL journal, NORMAL synchronous mode,
|
||||
/// foreign keys on) and applies incremental <c>user_version</c> migrations.
|
||||
/// foreign keys on), registers the custom SQL functions and applies
|
||||
/// incremental <c>user_version</c> migrations.
|
||||
/// </summary>
|
||||
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.
|
||||
@@ -31,6 +46,7 @@ public static class SqliteDatabase
|
||||
try
|
||||
{
|
||||
ApplyPragmas(connection);
|
||||
RegisterFunctions(connection);
|
||||
ApplyMigrations(connection, migrations);
|
||||
return connection;
|
||||
}
|
||||
@@ -67,6 +83,18 @@ public static class SqliteDatabase
|
||||
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.
|
||||
|
||||
@@ -136,3 +136,69 @@ public sealed class SchemaVersionException : YKanBanException
|
||||
SupportedVersion = supportedVersion;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The entities whose name/title is constrained by the schema to be non-empty
|
||||
/// and table-unique.
|
||||
/// </summary>
|
||||
public enum NamedEntity
|
||||
{
|
||||
/// <summary>A board column (constraint on columns.title).</summary>
|
||||
Column,
|
||||
|
||||
/// <summary>A tag (constraint on tags.name).</summary>
|
||||
Tag,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Signals that a column title or tag name was empty, violating the schema's
|
||||
/// CHECK constraint. Nothing was written.
|
||||
/// </summary>
|
||||
public sealed class NameRequiredException : YKanBanException
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the entity whose name was empty.
|
||||
/// </summary>
|
||||
public NamedEntity Entity { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Initializes the exception for an empty name.
|
||||
/// </summary>
|
||||
/// <param name="entity">The entity whose name was empty.</param>
|
||||
/// <param name="innerException">The underlying constraint violation.</param>
|
||||
public NameRequiredException(NamedEntity entity, Exception innerException)
|
||||
: base($"The {entity.ToString().ToLowerInvariant()} name must not be empty.", innerException)
|
||||
{
|
||||
Entity = entity;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Signals that a column title or tag name already exists (compared with ASCII
|
||||
/// case folding), violating the schema's UNIQUE constraint. Nothing was written.
|
||||
/// </summary>
|
||||
public sealed class DuplicateNameException : YKanBanException
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the entity whose name collided.
|
||||
/// </summary>
|
||||
public NamedEntity Entity { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the rejected name.
|
||||
/// </summary>
|
||||
public string Name { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Initializes the exception for a name collision.
|
||||
/// </summary>
|
||||
/// <param name="entity">The entity whose name collided.</param>
|
||||
/// <param name="name">The rejected name.</param>
|
||||
/// <param name="innerException">The underlying constraint violation.</param>
|
||||
public DuplicateNameException(NamedEntity entity, string name, Exception innerException)
|
||||
: base($"A {entity.ToString().ToLowerInvariant()} named '{name}' already exists.", innerException)
|
||||
{
|
||||
Entity = entity;
|
||||
Name = name;
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
using Microsoft.Data.Sqlite;
|
||||
using YKanBan.Models;
|
||||
using YKanBan.Search;
|
||||
|
||||
namespace YKanBan.Storage.Workspace;
|
||||
|
||||
@@ -71,14 +72,15 @@ public sealed class WorkspaceRepository : IDisposable
|
||||
/// <param name="title">The non-empty, table-unique title.</param>
|
||||
/// <param name="description">The optional description.</param>
|
||||
/// <returns>The created column.</returns>
|
||||
/// <exception cref="SqliteException">The title is empty or not unique.</exception>
|
||||
/// <exception cref="NameRequiredException">The title is empty.</exception>
|
||||
/// <exception cref="DuplicateNameException">The title is not unique.</exception>
|
||||
public ColumnModel AddColumn(string title, string description)
|
||||
{
|
||||
long now = UnixTime.Now;
|
||||
using var transaction = _connection.BeginTransaction();
|
||||
long id = ExecuteInsert(transaction,
|
||||
long id = MapNameConstraint(NamedEntity.Column, title, () => ExecuteInsert(transaction,
|
||||
"INSERT INTO columns (title, description, created_at, updated_at) VALUES ($title, $description, $now, $now);",
|
||||
("$title", title), ("$description", description), ("$now", now));
|
||||
("$title", title), ("$description", description), ("$now", now)));
|
||||
transaction.Commit();
|
||||
|
||||
return new ColumnModel(id, title, description, now, now);
|
||||
@@ -93,7 +95,8 @@ public sealed class WorkspaceRepository : IDisposable
|
||||
/// <param name="description">The new description.</param>
|
||||
/// <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>
|
||||
/// <exception cref="NameRequiredException">The new title is empty.</exception>
|
||||
/// <exception cref="DuplicateNameException">The new title is not unique.</exception>
|
||||
public ColumnModel UpdateColumn(long columnId, string title, string description)
|
||||
{
|
||||
ColumnModel existing = GetColumn(columnId)
|
||||
@@ -112,7 +115,7 @@ public sealed class WorkspaceRepository : IDisposable
|
||||
command.Parameters.AddWithValue("$description", description);
|
||||
command.Parameters.AddWithValue("$now", now);
|
||||
command.Parameters.AddWithValue("$id", columnId);
|
||||
command.ExecuteNonQuery();
|
||||
MapNameConstraint(NamedEntity.Column, title, command.ExecuteNonQuery);
|
||||
|
||||
return new ColumnModel(columnId, title, description, existing.CreatedAt, now);
|
||||
}
|
||||
@@ -132,16 +135,34 @@ 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() => GetCards(null);
|
||||
|
||||
/// <summary>
|
||||
/// Returns the cards matching a compiled search, with all of their assigned
|
||||
/// tags loaded (the filter selects cards, it never trims their tag lists),
|
||||
/// ordered by id ascending.
|
||||
/// </summary>
|
||||
/// <param name="filter">The compiled search, or <see langword="null"/> for every card.</param>
|
||||
/// <returns>The matching cards in id order.</returns>
|
||||
public IReadOnlyList<CardModel> GetCards(CompiledSearch? filter)
|
||||
{
|
||||
using var command = CreateCommand("""
|
||||
string where = filter is null ? "" : $"WHERE {filter.Predicate}";
|
||||
using var command = CreateCommand($"""
|
||||
SELECT c.id, c.column_id, c.title, c.content, c.created_at, c.updated_at,
|
||||
t.id, t.name, t.color, t.description
|
||||
FROM cards c
|
||||
LEFT JOIN card_tags ct ON ct.card_id = c.id
|
||||
LEFT JOIN tags t ON t.id = ct.tag_id
|
||||
ORDER BY c.id ASC;
|
||||
{where}
|
||||
ORDER BY c.id ASC, t.id ASC;
|
||||
""");
|
||||
if (filter is not null)
|
||||
{
|
||||
foreach ((string name, object value) in filter.Parameters)
|
||||
{
|
||||
command.Parameters.AddWithValue(name, value);
|
||||
}
|
||||
}
|
||||
using var reader = command.ExecuteReader();
|
||||
|
||||
// Single grouped pass: one output card per distinct card id, with its tags accumulated alongside.
|
||||
@@ -186,7 +207,7 @@ public sealed class WorkspaceRepository : IDisposable
|
||||
LEFT JOIN card_tags ct ON ct.card_id = c.id
|
||||
LEFT JOIN tags t ON t.id = ct.tag_id
|
||||
WHERE c.id = $id
|
||||
ORDER BY c.id ASC;
|
||||
ORDER BY t.id ASC;
|
||||
""");
|
||||
command.Parameters.AddWithValue("$id", cardId);
|
||||
using var reader = command.ExecuteReader();
|
||||
@@ -302,6 +323,18 @@ public sealed class WorkspaceRepository : IDisposable
|
||||
return command.ExecuteNonQuery() > 0;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Counts the cards of a column, regardless of any search filter.
|
||||
/// </summary>
|
||||
/// <param name="columnId">The column id.</param>
|
||||
/// <returns>The number of cards in the column.</returns>
|
||||
public long CountCards(long columnId)
|
||||
{
|
||||
using var command = CreateCommand("SELECT COUNT(*) FROM cards WHERE column_id = $id;");
|
||||
command.Parameters.AddWithValue("$id", columnId);
|
||||
return (long)command.ExecuteScalar()!;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deletes a card; the DDL cascade removes its tag links.
|
||||
/// </summary>
|
||||
@@ -361,13 +394,14 @@ public sealed class WorkspaceRepository : IDisposable
|
||||
/// <param name="color">The tag color.</param>
|
||||
/// <param name="description">The optional description.</param>
|
||||
/// <returns>The created tag.</returns>
|
||||
/// <exception cref="SqliteException">The name is empty or not unique.</exception>
|
||||
/// <exception cref="NameRequiredException">The name is empty.</exception>
|
||||
/// <exception cref="DuplicateNameException">The name is not unique.</exception>
|
||||
public TagModel AddTag(string name, RgbColor color, string description)
|
||||
{
|
||||
using var transaction = _connection.BeginTransaction();
|
||||
long id = ExecuteInsert(transaction,
|
||||
long id = MapNameConstraint(NamedEntity.Tag, name, () => ExecuteInsert(transaction,
|
||||
"INSERT INTO tags (name, color, description) VALUES ($name, $color, $description);",
|
||||
("$name", name), ("$color", color.ToString()), ("$description", description));
|
||||
("$name", name), ("$color", color.ToString()), ("$description", description)));
|
||||
transaction.Commit();
|
||||
|
||||
return new TagModel(id, name, color, description);
|
||||
@@ -382,7 +416,8 @@ public sealed class WorkspaceRepository : IDisposable
|
||||
/// <param name="description">The new description.</param>
|
||||
/// <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>
|
||||
/// <exception cref="NameRequiredException">The new name is empty.</exception>
|
||||
/// <exception cref="DuplicateNameException">The new name is not unique.</exception>
|
||||
public TagModel UpdateTag(long tagId, string name, RgbColor color, string description)
|
||||
{
|
||||
TagModel existing = GetTag(tagId)
|
||||
@@ -400,7 +435,7 @@ public sealed class WorkspaceRepository : IDisposable
|
||||
command.Parameters.AddWithValue("$color", color.ToString());
|
||||
command.Parameters.AddWithValue("$description", description);
|
||||
command.Parameters.AddWithValue("$id", tagId);
|
||||
command.ExecuteNonQuery();
|
||||
MapNameConstraint(NamedEntity.Tag, name, command.ExecuteNonQuery);
|
||||
|
||||
return new TagModel(tagId, name, color, description);
|
||||
}
|
||||
@@ -416,6 +451,40 @@ public sealed class WorkspaceRepository : IDisposable
|
||||
|
||||
#region Helpers
|
||||
|
||||
/// <summary>SQLite extended result code of a failed CHECK constraint.</summary>
|
||||
private const int SqliteConstraintCheck = 275;
|
||||
|
||||
/// <summary>SQLite extended result code of a failed UNIQUE constraint.</summary>
|
||||
private const int SqliteConstraintUnique = 2067;
|
||||
|
||||
/// <summary>
|
||||
/// Runs a write against columns.title or tags.name and translates the
|
||||
/// schema's non-empty (CHECK) and uniqueness (UNIQUE) violations into typed
|
||||
/// exceptions that the UI maps to localized messages.
|
||||
/// </summary>
|
||||
/// <typeparam name="T">The write's result type.</typeparam>
|
||||
/// <param name="entity">The entity being written.</param>
|
||||
/// <param name="name">The name or title being written.</param>
|
||||
/// <param name="write">The write to run.</param>
|
||||
/// <returns>The write's result.</returns>
|
||||
/// <exception cref="NameRequiredException">The name is empty.</exception>
|
||||
/// <exception cref="DuplicateNameException">The name is not unique.</exception>
|
||||
private static T MapNameConstraint<T>(NamedEntity entity, string name, Func<T> write)
|
||||
{
|
||||
try
|
||||
{
|
||||
return write();
|
||||
}
|
||||
catch (SqliteException exception) when (exception.SqliteExtendedErrorCode == SqliteConstraintCheck)
|
||||
{
|
||||
throw new NameRequiredException(entity, exception);
|
||||
}
|
||||
catch (SqliteException exception) when (exception.SqliteExtendedErrorCode == SqliteConstraintUnique)
|
||||
{
|
||||
throw new DuplicateNameException(entity, name, exception);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the tag with the given id.
|
||||
/// </summary>
|
||||
|
||||
@@ -6,6 +6,11 @@ namespace YKanBan.Storage.Workspace;
|
||||
/// assignments. Data validity is expressed in DDL (CHECK / UNIQUE / FOREIGN
|
||||
/// KEY) so every stored row is valid by construction, and cascading deletes
|
||||
/// are covered by the same DDL.
|
||||
///
|
||||
/// Title and name uniqueness is NOCASE (ASCII case folding) while the columns
|
||||
/// themselves keep the default BINARY collation, so ordering by title stays
|
||||
/// code-point based. Until the first release the v1 script may be edited in
|
||||
/// place; after it, every schema change must be appended as a new migration.
|
||||
/// </summary>
|
||||
public static class WorkspaceSchema
|
||||
{
|
||||
@@ -22,10 +27,11 @@ public static class WorkspaceSchema
|
||||
new SchemaMigration(CurrentVersion, "initial schema", """
|
||||
CREATE TABLE columns (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
title TEXT NOT NULL UNIQUE CHECK (length(title) > 0),
|
||||
title TEXT NOT NULL CHECK (length(title) > 0),
|
||||
description TEXT NOT NULL DEFAULT '',
|
||||
created_at INTEGER NOT NULL,
|
||||
updated_at INTEGER NOT NULL
|
||||
updated_at INTEGER NOT NULL,
|
||||
UNIQUE (title COLLATE NOCASE)
|
||||
);
|
||||
|
||||
CREATE TABLE cards (
|
||||
@@ -39,9 +45,10 @@ public static class WorkspaceSchema
|
||||
|
||||
CREATE TABLE tags (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
name TEXT NOT NULL UNIQUE CHECK (length(name) > 0),
|
||||
name TEXT NOT NULL CHECK (length(name) > 0),
|
||||
color TEXT NOT NULL CHECK (color GLOB '#[0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f]'),
|
||||
description TEXT NOT NULL DEFAULT ''
|
||||
description TEXT NOT NULL DEFAULT '',
|
||||
UNIQUE (name COLLATE NOCASE)
|
||||
);
|
||||
|
||||
CREATE TABLE card_tags (
|
||||
|
||||
@@ -0,0 +1,338 @@
|
||||
using System.Collections.ObjectModel;
|
||||
using System.Diagnostics;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using CommunityToolkit.Mvvm.Input;
|
||||
using YKanBan.Models;
|
||||
using YKanBan.Search;
|
||||
using YKanBan.Storage.AppData;
|
||||
using YKanBan.Storage.Workspace;
|
||||
using YKanBan.ViewModels.Dialogs;
|
||||
|
||||
namespace YKanBan.ViewModels.Board;
|
||||
|
||||
/// <summary>
|
||||
/// The board tab: the toolbar (search bar, new column, column width, card sort)
|
||||
/// and the columns laid out left to right, each listing its cards top to bottom.
|
||||
///
|
||||
/// The search runs only on an explicit search (button or Enter), never while
|
||||
/// typing. An invalid expression is reported in a message dialog and changes
|
||||
/// nothing: the box keeps its text and the board keeps the previous result.
|
||||
///
|
||||
/// Every write is followed by <see cref="Refresh"/>, which re-queries with the
|
||||
/// most recently successful search expression (<see cref="ActiveFilter"/>), not
|
||||
/// with whatever the search box currently holds: cards that no longer match
|
||||
/// disappear, new cards that do not match are not shown, and empty columns stay.
|
||||
/// </summary>
|
||||
public sealed partial class BoardViewModel : ViewModelBase
|
||||
{
|
||||
private readonly WorkspaceRepository _repository;
|
||||
private readonly AppConfig _config;
|
||||
private readonly IDialogService _dialogs;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes the board and loads it.
|
||||
/// </summary>
|
||||
/// <param name="repository">The workspace repository.</param>
|
||||
/// <param name="config">The live application configuration (sort, column width, confirmations).</param>
|
||||
/// <param name="dialogs">The modal dialog service.</param>
|
||||
public BoardViewModel(WorkspaceRepository repository, AppConfig config, IDialogService dialogs)
|
||||
{
|
||||
_repository = repository;
|
||||
_config = config;
|
||||
_dialogs = dialogs;
|
||||
|
||||
SortOptions =
|
||||
[
|
||||
new OptionItem(CardSortOption.Id, Resources.Sort_Id),
|
||||
new OptionItem(CardSortOption.UpdatedAt, Resources.Sort_UpdatedAt),
|
||||
new OptionItem(CardSortOption.Title, Resources.Sort_Title),
|
||||
];
|
||||
selectedSort = SortOptions.FirstOrDefault(option => (CardSortOption)option.Value == config.Sort.Card)
|
||||
?? SortOptions[0];
|
||||
columnWidth = ColumnWidths.Resolve(config.ColumnWidth);
|
||||
|
||||
Refresh();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Raised after every board write (the refresh included), so the tags tab
|
||||
/// can update its usage counts.
|
||||
/// </summary>
|
||||
public event EventHandler? DataWritten;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the columns in id order.
|
||||
/// </summary>
|
||||
public ObservableCollection<ColumnViewModel> Columns { get; } = [];
|
||||
|
||||
/// <summary>
|
||||
/// Gets the card sort options shown in the combobox.
|
||||
/// </summary>
|
||||
public IReadOnlyList<OptionItem> SortOptions { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the column models in id order, as of the last refresh.
|
||||
/// </summary>
|
||||
public IReadOnlyList<ColumnModel> ColumnModels { get; private set; } = [];
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the most recently successful search; <see langword="null"/> shows every card.
|
||||
/// </summary>
|
||||
public CompiledSearch? ActiveFilter { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the search box text; it only takes effect on <see cref="SearchCommand"/>.
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
[NotifyPropertyChangedFor(nameof(HasSearchText))]
|
||||
private string searchText = "";
|
||||
|
||||
/// <summary>
|
||||
/// Gets whether the search box holds text (shows the clear button).
|
||||
/// </summary>
|
||||
public bool HasSearchText => SearchText.Length > 0;
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the selected card sort option; changing it is persisted and re-sorts the board.
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private OptionItem selectedSort;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the effective column width in pixels.
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private int columnWidth;
|
||||
|
||||
/// <summary>
|
||||
/// Reloads the columns and the cards matching <see cref="ActiveFilter"/>.
|
||||
/// </summary>
|
||||
public void Refresh()
|
||||
{
|
||||
IReadOnlyList<ColumnModel> columns = _repository.GetColumns();
|
||||
ILookup<long, CardModel> cardsByColumn = _repository.GetCards(ActiveFilter).ToLookup(card => card.ColumnId);
|
||||
var sort = (CardSortOption)SelectedSort.Value;
|
||||
|
||||
ColumnModels = columns;
|
||||
Columns.Clear();
|
||||
foreach (ColumnModel column in columns)
|
||||
{
|
||||
Columns.Add(new ColumnViewModel(this, column, CardOrdering.Sort(cardsByColumn[column.Id], sort)));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Parses and runs the search box text; blank text shows every card. An
|
||||
/// invalid expression only shows the error dialog.
|
||||
/// </summary>
|
||||
/// <returns>A task completing after the refresh or the error dialog.</returns>
|
||||
[RelayCommand]
|
||||
private async Task SearchAsync()
|
||||
{
|
||||
CompiledSearch? filter;
|
||||
try
|
||||
{
|
||||
SearchNode? query = SearchQueryParser.Parse(SearchText);
|
||||
filter = query is null ? null : SearchSqlCompiler.Compile(query);
|
||||
}
|
||||
catch (SearchSyntaxException exception)
|
||||
{
|
||||
await _dialogs.ShowMessageAsync(
|
||||
Resources.Search_Error_Title,
|
||||
string.Format(Resources.Culture, Resources.Search_Error_Message, exception.Message));
|
||||
return;
|
||||
}
|
||||
|
||||
ActiveFilter = filter;
|
||||
Refresh();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Empties the search box and shows every card again.
|
||||
/// </summary>
|
||||
[RelayCommand]
|
||||
private void ClearSearch()
|
||||
{
|
||||
SearchText = "";
|
||||
ActiveFilter = null;
|
||||
Refresh();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Opens the new-column dialog.
|
||||
/// </summary>
|
||||
/// <returns>A task completing when the dialog closes.</returns>
|
||||
[RelayCommand]
|
||||
private async Task AddColumnAsync()
|
||||
{
|
||||
var dialog = new ColumnEditorDialogViewModel(null, (title, description) => _repository.AddColumn(title, description));
|
||||
if (await _dialogs.ShowAsync(dialog))
|
||||
{
|
||||
RefreshAfterWrite();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Opens the column width dialog and applies the choice.
|
||||
/// </summary>
|
||||
/// <returns>A task completing when the dialog closes.</returns>
|
||||
[RelayCommand]
|
||||
private async Task AdjustColumnWidthAsync()
|
||||
{
|
||||
if (await _dialogs.ShowAsync(new ColumnWidthDialogViewModel(_config.ColumnWidth)))
|
||||
{
|
||||
ColumnWidth = ColumnWidths.Resolve(_config.ColumnWidth);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Opens the edit-column dialog.
|
||||
/// </summary>
|
||||
/// <param name="column">The column to edit.</param>
|
||||
/// <returns>A task completing when the dialog closes.</returns>
|
||||
internal async Task EditColumnAsync(ColumnModel column)
|
||||
{
|
||||
var dialog = new ColumnEditorDialogViewModel(
|
||||
column, (title, description) => _repository.UpdateColumn(column.Id, title, description));
|
||||
if (await _dialogs.ShowAsync(dialog))
|
||||
{
|
||||
RefreshAfterWrite();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deletes a column with its cards, asking first when that confirmation is enabled.
|
||||
/// </summary>
|
||||
/// <param name="column">The column to delete.</param>
|
||||
/// <returns>A task completing when the column is deleted or the deletion was declined.</returns>
|
||||
internal async Task DeleteColumnAsync(ColumnModel column)
|
||||
{
|
||||
await RunWriteAsync(async () =>
|
||||
{
|
||||
if (_config.Confirmations.DeleteColumn)
|
||||
{
|
||||
long count = _repository.CountCards(column.Id);
|
||||
string message = string.Format(Resources.Culture, Resources.Confirm_DeleteColumn, column.Title, count);
|
||||
if (!await _dialogs.ConfirmAsync(message, Resources.Common_Delete))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
_repository.DeleteColumn(column.Id);
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Opens the card editor for a new card in a column.
|
||||
/// </summary>
|
||||
/// <param name="columnId">The column receiving the card.</param>
|
||||
/// <returns>A task completing when the editor closes.</returns>
|
||||
internal async Task AddCardAsync(long columnId)
|
||||
{
|
||||
var editor = CardEditorDialogViewModel.ForNewCard(
|
||||
_repository, _dialogs, columnId, _config.Confirmations.DiscardEdit);
|
||||
await _dialogs.ShowAsync(editor);
|
||||
|
||||
// Refresh even after a cancel: the nested picker may have created tags.
|
||||
RefreshAfterWrite();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Opens the card editor for an existing card, reloaded from the database.
|
||||
/// </summary>
|
||||
/// <param name="cardId">The card to edit.</param>
|
||||
/// <returns>A task completing when the editor closes.</returns>
|
||||
internal async Task EditCardAsync(long cardId)
|
||||
{
|
||||
CardModel? card = _repository.GetCard(cardId);
|
||||
if (card is null)
|
||||
{
|
||||
Refresh();
|
||||
return;
|
||||
}
|
||||
|
||||
var editor = CardEditorDialogViewModel.ForExistingCard(
|
||||
_repository, _dialogs, card, _config.Confirmations.DiscardEdit);
|
||||
await _dialogs.ShowAsync(editor);
|
||||
RefreshAfterWrite();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deletes a card, asking first when that confirmation is enabled.
|
||||
/// </summary>
|
||||
/// <param name="card">The card to delete.</param>
|
||||
/// <returns>A task completing when the card is deleted or the deletion was declined.</returns>
|
||||
internal async Task DeleteCardAsync(CardModel card)
|
||||
{
|
||||
await RunWriteAsync(async () =>
|
||||
{
|
||||
if (_config.Confirmations.DeleteCard)
|
||||
{
|
||||
string message = string.Format(Resources.Culture, Resources.Confirm_DeleteCard, CardViewModel.FormatHeader(card));
|
||||
if (!await _dialogs.ConfirmAsync(message, Resources.Common_Delete))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
_repository.DeleteCard(card.Id);
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Moves a card to another column.
|
||||
/// </summary>
|
||||
/// <param name="cardId">The card to move.</param>
|
||||
/// <param name="columnId">The target column.</param>
|
||||
/// <returns>A task completing when the card is moved.</returns>
|
||||
internal Task MoveCardAsync(long cardId, long columnId) =>
|
||||
RunWriteAsync(() =>
|
||||
{
|
||||
_repository.MoveCard(cardId, columnId);
|
||||
return Task.FromResult(true);
|
||||
});
|
||||
|
||||
/// <summary>
|
||||
/// Runs an immediate write and refreshes after it; an unexpected failure is
|
||||
/// reported in a message dialog and the board is refreshed to the stored state.
|
||||
/// </summary>
|
||||
/// <param name="write">The write; returns <see langword="false"/> when the user declined it.</param>
|
||||
/// <returns>A task completing after the refresh.</returns>
|
||||
private async Task RunWriteAsync(Func<Task<bool>> write)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!await write())
|
||||
{
|
||||
return;
|
||||
}
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
Debug.WriteLine(exception);
|
||||
await _dialogs.ShowMessageAsync(
|
||||
Resources.Error_Operation_Title, Resources.Error_Operation_Message, exception.Message);
|
||||
}
|
||||
RefreshAfterWrite();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Refreshes after a write and announces it.
|
||||
/// </summary>
|
||||
private void RefreshAfterWrite()
|
||||
{
|
||||
Refresh();
|
||||
DataWritten?.Invoke(this, EventArgs.Empty);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Persists the sort option and re-sorts the board.
|
||||
/// </summary>
|
||||
/// <param name="value">The new sort option.</param>
|
||||
partial void OnSelectedSortChanged(OptionItem value)
|
||||
{
|
||||
_config.Sort.Card = (CardSortOption)value.Value;
|
||||
Refresh();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
using System.Globalization;
|
||||
using CommunityToolkit.Mvvm.Input;
|
||||
using YKanBan.Models;
|
||||
|
||||
namespace YKanBan.ViewModels.Board;
|
||||
|
||||
/// <summary>
|
||||
/// One card in a column list: "#id" in bold on the same line as the title, the
|
||||
/// content cut to a fixed length, and the tag badges below. No timestamps.
|
||||
/// Clicking the card opens the editor; its menu deletes or moves it.
|
||||
/// </summary>
|
||||
public sealed partial class CardViewModel : ViewModelBase
|
||||
{
|
||||
/// <summary>
|
||||
/// The number of text elements of content shown on the card.
|
||||
/// </summary>
|
||||
public const int ExcerptLength = 200;
|
||||
|
||||
private readonly BoardViewModel _board;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes the card.
|
||||
/// </summary>
|
||||
/// <param name="board">The owning board.</param>
|
||||
/// <param name="card">The card shown.</param>
|
||||
public CardViewModel(BoardViewModel board, CardModel card)
|
||||
{
|
||||
_board = board;
|
||||
Card = card;
|
||||
IdText = $"#{card.Id.ToString(CultureInfo.InvariantCulture)}";
|
||||
Excerpt = MakeExcerpt(card.Content);
|
||||
Tags = card.Tags.Select(tag => new TagBadgeViewModel(tag)).ToList();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the card shown.
|
||||
/// </summary>
|
||||
public CardModel Card { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the "#id" text.
|
||||
/// </summary>
|
||||
public string IdText { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the title; empty when the card has none.
|
||||
/// </summary>
|
||||
public string Title => Card.Title;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the title as it follows "#id" on the header line: a space and the
|
||||
/// title, or nothing when the card has no title.
|
||||
/// </summary>
|
||||
public string TitleSuffix => Card.Title.Length == 0 ? "" : " " + Card.Title;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the truncated content.
|
||||
/// </summary>
|
||||
public string Excerpt { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets whether there is content to show.
|
||||
/// </summary>
|
||||
public bool HasExcerpt => Excerpt.Length > 0;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the tag badges.
|
||||
/// </summary>
|
||||
public IReadOnlyList<TagBadgeViewModel> Tags { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets whether the card has tags.
|
||||
/// </summary>
|
||||
public bool HasTags => Tags.Count > 0;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the "move to column" targets; built when the menu asks for them.
|
||||
/// The card's current column is listed but disabled.
|
||||
/// </summary>
|
||||
public IReadOnlyList<MoveTargetViewModel> MoveTargets =>
|
||||
_board.ColumnModels
|
||||
.Select(column => new MoveTargetViewModel(column.Title, column.Id != Card.ColumnId, MoveToCommand, column.Id))
|
||||
.ToList();
|
||||
|
||||
/// <summary>
|
||||
/// Formats the "#id title" header text of a card ("#id" alone without a title).
|
||||
/// </summary>
|
||||
/// <param name="card">The card.</param>
|
||||
/// <returns>The header text.</returns>
|
||||
public static string FormatHeader(CardModel card) =>
|
||||
card.Title.Length == 0
|
||||
? $"#{card.Id.ToString(CultureInfo.InvariantCulture)}"
|
||||
: $"#{card.Id.ToString(CultureInfo.InvariantCulture)} {card.Title}";
|
||||
|
||||
/// <summary>
|
||||
/// Cuts content to <see cref="ExcerptLength"/> text elements, appending an
|
||||
/// ellipsis when something was cut. Surrogate pairs and combining sequences
|
||||
/// are never split.
|
||||
/// </summary>
|
||||
/// <param name="content">The card content.</param>
|
||||
/// <returns>The excerpt.</returns>
|
||||
public static string MakeExcerpt(string content)
|
||||
{
|
||||
string trimmed = content.Trim();
|
||||
var info = new StringInfo(trimmed);
|
||||
return info.LengthInTextElements <= ExcerptLength
|
||||
? trimmed
|
||||
: info.SubstringByTextElements(0, ExcerptLength).TrimEnd() + "…";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Opens the card editor.
|
||||
/// </summary>
|
||||
/// <returns>A task completing when the editor closes.</returns>
|
||||
[RelayCommand]
|
||||
private Task EditAsync() => _board.EditCardAsync(Card.Id);
|
||||
|
||||
/// <summary>
|
||||
/// Deletes the card.
|
||||
/// </summary>
|
||||
/// <returns>A task completing when the card is deleted or the deletion was declined.</returns>
|
||||
[RelayCommand]
|
||||
private Task DeleteAsync() => _board.DeleteCardAsync(Card);
|
||||
|
||||
/// <summary>
|
||||
/// Moves the card to another column.
|
||||
/// </summary>
|
||||
/// <param name="columnId">The target column.</param>
|
||||
/// <returns>A task completing when the card is moved.</returns>
|
||||
[RelayCommand]
|
||||
private Task MoveToAsync(long columnId) => _board.MoveCardAsync(Card.Id, columnId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// An entry of a card's "move to column" submenu.
|
||||
/// </summary>
|
||||
/// <param name="Title">The column title.</param>
|
||||
/// <param name="IsEnabled">Whether the entry can be picked (false for the card's own column).</param>
|
||||
/// <param name="Command">The move command.</param>
|
||||
/// <param name="ColumnId">The target column, passed to <paramref name="Command"/>.</param>
|
||||
public sealed record MoveTargetViewModel(string Title, bool IsEnabled, IAsyncRelayCommand<long> Command, long ColumnId);
|
||||
@@ -0,0 +1,77 @@
|
||||
using CommunityToolkit.Mvvm.Input;
|
||||
using YKanBan.Models;
|
||||
|
||||
namespace YKanBan.ViewModels.Board;
|
||||
|
||||
/// <summary>
|
||||
/// One board column: its header (title, card count, description, the new-card
|
||||
/// button and the edit/delete menu) and its virtualized card list.
|
||||
/// </summary>
|
||||
public sealed partial class ColumnViewModel : ViewModelBase
|
||||
{
|
||||
private readonly BoardViewModel _board;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes the column.
|
||||
/// </summary>
|
||||
/// <param name="board">The owning board.</param>
|
||||
/// <param name="column">The column shown.</param>
|
||||
/// <param name="cards">The column's visible cards, in display order.</param>
|
||||
public ColumnViewModel(BoardViewModel board, ColumnModel column, IReadOnlyList<CardModel> cards)
|
||||
{
|
||||
_board = board;
|
||||
Column = column;
|
||||
Cards = cards.Select(card => new CardViewModel(board, card)).ToList();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the column shown.
|
||||
/// </summary>
|
||||
public ColumnModel Column { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the column title.
|
||||
/// </summary>
|
||||
public string Title => Column.Title;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the column description.
|
||||
/// </summary>
|
||||
public string Description => Column.Description;
|
||||
|
||||
/// <summary>
|
||||
/// Gets whether the column has a description to show.
|
||||
/// </summary>
|
||||
public bool HasDescription => Column.Description.Length > 0;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the number of visible cards.
|
||||
/// </summary>
|
||||
public int CardCount => Cards.Count;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the visible cards in display order.
|
||||
/// </summary>
|
||||
public IReadOnlyList<CardViewModel> Cards { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Opens the card editor for a new card in this column.
|
||||
/// </summary>
|
||||
/// <returns>A task completing when the editor closes.</returns>
|
||||
[RelayCommand]
|
||||
private Task AddCardAsync() => _board.AddCardAsync(Column.Id);
|
||||
|
||||
/// <summary>
|
||||
/// Opens the edit-column dialog.
|
||||
/// </summary>
|
||||
/// <returns>A task completing when the dialog closes.</returns>
|
||||
[RelayCommand]
|
||||
private Task EditAsync() => _board.EditColumnAsync(Column);
|
||||
|
||||
/// <summary>
|
||||
/// Deletes the column with its cards.
|
||||
/// </summary>
|
||||
/// <returns>A task completing when the column is deleted or the deletion was declined.</returns>
|
||||
[RelayCommand]
|
||||
private Task DeleteAsync() => _board.DeleteColumnAsync(Column);
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
using Avalonia.Media;
|
||||
using Avalonia.Media.Immutable;
|
||||
using YKanBan.Models;
|
||||
|
||||
namespace YKanBan.ViewModels.Board;
|
||||
|
||||
/// <summary>
|
||||
/// A colored tag badge (color + name). Tag colors are user data: they are shown
|
||||
/// as the literal #RRGGBB value in both themes, with a black or white text color
|
||||
/// chosen for contrast.
|
||||
/// </summary>
|
||||
public sealed class TagBadgeViewModel : ViewModelBase
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes the badge.
|
||||
/// </summary>
|
||||
/// <param name="tag">The tag shown.</param>
|
||||
public TagBadgeViewModel(TagModel tag)
|
||||
{
|
||||
Tag = tag;
|
||||
Background = new ImmutableSolidColorBrush(Color.FromRgb(tag.Color.R, tag.Color.G, tag.Color.B));
|
||||
Foreground = IsLight(tag.Color) ? Brushes.Black : Brushes.White;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the tag shown.
|
||||
/// </summary>
|
||||
public TagModel Tag { 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 the badge fill: the tag's own color.
|
||||
/// </summary>
|
||||
public IBrush Background { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the text color contrasting with <see cref="Background"/>.
|
||||
/// </summary>
|
||||
public IBrush Foreground { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Decides whether dark text reads better on a color, by its relative luminance.
|
||||
/// </summary>
|
||||
/// <param name="color">The background color.</param>
|
||||
/// <returns><see langword="true"/> for light colors.</returns>
|
||||
public static bool IsLight(RgbColor color) =>
|
||||
(0.299 * color.R) + (0.587 * color.G) + (0.114 * color.B) > 150;
|
||||
}
|
||||
@@ -30,7 +30,7 @@ public sealed class AboutDialogViewModel : ViewModelBase
|
||||
/// <summary>
|
||||
/// Gets the repository URL.
|
||||
/// </summary>
|
||||
public string RepositoryUrl => "https://github.com/yyc12345/YKanBan";
|
||||
public string RepositoryUrl => "https://code.blumia.cn/yyc12345/YKanBan";
|
||||
|
||||
/// <summary>
|
||||
/// Gets the license name.
|
||||
|
||||
@@ -0,0 +1,228 @@
|
||||
using System.Collections.ObjectModel;
|
||||
using System.Globalization;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using CommunityToolkit.Mvvm.Input;
|
||||
using YKanBan.Models;
|
||||
using YKanBan.Storage.Workspace;
|
||||
using YKanBan.ViewModels.Board;
|
||||
|
||||
namespace YKanBan.ViewModels.Dialogs;
|
||||
|
||||
/// <summary>
|
||||
/// The card editor — one unit of work. Title, content and the tag assignment
|
||||
/// are edited in memory and written together in a single transaction on
|
||||
/// confirmation; cancelling writes nothing about the card or its assignment.
|
||||
/// Confirming an existing card without effective changes writes nothing and
|
||||
/// keeps its timestamps. The only immediate write is the creation of a new tag
|
||||
/// in the nested tag picker (see <see cref="TagPickerDialogViewModel"/>).
|
||||
/// </summary>
|
||||
public sealed partial class CardEditorDialogViewModel : DialogViewModelBase
|
||||
{
|
||||
private readonly WorkspaceRepository _repository;
|
||||
private readonly IDialogService _dialogs;
|
||||
private readonly CardModel? _existing;
|
||||
private readonly long _columnId;
|
||||
private readonly bool _confirmDiscard;
|
||||
private readonly string _initialTitle;
|
||||
private readonly string _initialContent;
|
||||
private readonly HashSet<long> _initialTagIds;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes the editor for a new card in a column.
|
||||
/// </summary>
|
||||
/// <param name="repository">The workspace repository.</param>
|
||||
/// <param name="dialogs">The dialog service, for the nested tag picker and the discard confirmation.</param>
|
||||
/// <param name="columnId">The column receiving the new card.</param>
|
||||
/// <param name="confirmDiscard">Whether discarding changes asks for confirmation.</param>
|
||||
/// <returns>The editor.</returns>
|
||||
public static CardEditorDialogViewModel ForNewCard(
|
||||
WorkspaceRepository repository, IDialogService dialogs, long columnId, bool confirmDiscard) =>
|
||||
new(repository, dialogs, null, columnId, confirmDiscard);
|
||||
|
||||
/// <summary>
|
||||
/// Initializes the editor for an existing card.
|
||||
/// </summary>
|
||||
/// <param name="repository">The workspace repository.</param>
|
||||
/// <param name="dialogs">The dialog service, for the nested tag picker and the discard confirmation.</param>
|
||||
/// <param name="card">The card to edit.</param>
|
||||
/// <param name="confirmDiscard">Whether discarding changes asks for confirmation.</param>
|
||||
/// <returns>The editor.</returns>
|
||||
public static CardEditorDialogViewModel ForExistingCard(
|
||||
WorkspaceRepository repository, IDialogService dialogs, CardModel card, bool confirmDiscard) =>
|
||||
new(repository, dialogs, card, card.ColumnId, confirmDiscard);
|
||||
|
||||
private CardEditorDialogViewModel(
|
||||
WorkspaceRepository repository, IDialogService dialogs, CardModel? existing, long columnId, bool confirmDiscard)
|
||||
{
|
||||
_repository = repository;
|
||||
_dialogs = dialogs;
|
||||
_existing = existing;
|
||||
_columnId = columnId;
|
||||
_confirmDiscard = confirmDiscard;
|
||||
_initialTitle = existing?.Title ?? "";
|
||||
_initialContent = existing?.Content ?? "";
|
||||
_initialTagIds = existing?.Tags.Select(tag => tag.Id).ToHashSet() ?? [];
|
||||
|
||||
cardTitle = _initialTitle;
|
||||
content = _initialContent;
|
||||
Tags = new ObservableCollection<TagBadgeViewModel>(
|
||||
existing?.Tags.Select(tag => new TagBadgeViewModel(tag)) ?? []);
|
||||
|
||||
if (existing is null)
|
||||
{
|
||||
Title = Resources.CardEditor_TitleNew;
|
||||
}
|
||||
else
|
||||
{
|
||||
CultureInfo? culture = Resources.Culture;
|
||||
Title = Resources.CardEditor_TitleEdit;
|
||||
IdText = $"#{existing.Id.ToString(CultureInfo.InvariantCulture)}";
|
||||
CreatedText = string.Format(culture, Resources.CardEditor_Created, FormatTime(existing.CreatedAt));
|
||||
ModifiedText = string.Format(culture, Resources.CardEditor_Modified, FormatTime(existing.UpdatedAt));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the localized window title.
|
||||
/// </summary>
|
||||
public string Title { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets whether the card already exists (and thus has an id and timestamps to show).
|
||||
/// </summary>
|
||||
public bool IsExisting => _existing is not null;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the read-only "#id" text of an existing card.
|
||||
/// </summary>
|
||||
public string? IdText { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the read-only creation time line of an existing card.
|
||||
/// </summary>
|
||||
public string? CreatedText { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the read-only modification time line of an existing card.
|
||||
/// </summary>
|
||||
public string? ModifiedText { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the tags assigned in this edit session, in assignment order.
|
||||
/// </summary>
|
||||
public ObservableCollection<TagBadgeViewModel> Tags { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the card written on confirmation; <see langword="null"/> until then.
|
||||
/// </summary>
|
||||
public CardModel? SavedCard { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the card title; the empty string means "no title".
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private string cardTitle;
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the multiline card content.
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private string content;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the localized error of the last confirmation, or <see langword="null"/>.
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
[NotifyPropertyChangedFor(nameof(HasError))]
|
||||
private string? errorMessage;
|
||||
|
||||
/// <summary>
|
||||
/// Gets whether an error is shown.
|
||||
/// </summary>
|
||||
public bool HasError => ErrorMessage is not null;
|
||||
|
||||
/// <summary>
|
||||
/// Gets whether the in-memory state differs from the state the editor opened with.
|
||||
/// </summary>
|
||||
public bool IsDirty =>
|
||||
CardTitle != _initialTitle
|
||||
|| Content != _initialContent
|
||||
|| !_initialTagIds.SetEquals(Tags.Select(tag => tag.Tag.Id));
|
||||
|
||||
/// <summary>
|
||||
/// Opens the nested tag picker and assigns the picked (or newly created) tag.
|
||||
/// </summary>
|
||||
/// <returns>A task completing when the picker closes.</returns>
|
||||
[RelayCommand]
|
||||
private async Task AddTagAsync()
|
||||
{
|
||||
var picker = new TagPickerDialogViewModel(_repository, Tags.Select(tag => tag.Tag.Id).ToHashSet());
|
||||
if (await _dialogs.ShowAsync(picker) && picker.PickedTag is { } picked)
|
||||
{
|
||||
Tags.Add(new TagBadgeViewModel(picked));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes a tag from the in-memory assignment.
|
||||
/// </summary>
|
||||
/// <param name="tag">The tag to remove.</param>
|
||||
[RelayCommand]
|
||||
private void RemoveTag(TagBadgeViewModel tag) => Tags.Remove(tag);
|
||||
|
||||
/// <summary>
|
||||
/// Writes the card in one transaction and closes; an unchanged existing card
|
||||
/// is not written at all.
|
||||
/// </summary>
|
||||
[RelayCommand]
|
||||
private void Confirm()
|
||||
{
|
||||
if (_existing is not null && !IsDirty)
|
||||
{
|
||||
SavedCard = _existing;
|
||||
Close(true);
|
||||
return;
|
||||
}
|
||||
|
||||
long[] tagIds = Tags.Select(tag => tag.Tag.Id).ToArray();
|
||||
try
|
||||
{
|
||||
SavedCard = _existing is null
|
||||
? _repository.AddCard(_columnId, CardTitle, Content, tagIds)
|
||||
: _repository.UpdateCard(_existing.Id, CardTitle, Content, tagIds);
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
ErrorMessage = WriteErrorMessages.Describe(exception);
|
||||
return;
|
||||
}
|
||||
Close(true);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Closes without writing the card, asking first when there are unsaved
|
||||
/// changes and the discard confirmation is enabled.
|
||||
/// </summary>
|
||||
[RelayCommand]
|
||||
private Task CancelAsync() => RequestCancelAsync();
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override async Task RequestCancelAsync()
|
||||
{
|
||||
if (_confirmDiscard && IsDirty
|
||||
&& !await _dialogs.ConfirmAsync(Resources.Confirm_DiscardEdit, Resources.Common_Discard))
|
||||
{
|
||||
return;
|
||||
}
|
||||
Close(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Formats a Unix-seconds timestamp in local time with the language's pattern.
|
||||
/// </summary>
|
||||
/// <param name="unixSeconds">The timestamp.</param>
|
||||
/// <returns>The formatted time.</returns>
|
||||
private static string FormatTime(long unixSeconds) =>
|
||||
DateTimeOffset.FromUnixTimeSeconds(unixSeconds).ToLocalTime()
|
||||
.ToString(Resources.Common_TimePattern, Resources.Culture);
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using CommunityToolkit.Mvvm.Input;
|
||||
using YKanBan.Models;
|
||||
|
||||
namespace YKanBan.ViewModels.Dialogs;
|
||||
|
||||
/// <summary>
|
||||
/// The new-column / edit-column dialog: a required title and an optional
|
||||
/// description. Confirming writes through the supplied save callback; a
|
||||
/// schema-constraint violation (empty or duplicate title) is shown inside the
|
||||
/// dialog, which stays open with the user's input intact.
|
||||
/// </summary>
|
||||
public sealed partial class ColumnEditorDialogViewModel : DialogViewModelBase
|
||||
{
|
||||
private readonly Action<string, string> _save;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes the dialog.
|
||||
/// </summary>
|
||||
/// <param name="existing">The column being edited, or <see langword="null"/> for a new column.</param>
|
||||
/// <param name="save">Writes the title and description; throws the repository's typed exceptions.</param>
|
||||
public ColumnEditorDialogViewModel(ColumnModel? existing, Action<string, string> save)
|
||||
{
|
||||
_save = save;
|
||||
Title = existing is null ? Resources.ColumnEditor_TitleNew : Resources.ColumnEditor_TitleEdit;
|
||||
columnTitle = existing?.Title ?? "";
|
||||
description = existing?.Description ?? "";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the localized window title.
|
||||
/// </summary>
|
||||
public string Title { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the column title being edited (not trimmed).
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private string columnTitle;
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the column description being edited.
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private string description;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the localized constraint error of the last confirmation, or <see langword="null"/>.
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
[NotifyPropertyChangedFor(nameof(HasError))]
|
||||
private string? errorMessage;
|
||||
|
||||
/// <summary>
|
||||
/// Gets whether an error is shown.
|
||||
/// </summary>
|
||||
public bool HasError => ErrorMessage is not null;
|
||||
|
||||
/// <summary>
|
||||
/// Writes the column; closes on success, otherwise shows the constraint error.
|
||||
/// </summary>
|
||||
[RelayCommand]
|
||||
private void Confirm()
|
||||
{
|
||||
try
|
||||
{
|
||||
_save(ColumnTitle, Description);
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
ErrorMessage = WriteErrorMessages.Describe(exception);
|
||||
return;
|
||||
}
|
||||
Close(true);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Closes without writing.
|
||||
/// </summary>
|
||||
[RelayCommand]
|
||||
private Task CancelAsync() => RequestCancelAsync();
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
using System.Globalization;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using CommunityToolkit.Mvvm.Input;
|
||||
using YKanBan.Storage.AppData;
|
||||
|
||||
namespace YKanBan.ViewModels.Dialogs;
|
||||
|
||||
/// <summary>
|
||||
/// The column width dialog: one of the narrow / standard / wide presets or a
|
||||
/// manual pixel width (160–720). The choice is global and is committed to the
|
||||
/// live configuration on confirmation only.
|
||||
/// </summary>
|
||||
public sealed partial class ColumnWidthDialogViewModel : DialogViewModelBase
|
||||
{
|
||||
private readonly ColumnWidthSettings _settings;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes the dialog from the live settings.
|
||||
/// </summary>
|
||||
/// <param name="settings">The live column width settings.</param>
|
||||
public ColumnWidthDialogViewModel(ColumnWidthSettings settings)
|
||||
{
|
||||
_settings = settings;
|
||||
CultureInfo? culture = Resources.Culture;
|
||||
NarrowLabel = string.Format(culture, Resources.ColumnWidth_Narrow, ColumnWidths.Narrow);
|
||||
StandardLabel = string.Format(culture, Resources.ColumnWidth_Standard, ColumnWidths.Standard);
|
||||
WideLabel = string.Format(culture, Resources.ColumnWidth_Wide, ColumnWidths.Wide);
|
||||
RangeLabel = string.Format(culture, Resources.ColumnWidth_Range, AppConfig.MinColumnPixels, AppConfig.MaxColumnPixels);
|
||||
|
||||
isNarrow = settings.Preset == ColumnWidthPreset.Narrow;
|
||||
isStandard = settings.Preset == ColumnWidthPreset.Standard;
|
||||
isWide = settings.Preset == ColumnWidthPreset.Wide;
|
||||
isCustom = settings.Preset == ColumnWidthPreset.Custom;
|
||||
customPixels = settings.CustomPixels;
|
||||
}
|
||||
|
||||
/// <summary>Gets the localized narrow preset label.</summary>
|
||||
public string NarrowLabel { get; }
|
||||
|
||||
/// <summary>Gets the localized standard preset label.</summary>
|
||||
public string StandardLabel { get; }
|
||||
|
||||
/// <summary>Gets the localized wide preset label.</summary>
|
||||
public string WideLabel { get; }
|
||||
|
||||
/// <summary>Gets the localized accepted pixel range.</summary>
|
||||
public string RangeLabel { get; }
|
||||
|
||||
/// <summary>Gets the smallest accepted custom width.</summary>
|
||||
public int MinPixels => AppConfig.MinColumnPixels;
|
||||
|
||||
/// <summary>Gets the largest accepted custom width.</summary>
|
||||
public int MaxPixels => AppConfig.MaxColumnPixels;
|
||||
|
||||
/// <summary>Gets or sets whether the narrow preset is selected.</summary>
|
||||
[ObservableProperty]
|
||||
private bool isNarrow;
|
||||
|
||||
/// <summary>Gets or sets whether the standard preset is selected.</summary>
|
||||
[ObservableProperty]
|
||||
private bool isStandard;
|
||||
|
||||
/// <summary>Gets or sets whether the wide preset is selected.</summary>
|
||||
[ObservableProperty]
|
||||
private bool isWide;
|
||||
|
||||
/// <summary>Gets or sets whether the manual width is selected.</summary>
|
||||
[ObservableProperty]
|
||||
private bool isCustom;
|
||||
|
||||
/// <summary>Gets or sets the manual width in pixels; <see langword="null"/> while the box is empty.</summary>
|
||||
[ObservableProperty]
|
||||
private decimal? customPixels;
|
||||
|
||||
/// <summary>
|
||||
/// Commits the selection to the live settings and closes.
|
||||
/// </summary>
|
||||
[RelayCommand]
|
||||
private void Confirm()
|
||||
{
|
||||
if (IsCustom)
|
||||
{
|
||||
int pixels = (int)Math.Clamp(CustomPixels ?? _settings.CustomPixels, AppConfig.MinColumnPixels, AppConfig.MaxColumnPixels);
|
||||
_settings.Preset = ColumnWidthPreset.Custom;
|
||||
_settings.CustomPixels = pixels;
|
||||
}
|
||||
else
|
||||
{
|
||||
_settings.Preset = IsNarrow ? ColumnWidthPreset.Narrow
|
||||
: IsWide ? ColumnWidthPreset.Wide
|
||||
: ColumnWidthPreset.Standard;
|
||||
}
|
||||
Close(true);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Closes without changing anything.
|
||||
/// </summary>
|
||||
[RelayCommand]
|
||||
private Task CancelAsync() => RequestCancelAsync();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Pixel widths of the column width presets.
|
||||
/// </summary>
|
||||
public static class ColumnWidths
|
||||
{
|
||||
/// <summary>The narrow preset width.</summary>
|
||||
public const int Narrow = 240;
|
||||
|
||||
/// <summary>The standard (default) preset width.</summary>
|
||||
public const int Standard = 320;
|
||||
|
||||
/// <summary>The wide preset width.</summary>
|
||||
public const int Wide = 480;
|
||||
|
||||
/// <summary>
|
||||
/// Resolves the effective column width of the settings.
|
||||
/// </summary>
|
||||
/// <param name="settings">The column width settings.</param>
|
||||
/// <returns>The width in pixels.</returns>
|
||||
public static int Resolve(ColumnWidthSettings settings) => settings.Preset switch
|
||||
{
|
||||
ColumnWidthPreset.Narrow => Narrow,
|
||||
ColumnWidthPreset.Wide => Wide,
|
||||
ColumnWidthPreset.Custom => Math.Clamp(settings.CustomPixels, AppConfig.MinColumnPixels, AppConfig.MaxColumnPixels),
|
||||
_ => Standard,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
using CommunityToolkit.Mvvm.Input;
|
||||
|
||||
namespace YKanBan.ViewModels.Dialogs;
|
||||
|
||||
/// <summary>
|
||||
/// A yes/no confirmation: a message, a confirming button with an action
|
||||
/// specific label (for example "Delete") and a cancel button.
|
||||
/// </summary>
|
||||
public sealed partial class ConfirmDialogViewModel : DialogViewModelBase
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes the confirmation.
|
||||
/// </summary>
|
||||
/// <param name="message">The localized question.</param>
|
||||
/// <param name="confirmLabel">The localized label of the confirming button.</param>
|
||||
public ConfirmDialogViewModel(string message, string confirmLabel)
|
||||
{
|
||||
Message = message;
|
||||
ConfirmLabel = confirmLabel;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the localized question.
|
||||
/// </summary>
|
||||
public string Message { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the localized label of the confirming button.
|
||||
/// </summary>
|
||||
public string ConfirmLabel { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Closes with a positive result.
|
||||
/// </summary>
|
||||
[RelayCommand]
|
||||
private void Confirm() => Close(true);
|
||||
|
||||
/// <summary>
|
||||
/// Closes with a negative result.
|
||||
/// </summary>
|
||||
[RelayCommand]
|
||||
private Task CancelAsync() => RequestCancelAsync();
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
namespace YKanBan.ViewModels.Dialogs;
|
||||
|
||||
/// <summary>
|
||||
/// Base class for modal dialog view models shown through <see cref="IDialogService"/>.
|
||||
/// The dialog decides when it closes: it raises <see cref="CloseRequested"/>
|
||||
/// with its result, and a close attempted by the window itself (title-bar close
|
||||
/// button, Escape) is routed to <see cref="RequestCancelAsync"/> so that the
|
||||
/// dialog can veto it, for example to ask before discarding edits.
|
||||
/// </summary>
|
||||
public abstract class DialogViewModelBase : ViewModelBase
|
||||
{
|
||||
/// <summary>
|
||||
/// Raised when the dialog wants to close; the argument is the dialog result.
|
||||
/// </summary>
|
||||
public event EventHandler<bool>? CloseRequested;
|
||||
|
||||
/// <summary>
|
||||
/// Handles a cancel request coming from the window (or a cancel button).
|
||||
/// The default closes immediately with a negative result.
|
||||
/// </summary>
|
||||
/// <returns>A task completing once the request has been handled.</returns>
|
||||
public virtual Task RequestCancelAsync()
|
||||
{
|
||||
Close(false);
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asks the hosting window to close with the given result.
|
||||
/// </summary>
|
||||
/// <param name="result">The dialog result.</param>
|
||||
protected void Close(bool result) => CloseRequested?.Invoke(this, result);
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
namespace YKanBan.ViewModels.Dialogs;
|
||||
|
||||
/// <summary>
|
||||
/// Opens modal dialogs on behalf of view models, which never reference views.
|
||||
/// Every dialog is owned by the top-most open window, so a dialog opened from
|
||||
/// inside another dialog (nested modal) is centered on and blocks that dialog.
|
||||
/// </summary>
|
||||
public interface IDialogService
|
||||
{
|
||||
/// <summary>
|
||||
/// Shows a dialog modally and waits until it closes.
|
||||
/// </summary>
|
||||
/// <param name="dialog">The dialog view model; its window is resolved by naming convention.</param>
|
||||
/// <returns>The dialog result: <see langword="true"/> when it was accepted.</returns>
|
||||
Task<bool> ShowAsync(DialogViewModelBase dialog);
|
||||
|
||||
/// <summary>
|
||||
/// Shows the system save-file dialog for a Markdown file.
|
||||
/// </summary>
|
||||
/// <param name="suggestedFileName">The proposed file name.</param>
|
||||
/// <returns>The chosen local path, or <see langword="null"/> when the user cancelled.</returns>
|
||||
Task<string?> PickSaveFilePathAsync(string suggestedFileName);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Convenience wrappers for the plain confirmation and message dialogs.
|
||||
/// </summary>
|
||||
public static class DialogServiceExtensions
|
||||
{
|
||||
/// <summary>
|
||||
/// Asks a yes/no question.
|
||||
/// </summary>
|
||||
/// <param name="dialogs">The dialog service.</param>
|
||||
/// <param name="message">The localized question.</param>
|
||||
/// <param name="confirmLabel">The localized label of the confirming button.</param>
|
||||
/// <returns><see langword="true"/> when the user confirmed.</returns>
|
||||
public static Task<bool> ConfirmAsync(this IDialogService dialogs, string message, string confirmLabel) =>
|
||||
dialogs.ShowAsync(new ConfirmDialogViewModel(message, confirmLabel));
|
||||
|
||||
/// <summary>
|
||||
/// Shows an informational message with an optional read-only details block.
|
||||
/// </summary>
|
||||
/// <param name="dialogs">The dialog service.</param>
|
||||
/// <param name="title">The localized window title.</param>
|
||||
/// <param name="message">The localized message.</param>
|
||||
/// <param name="details">Untranslated diagnostic details, or <see langword="null"/>.</param>
|
||||
/// <returns>A task completing when the dialog closes.</returns>
|
||||
public static Task ShowMessageAsync(this IDialogService dialogs, string title, string message, string? details = null) =>
|
||||
dialogs.ShowAsync(new MessageDialogViewModel(title, message, details));
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
using CommunityToolkit.Mvvm.Input;
|
||||
|
||||
namespace YKanBan.ViewModels.Dialogs;
|
||||
|
||||
/// <summary>
|
||||
/// A purely informational dialog with a single OK button: a localized message
|
||||
/// plus optional untranslated, copyable diagnostic details.
|
||||
/// </summary>
|
||||
public sealed partial class MessageDialogViewModel : DialogViewModelBase
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes the message.
|
||||
/// </summary>
|
||||
/// <param name="title">The localized window title.</param>
|
||||
/// <param name="message">The localized message.</param>
|
||||
/// <param name="details">Untranslated diagnostic details, or <see langword="null"/>.</param>
|
||||
public MessageDialogViewModel(string title, string message, string? details)
|
||||
{
|
||||
Title = title;
|
||||
Message = message;
|
||||
Details = details;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the localized window title.
|
||||
/// </summary>
|
||||
public string Title { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the localized message.
|
||||
/// </summary>
|
||||
public string Message { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the diagnostic details, or <see langword="null"/> when there are none.
|
||||
/// </summary>
|
||||
public string? Details { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets whether a details block is shown.
|
||||
/// </summary>
|
||||
public bool HasDetails => !string.IsNullOrEmpty(Details);
|
||||
|
||||
/// <summary>
|
||||
/// Closes the dialog.
|
||||
/// </summary>
|
||||
[RelayCommand]
|
||||
private void Ok() => Close(true);
|
||||
}
|
||||
@@ -26,7 +26,7 @@ public sealed partial class SettingsDialogViewModel : ViewModelBase
|
||||
Languages =
|
||||
[
|
||||
new OptionItem(AppConfig.DefaultLanguage, Resources.Settings_LanguageEnglish),
|
||||
new OptionItem("zh-Hans", Resources.Settings_LanguageChinese),
|
||||
new OptionItem(AppConfig.SimplifiedChineseLanguage, Resources.Settings_LanguageChinese),
|
||||
];
|
||||
selectedLanguage = Languages.FirstOrDefault(option => (string)option.Value == _config.Language)
|
||||
?? Languages[0];
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
using YKanBan.Models;
|
||||
|
||||
namespace YKanBan.ViewModels.Dialogs;
|
||||
|
||||
/// <summary>
|
||||
/// The default colors proposed for new tags, shared by the tag picker and the
|
||||
/// tag editor.
|
||||
/// </summary>
|
||||
public static class TagColors
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the palette, offered as swatches and cycled for new-tag defaults.
|
||||
/// </summary>
|
||||
public static IReadOnlyList<RgbColor> Palette { get; } =
|
||||
[
|
||||
new(0xd7, 0x3a, 0x4a), new(0x00, 0x75, 0xca), new(0x0e, 0x8a, 0x16), new(0xfb, 0xca, 0x04),
|
||||
new(0x7c, 0x3a, 0xed), new(0xe9, 0x9b, 0x3c), new(0x00, 0x8b, 0x8b), new(0xcf, 0xd3, 0xd7),
|
||||
];
|
||||
|
||||
/// <summary>
|
||||
/// Returns the default color of a new tag, cycled by the number of existing tags.
|
||||
/// </summary>
|
||||
/// <param name="existingCount">The number of tags already in the workspace.</param>
|
||||
/// <returns>The proposed color.</returns>
|
||||
public static RgbColor DefaultFor(int existingCount) => Palette[existingCount % Palette.Count];
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
using Avalonia.Media;
|
||||
using Avalonia.Media.Immutable;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using CommunityToolkit.Mvvm.Input;
|
||||
using YKanBan.Models;
|
||||
|
||||
namespace YKanBan.ViewModels.Dialogs;
|
||||
|
||||
/// <summary>
|
||||
/// The new-tag / edit-tag dialog of the tags tab: name (required, not trimmed),
|
||||
/// #RRGGBB color with palette swatches and a live preview, and an optional
|
||||
/// description. Confirming writes through the supplied save callback; an invalid
|
||||
/// color or a schema-constraint violation (empty or duplicate name) is shown
|
||||
/// inside the dialog, which stays open with the user's input intact.
|
||||
/// </summary>
|
||||
public sealed partial class TagEditorDialogViewModel : DialogViewModelBase
|
||||
{
|
||||
private readonly Action<string, RgbColor, string> _save;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes the dialog.
|
||||
/// </summary>
|
||||
/// <param name="existing">The tag being edited, or <see langword="null"/> for a new tag.</param>
|
||||
/// <param name="defaultColor">The color proposed for a new tag.</param>
|
||||
/// <param name="save">Writes the name, color and description; throws the repository's typed exceptions.</param>
|
||||
public TagEditorDialogViewModel(TagModel? existing, RgbColor defaultColor, Action<string, RgbColor, string> save)
|
||||
{
|
||||
_save = save;
|
||||
Title = existing is null ? Resources.TagEditor_TitleNew : Resources.TagEditor_TitleEdit;
|
||||
name = existing?.Name ?? "";
|
||||
color = (existing?.Color ?? defaultColor).ToString();
|
||||
description = existing?.Description ?? "";
|
||||
Swatches = TagColors.Palette.Select(swatch => new ColorSwatch(swatch.ToString(), ToBrush(swatch))).ToList();
|
||||
UpdateColorPreview();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the localized window title.
|
||||
/// </summary>
|
||||
public string Title { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the palette swatches; clicking one sets <see cref="Color"/>.
|
||||
/// </summary>
|
||||
public IReadOnlyList<ColorSwatch> Swatches { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the tag name being edited (not trimmed).
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private string name;
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the #RRGGBB color text being edited.
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private string color;
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the tag description being edited.
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private string description;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the preview of <see cref="Color"/>, transparent while it is not valid.
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private IBrush colorPreview = Brushes.Transparent;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the localized error of the last confirmation, or <see langword="null"/>.
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
[NotifyPropertyChangedFor(nameof(HasError))]
|
||||
private string? errorMessage;
|
||||
|
||||
/// <summary>
|
||||
/// Gets whether an error is shown.
|
||||
/// </summary>
|
||||
public bool HasError => ErrorMessage is not null;
|
||||
|
||||
/// <summary>
|
||||
/// Takes a swatch color.
|
||||
/// </summary>
|
||||
/// <param name="hex">The swatch's #RRGGBB text.</param>
|
||||
[RelayCommand]
|
||||
private void PickSwatch(string hex) => Color = hex;
|
||||
|
||||
/// <summary>
|
||||
/// Writes the tag; closes on success, otherwise shows the error.
|
||||
/// </summary>
|
||||
[RelayCommand]
|
||||
private void Confirm()
|
||||
{
|
||||
if (!RgbColor.TryParse(Color, out RgbColor parsed))
|
||||
{
|
||||
ErrorMessage = Resources.Error_Tag_InvalidColor;
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
_save(Name, parsed, Description);
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
ErrorMessage = WriteErrorMessages.Describe(exception);
|
||||
return;
|
||||
}
|
||||
Close(true);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Closes without writing.
|
||||
/// </summary>
|
||||
[RelayCommand]
|
||||
private Task CancelAsync() => RequestCancelAsync();
|
||||
|
||||
/// <summary>
|
||||
/// Refreshes the color preview.
|
||||
/// </summary>
|
||||
/// <param name="value">The new color text.</param>
|
||||
partial void OnColorChanged(string value) => UpdateColorPreview();
|
||||
|
||||
/// <summary>
|
||||
/// Recomputes <see cref="ColorPreview"/> from <see cref="Color"/>.
|
||||
/// </summary>
|
||||
private void UpdateColorPreview() =>
|
||||
ColorPreview = RgbColor.TryParse(Color, out RgbColor parsed) ? ToBrush(parsed) : Brushes.Transparent;
|
||||
|
||||
/// <summary>
|
||||
/// Creates the thread-agnostic brush of a tag color.
|
||||
/// </summary>
|
||||
/// <param name="value">The color.</param>
|
||||
/// <returns>The brush.</returns>
|
||||
private static IBrush ToBrush(RgbColor value) =>
|
||||
new ImmutableSolidColorBrush(Avalonia.Media.Color.FromRgb(value.R, value.G, value.B));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A palette swatch of the tag editor.
|
||||
/// </summary>
|
||||
/// <param name="Hex">The #RRGGBB text.</param>
|
||||
/// <param name="Brush">The fill.</param>
|
||||
public sealed record ColorSwatch(string Hex, IBrush Brush);
|
||||
@@ -0,0 +1,176 @@
|
||||
using System.Collections.ObjectModel;
|
||||
using Avalonia.Media;
|
||||
using Avalonia.Media.Immutable;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using CommunityToolkit.Mvvm.Input;
|
||||
using YKanBan.Models;
|
||||
using YKanBan.Storage;
|
||||
using YKanBan.Storage.Workspace;
|
||||
using YKanBan.ViewModels.Board;
|
||||
|
||||
namespace YKanBan.ViewModels.Dialogs;
|
||||
|
||||
/// <summary>
|
||||
/// The nested "add tag" modal of the card editor: a filterable list of the
|
||||
/// existing tags not yet on the card, plus a new-tag entry. Picking a tag closes
|
||||
/// the dialog with it as <see cref="PickedTag"/>.
|
||||
///
|
||||
/// Exception to the edit-dialog unit of work: a tag created here is written to
|
||||
/// the tags table immediately (tags are global entities), so it survives even
|
||||
/// when the outer card edit is cancelled — only the assignment is discarded.
|
||||
/// </summary>
|
||||
public sealed partial class TagPickerDialogViewModel : DialogViewModelBase
|
||||
{
|
||||
private readonly WorkspaceRepository _repository;
|
||||
private readonly IReadOnlyList<TagBadgeViewModel> _available;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes the picker.
|
||||
/// </summary>
|
||||
/// <param name="repository">The workspace repository; new tags are written through it immediately.</param>
|
||||
/// <param name="assignedTagIds">The tags already on the card, which are not offered again.</param>
|
||||
public TagPickerDialogViewModel(WorkspaceRepository repository, IReadOnlyCollection<long> assignedTagIds)
|
||||
{
|
||||
_repository = repository;
|
||||
IReadOnlyList<TagModel> all = repository.GetTags();
|
||||
_available = all
|
||||
.Where(tag => !assignedTagIds.Contains(tag.Id))
|
||||
.Select(tag => new TagBadgeViewModel(tag))
|
||||
.ToList();
|
||||
FilteredTags = new ObservableCollection<TagBadgeViewModel>(_available);
|
||||
|
||||
newColor = TagColors.DefaultFor(all.Count).ToString();
|
||||
UpdateColorPreview();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the tag the user picked or created, once the dialog closed positively.
|
||||
/// </summary>
|
||||
public TagModel? PickedTag { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the available tags matching <see cref="FilterText"/>.
|
||||
/// </summary>
|
||||
public ObservableCollection<TagBadgeViewModel> FilteredTags { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets whether no available tag matches the filter.
|
||||
/// </summary>
|
||||
public bool NoMatches => FilteredTags.Count == 0;
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the list filter: a case-insensitive substring of the tag name.
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private string filterText = "";
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the name of the tag to create (not trimmed).
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private string newName = "";
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the #RRGGBB color text of the tag to create.
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private string newColor;
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the description of the tag to create.
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private string newDescription = "";
|
||||
|
||||
/// <summary>
|
||||
/// Gets the preview of <see cref="NewColor"/>, transparent while it is not valid.
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private IBrush newColorPreview = Brushes.Transparent;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the localized error of the last create attempt, or <see langword="null"/>.
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
[NotifyPropertyChangedFor(nameof(HasError))]
|
||||
private string? errorMessage;
|
||||
|
||||
/// <summary>
|
||||
/// Gets whether an error is shown.
|
||||
/// </summary>
|
||||
public bool HasError => ErrorMessage is not null;
|
||||
|
||||
/// <summary>
|
||||
/// Picks an existing tag and closes.
|
||||
/// </summary>
|
||||
/// <param name="tag">The picked tag.</param>
|
||||
[RelayCommand]
|
||||
private void Pick(TagBadgeViewModel tag)
|
||||
{
|
||||
PickedTag = tag.Tag;
|
||||
Close(true);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates the new tag right away and closes with it picked; constraint
|
||||
/// violations and an invalid color keep the dialog open with an error.
|
||||
/// </summary>
|
||||
[RelayCommand]
|
||||
private void Create()
|
||||
{
|
||||
if (!RgbColor.TryParse(NewColor, out RgbColor color))
|
||||
{
|
||||
ErrorMessage = Resources.Error_Tag_InvalidColor;
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
PickedTag = _repository.AddTag(NewName, color, NewDescription);
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
ErrorMessage = WriteErrorMessages.Describe(exception);
|
||||
return;
|
||||
}
|
||||
Close(true);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Closes without picking anything.
|
||||
/// </summary>
|
||||
[RelayCommand]
|
||||
private Task CancelAsync() => RequestCancelAsync();
|
||||
|
||||
/// <summary>
|
||||
/// Re-filters the list.
|
||||
/// </summary>
|
||||
/// <param name="value">The new filter text.</param>
|
||||
partial void OnFilterTextChanged(string value)
|
||||
{
|
||||
string folded = SqliteDatabase.Fold(value);
|
||||
FilteredTags.Clear();
|
||||
foreach (TagBadgeViewModel tag in _available)
|
||||
{
|
||||
if (SqliteDatabase.Fold(tag.Name).Contains(folded, StringComparison.Ordinal))
|
||||
{
|
||||
FilteredTags.Add(tag);
|
||||
}
|
||||
}
|
||||
OnPropertyChanged(nameof(NoMatches));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Refreshes the color preview.
|
||||
/// </summary>
|
||||
/// <param name="value">The new color text.</param>
|
||||
partial void OnNewColorChanged(string value) => UpdateColorPreview();
|
||||
|
||||
/// <summary>
|
||||
/// Recomputes <see cref="NewColorPreview"/> from <see cref="NewColor"/>.
|
||||
/// </summary>
|
||||
private void UpdateColorPreview() =>
|
||||
NewColorPreview = RgbColor.TryParse(NewColor, out RgbColor color)
|
||||
? new ImmutableSolidColorBrush(Color.FromRgb(color.R, color.G, color.B))
|
||||
: Brushes.Transparent;
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
using System.Globalization;
|
||||
using YKanBan.Storage;
|
||||
|
||||
namespace YKanBan.ViewModels.Dialogs;
|
||||
|
||||
/// <summary>
|
||||
/// Maps a failed dialog write to the localized message shown inside the dialog
|
||||
/// that attempted it (the dialog stays open and keeps the user's input). The
|
||||
/// typed schema-constraint exceptions get dedicated messages; anything else
|
||||
/// gets a generic one carrying the untranslated exception message.
|
||||
/// </summary>
|
||||
public static class WriteErrorMessages
|
||||
{
|
||||
/// <summary>
|
||||
/// Returns the localized message for a failed write.
|
||||
/// </summary>
|
||||
/// <param name="exception">The exception thrown by the write.</param>
|
||||
/// <returns>The localized message.</returns>
|
||||
public static string Describe(Exception exception)
|
||||
{
|
||||
CultureInfo? culture = Resources.Culture;
|
||||
return exception switch
|
||||
{
|
||||
NameRequiredException { Entity: NamedEntity.Column } => Resources.Error_Column_TitleRequired,
|
||||
NameRequiredException { Entity: NamedEntity.Tag } => Resources.Error_Tag_NameRequired,
|
||||
DuplicateNameException { Entity: NamedEntity.Column } duplicate =>
|
||||
string.Format(culture, Resources.Error_Column_Duplicate, duplicate.Name),
|
||||
DuplicateNameException { Entity: NamedEntity.Tag } duplicate =>
|
||||
string.Format(culture, Resources.Error_Tag_Duplicate, duplicate.Name),
|
||||
_ => string.Format(culture, Resources.Error_SaveFailed, exception.Message),
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
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, an 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),
|
||||
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),
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@ using YKanBan.Launching;
|
||||
using YKanBan.Services;
|
||||
using YKanBan.Storage;
|
||||
using YKanBan.Storage.Workspace;
|
||||
using YKanBan.ViewModels.Dialogs;
|
||||
using YKanBan.ViewModels.ErrorPages;
|
||||
|
||||
namespace YKanBan.ViewModels;
|
||||
@@ -16,15 +17,18 @@ namespace YKanBan.ViewModels;
|
||||
public sealed partial class MainWindowViewModel : ViewModelBase
|
||||
{
|
||||
private readonly AppServices _services;
|
||||
private readonly IDialogService _dialogs;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes the view model and resolves the workspace state.
|
||||
/// </summary>
|
||||
/// <param name="services">The process composition root.</param>
|
||||
/// <param name="dialogs">The modal dialog service used by the board.</param>
|
||||
/// <param name="arguments">The command-line arguments (excluding the executable).</param>
|
||||
public MainWindowViewModel(AppServices services, IReadOnlyList<string> arguments)
|
||||
public MainWindowViewModel(AppServices services, IDialogService dialogs, IReadOnlyList<string> arguments)
|
||||
{
|
||||
_services = services;
|
||||
_dialogs = dialogs;
|
||||
ShowSettings = new Interaction<Unit>();
|
||||
ShowAbout = new Interaction<Unit>();
|
||||
InitializeWorkspace = new Interaction<Unit>();
|
||||
@@ -89,6 +93,12 @@ public sealed partial class MainWindowViewModel : ViewModelBase
|
||||
{
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -98,7 +108,7 @@ public sealed partial class MainWindowViewModel : ViewModelBase
|
||||
private void OpenWorkspace(string folderPath)
|
||||
{
|
||||
WorkspaceSession session = _services.OpenWorkspace(folderPath);
|
||||
Content = new WorkspaceViewModel(session, ShowSettings, ShowAbout);
|
||||
Content = new WorkspaceViewModel(session, ShowSettings, ShowAbout, _services.Config, _dialogs);
|
||||
Title = $"{new DirectoryInfo(folderPath).Name} - {Resources.App_Name}";
|
||||
}
|
||||
|
||||
@@ -120,10 +130,11 @@ public sealed partial class MainWindowViewModel : ViewModelBase
|
||||
WorkspacePreset.AddPresetColumns(page.FolderPath);
|
||||
OpenWorkspace(page.FolderPath);
|
||||
}
|
||||
catch (Exception exception) when (exception is YKanBanException or IOException or UnauthorizedAccessException)
|
||||
catch (Exception exception)
|
||||
{
|
||||
// Initialization failed; the page remains so the user can retry.
|
||||
// Initialization failed: switch to the open-failed page, which has no operations.
|
||||
Debug.WriteLine(exception);
|
||||
Content = new OpenFailedPageViewModel(page.FolderPath, exception);
|
||||
}
|
||||
|
||||
return Task.CompletedTask;
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
using CommunityToolkit.Mvvm.Input;
|
||||
using YKanBan.Models;
|
||||
using YKanBan.ViewModels.Board;
|
||||
|
||||
namespace YKanBan.ViewModels.Tags;
|
||||
|
||||
/// <summary>
|
||||
/// One row of the tags tab: the colored badge, the description and the usage
|
||||
/// count, with edit and delete actions.
|
||||
/// </summary>
|
||||
public sealed partial class TagRowViewModel : ViewModelBase
|
||||
{
|
||||
private readonly TagsViewModel _owner;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes the row.
|
||||
/// </summary>
|
||||
/// <param name="owner">The tags tab performing the actions.</param>
|
||||
/// <param name="tag">The tag shown.</param>
|
||||
/// <param name="usageCount">The number of cards carrying the tag.</param>
|
||||
public TagRowViewModel(TagsViewModel owner, TagModel tag, long usageCount)
|
||||
{
|
||||
_owner = owner;
|
||||
Tag = tag;
|
||||
Badge = new TagBadgeViewModel(tag);
|
||||
UsageCount = usageCount;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the tag shown.
|
||||
/// </summary>
|
||||
public TagModel Tag { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the colored badge (color + name).
|
||||
/// </summary>
|
||||
public TagBadgeViewModel Badge { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the tag description.
|
||||
/// </summary>
|
||||
public string Description => Tag.Description;
|
||||
|
||||
/// <summary>
|
||||
/// Gets whether the tag has a description.
|
||||
/// </summary>
|
||||
public bool HasDescription => Tag.Description.Length > 0;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the #RRGGBB color text.
|
||||
/// </summary>
|
||||
public string ColorText => Tag.Color.ToString();
|
||||
|
||||
/// <summary>
|
||||
/// Gets the number of cards carrying the tag.
|
||||
/// </summary>
|
||||
public long UsageCount { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the localized usage count, for example "3 cards".
|
||||
/// </summary>
|
||||
public string UsageText => string.Format(Resources.Culture, Resources.Tags_UsageCount, UsageCount);
|
||||
|
||||
/// <summary>
|
||||
/// Opens the edit dialog.
|
||||
/// </summary>
|
||||
/// <returns>A task completing when the dialog closes.</returns>
|
||||
[RelayCommand]
|
||||
private Task EditAsync() => _owner.EditTagAsync(Tag);
|
||||
|
||||
/// <summary>
|
||||
/// Deletes the tag.
|
||||
/// </summary>
|
||||
/// <returns>A task completing when the tag is deleted or the deletion was declined.</returns>
|
||||
[RelayCommand]
|
||||
private Task DeleteAsync() => _owner.DeleteTagAsync(Tag, UsageCount);
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
using System.Collections.ObjectModel;
|
||||
using System.Diagnostics;
|
||||
using CommunityToolkit.Mvvm.Input;
|
||||
using YKanBan.Models;
|
||||
using YKanBan.Storage.AppData;
|
||||
using YKanBan.Storage.Workspace;
|
||||
using YKanBan.ViewModels.Dialogs;
|
||||
|
||||
namespace YKanBan.ViewModels.Tags;
|
||||
|
||||
/// <summary>
|
||||
/// The tags tab, a tag manager in the style of the GitHub issue labels page:
|
||||
/// every tag with its color, name, description and usage count, plus creating,
|
||||
/// editing (rename, recolor, describe) and deleting tags. Unreferenced tags are
|
||||
/// never cleaned up automatically, so this is where they are removed.
|
||||
/// </summary>
|
||||
public sealed partial class TagsViewModel : ViewModelBase
|
||||
{
|
||||
private readonly WorkspaceRepository _repository;
|
||||
private readonly AppConfig _config;
|
||||
private readonly IDialogService _dialogs;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes the tab and loads it.
|
||||
/// </summary>
|
||||
/// <param name="repository">The workspace repository.</param>
|
||||
/// <param name="config">The live application configuration (delete confirmation).</param>
|
||||
/// <param name="dialogs">The modal dialog service.</param>
|
||||
public TagsViewModel(WorkspaceRepository repository, AppConfig config, IDialogService dialogs)
|
||||
{
|
||||
_repository = repository;
|
||||
_config = config;
|
||||
_dialogs = dialogs;
|
||||
Refresh();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Raised after every tag write, so the board can show the new names and colors.
|
||||
/// </summary>
|
||||
public event EventHandler? TagsChanged;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the tags in id order.
|
||||
/// </summary>
|
||||
public ObservableCollection<TagRowViewModel> Tags { get; } = [];
|
||||
|
||||
/// <summary>
|
||||
/// Gets the localized total, for example "3 tags".
|
||||
/// </summary>
|
||||
public string Summary => string.Format(Resources.Culture, Resources.Tags_Summary, Tags.Count);
|
||||
|
||||
/// <summary>
|
||||
/// Gets whether the workspace has no tags yet.
|
||||
/// </summary>
|
||||
public bool IsEmpty => Tags.Count == 0;
|
||||
|
||||
/// <summary>
|
||||
/// Reloads the tags with their usage counts.
|
||||
/// </summary>
|
||||
public void Refresh()
|
||||
{
|
||||
Tags.Clear();
|
||||
foreach ((TagModel tag, long usage) in _repository.GetTagsWithUsage())
|
||||
{
|
||||
Tags.Add(new TagRowViewModel(this, tag, usage));
|
||||
}
|
||||
OnPropertyChanged(nameof(Summary));
|
||||
OnPropertyChanged(nameof(IsEmpty));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Opens the new-tag dialog.
|
||||
/// </summary>
|
||||
/// <returns>A task completing when the dialog closes.</returns>
|
||||
[RelayCommand]
|
||||
private async Task AddTagAsync()
|
||||
{
|
||||
var dialog = new TagEditorDialogViewModel(
|
||||
null,
|
||||
TagColors.DefaultFor(Tags.Count),
|
||||
(name, color, description) => _repository.AddTag(name, color, description));
|
||||
if (await _dialogs.ShowAsync(dialog))
|
||||
{
|
||||
AfterWrite();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Opens the edit-tag dialog.
|
||||
/// </summary>
|
||||
/// <param name="tag">The tag to edit.</param>
|
||||
/// <returns>A task completing when the dialog closes.</returns>
|
||||
internal async Task EditTagAsync(TagModel tag)
|
||||
{
|
||||
var dialog = new TagEditorDialogViewModel(
|
||||
tag,
|
||||
tag.Color,
|
||||
(name, color, description) => _repository.UpdateTag(tag.Id, name, color, description));
|
||||
if (await _dialogs.ShowAsync(dialog))
|
||||
{
|
||||
AfterWrite();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deletes a tag (removing it from its cards), asking first when that
|
||||
/// confirmation is enabled.
|
||||
/// </summary>
|
||||
/// <param name="tag">The tag to delete.</param>
|
||||
/// <param name="usageCount">The number of cards carrying it.</param>
|
||||
/// <returns>A task completing when the tag is deleted or the deletion was declined.</returns>
|
||||
internal async Task DeleteTagAsync(TagModel tag, long usageCount)
|
||||
{
|
||||
if (_config.Confirmations.DeleteTag)
|
||||
{
|
||||
string message = string.Format(Resources.Culture, Resources.Confirm_DeleteTag, tag.Name, usageCount);
|
||||
if (!await _dialogs.ConfirmAsync(message, Resources.Common_Delete))
|
||||
{
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
_repository.DeleteTag(tag.Id);
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
Debug.WriteLine(exception);
|
||||
await _dialogs.ShowMessageAsync(
|
||||
Resources.Error_Operation_Title, Resources.Error_Operation_Message, exception.Message);
|
||||
}
|
||||
AfterWrite();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reloads the list and tells the board that tags changed.
|
||||
/// </summary>
|
||||
private void AfterWrite()
|
||||
{
|
||||
Refresh();
|
||||
TagsChanged?.Invoke(this, EventArgs.Empty);
|
||||
}
|
||||
}
|
||||
@@ -1,17 +1,26 @@
|
||||
using System.Diagnostics;
|
||||
using System.Text;
|
||||
using CommunityToolkit.Mvvm.Input;
|
||||
using YKanBan.Export;
|
||||
using YKanBan.Storage.AppData;
|
||||
using YKanBan.Storage.Workspace;
|
||||
using YKanBan.ViewModels.Board;
|
||||
using YKanBan.ViewModels.Dialogs;
|
||||
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. A write on either
|
||||
/// tab refreshes the other: tag edits change the board's badges and filter
|
||||
/// matches, card edits change the tags' usage counts.
|
||||
/// </summary>
|
||||
public sealed partial class WorkspaceViewModel : ViewModelBase
|
||||
{
|
||||
private readonly Interaction<Unit> _showSettings;
|
||||
private readonly Interaction<Unit> _showAbout;
|
||||
private readonly IDialogService _dialogs;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes the view for an open workspace.
|
||||
@@ -19,16 +28,25 @@ public sealed partial class WorkspaceViewModel : ViewModelBase
|
||||
/// <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>
|
||||
/// <param name="config">The live application configuration.</param>
|
||||
/// <param name="dialogs">The modal dialog service.</param>
|
||||
public WorkspaceViewModel(
|
||||
WorkspaceSession session,
|
||||
Interaction<Unit> showSettings,
|
||||
Interaction<Unit> showAbout)
|
||||
Interaction<Unit> showAbout,
|
||||
AppConfig config,
|
||||
IDialogService dialogs)
|
||||
{
|
||||
Session = session;
|
||||
WorkspaceName = new DirectoryInfo(session.FolderPath).Name;
|
||||
WorkspacePath = session.FolderPath;
|
||||
_showSettings = showSettings;
|
||||
_showAbout = showAbout;
|
||||
_dialogs = dialogs;
|
||||
Board = new BoardViewModel(session.Repository, config, dialogs);
|
||||
Tags = new TagsViewModel(session.Repository, config, dialogs);
|
||||
Board.DataWritten += (_, _) => Tags.Refresh();
|
||||
Tags.TagsChanged += (_, _) => Board.Refresh();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -46,6 +64,16 @@ public sealed partial class WorkspaceViewModel : ViewModelBase
|
||||
/// </summary>
|
||||
public string WorkspacePath { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the board tab.
|
||||
/// </summary>
|
||||
public BoardViewModel Board { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the tags tab.
|
||||
/// </summary>
|
||||
public TagsViewModel Tags { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Opens the settings dialog through the registered interaction.
|
||||
/// </summary>
|
||||
@@ -59,11 +87,32 @@ 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.
|
||||
/// Exports the whole workspace to a Markdown file chosen in the system save
|
||||
/// dialog. The export ignores the board's search filter and card sort; the
|
||||
/// default file name and all template text follow the UI language.
|
||||
/// </summary>
|
||||
/// <returns>A task completing when the file is written or the export was cancelled.</returns>
|
||||
[RelayCommand]
|
||||
private static void Export()
|
||||
private async Task ExportAsync()
|
||||
{
|
||||
DateTimeOffset exportedAt = DateTimeOffset.Now;
|
||||
string? path = await _dialogs.PickSaveFilePathAsync(MarkdownExporter.BuildFileName(WorkspaceName, exportedAt));
|
||||
if (path is null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
WorkspaceRepository repository = Session.Repository;
|
||||
string markdown = MarkdownExporter.Export(
|
||||
WorkspaceName, repository.GetColumns(), repository.GetCards(), repository.GetTagsWithUsage(), exportedAt);
|
||||
await File.WriteAllTextAsync(path, markdown, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false));
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
Debug.WriteLine(exception);
|
||||
await _dialogs.ShowMessageAsync(Resources.Export_Failed_Title, Resources.Export_Failed_Message, exception.Message);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,201 @@
|
||||
<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"
|
||||
x:Name="Root">
|
||||
|
||||
<Grid RowDefinitions="Auto,*" RowSpacing="8">
|
||||
|
||||
<!-- Toolbar: search bar on the left; new column, column width and card sort on the right. -->
|
||||
<Grid Grid.Row="0" ColumnDefinitions="*,Auto" ColumnSpacing="16">
|
||||
<StackPanel Grid.Column="0" Orientation="Horizontal" Spacing="8">
|
||||
<TextBox Text="{Binding SearchText}" Width="420"
|
||||
Watermark="{x:Static lang:Resources.Board_SearchWatermark}">
|
||||
<TextBox.KeyBindings>
|
||||
<KeyBinding Gesture="Enter" Command="{Binding SearchCommand}"/>
|
||||
</TextBox.KeyBindings>
|
||||
<TextBox.InnerLeftContent>
|
||||
<icons:PackIconLucide Kind="Search" Width="14" Height="14" Margin="8,0,0,0" Opacity="0.6"
|
||||
VerticalAlignment="Center"/>
|
||||
</TextBox.InnerLeftContent>
|
||||
<TextBox.InnerRightContent>
|
||||
<Button Command="{Binding ClearSearchCommand}" IsVisible="{Binding HasSearchText}"
|
||||
Theme="{StaticResource BorderlessButton}" Padding="6,0"
|
||||
MinHeight="0" Height="24" VerticalAlignment="Center"
|
||||
ToolTip.Tip="{x:Static lang:Resources.Board_ClearSearch}">
|
||||
<icons:PackIconLucide Kind="X" Width="14" Height="14"/>
|
||||
</Button>
|
||||
</TextBox.InnerRightContent>
|
||||
</TextBox>
|
||||
<Button Command="{Binding SearchCommand}" Classes="Primary">
|
||||
<TextBlock Text="{x:Static lang:Resources.Board_Search}"/>
|
||||
</Button>
|
||||
</StackPanel>
|
||||
<StackPanel Grid.Column="1" Orientation="Horizontal" Spacing="8">
|
||||
<Button Command="{Binding AddColumnCommand}">
|
||||
<StackPanel Orientation="Horizontal" Spacing="6">
|
||||
<icons:PackIconLucide Kind="Plus" Width="16" Height="16"/>
|
||||
<TextBlock Text="{x:Static lang:Resources.Board_AddColumn}"/>
|
||||
</StackPanel>
|
||||
</Button>
|
||||
<Button Command="{Binding AdjustColumnWidthCommand}">
|
||||
<StackPanel Orientation="Horizontal" Spacing="6">
|
||||
<icons:PackIconLucide Kind="MoveHorizontal" Width="16" Height="16"/>
|
||||
<TextBlock Text="{x:Static lang:Resources.Board_ColumnWidth}"/>
|
||||
</StackPanel>
|
||||
</Button>
|
||||
<ComboBox ItemsSource="{Binding SortOptions}" SelectedItem="{Binding SelectedSort}" MinWidth="160"
|
||||
ToolTip.Tip="{x:Static lang:Resources.Board_Sort}">
|
||||
<ComboBox.ItemTemplate>
|
||||
<DataTemplate x:DataType="vmBase:OptionItem">
|
||||
<TextBlock Text="{Binding Label}"/>
|
||||
</DataTemplate>
|
||||
</ComboBox.ItemTemplate>
|
||||
</ComboBox>
|
||||
</StackPanel>
|
||||
</Grid>
|
||||
|
||||
<!-- Columns left to right; each column scrolls its own virtualized card list. -->
|
||||
<ScrollViewer Grid.Row="1" HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Disabled">
|
||||
<ItemsControl ItemsSource="{Binding Columns}">
|
||||
<ItemsControl.ItemsPanel>
|
||||
<ItemsPanelTemplate>
|
||||
<StackPanel Orientation="Horizontal" Spacing="12"/>
|
||||
</ItemsPanelTemplate>
|
||||
</ItemsControl.ItemsPanel>
|
||||
<ItemsControl.ItemTemplate>
|
||||
<DataTemplate x:DataType="vm:ColumnViewModel">
|
||||
<Border Width="{Binding #Root.((vm:BoardViewModel)DataContext).ColumnWidth}"
|
||||
Background="{DynamicResource ColumnBackgroundBrush}"
|
||||
BorderBrush="{DynamicResource PanelBorderBrush}" BorderThickness="1"
|
||||
CornerRadius="6" Padding="8">
|
||||
<Grid RowDefinitions="Auto,*" RowSpacing="8">
|
||||
|
||||
<!-- Column header: title, count, description, new card, edit/delete menu. -->
|
||||
<Grid Grid.Row="0" ColumnDefinitions="*,Auto,Auto">
|
||||
<StackPanel Grid.Column="0" Spacing="2" VerticalAlignment="Center">
|
||||
<StackPanel Orientation="Horizontal" Spacing="6">
|
||||
<TextBlock Text="{Binding Title}" FontWeight="SemiBold"
|
||||
TextTrimming="CharacterEllipsis"/>
|
||||
<TextBlock Text="{Binding CardCount}" Opacity="0.6"/>
|
||||
</StackPanel>
|
||||
<TextBlock Text="{Binding Description}" IsVisible="{Binding HasDescription}"
|
||||
FontSize="12" Opacity="0.7" TextWrapping="Wrap" MaxLines="3"
|
||||
TextTrimming="CharacterEllipsis"/>
|
||||
</StackPanel>
|
||||
<Button Grid.Column="1" Command="{Binding AddCardCommand}" VerticalAlignment="Top"
|
||||
Theme="{StaticResource BorderlessButton}" Padding="4"
|
||||
ToolTip.Tip="{x:Static lang:Resources.Board_AddCard}">
|
||||
<icons:PackIconLucide Kind="Plus" Width="16" Height="16"/>
|
||||
</Button>
|
||||
<Button Grid.Column="2" VerticalAlignment="Top"
|
||||
Theme="{StaticResource BorderlessButton}" Padding="4"
|
||||
ToolTip.Tip="{x:Static lang:Resources.Menu_More}">
|
||||
<icons:PackIconLucide Kind="Ellipsis" Width="16" Height="16"/>
|
||||
<Button.Flyout>
|
||||
<MenuFlyout Placement="BottomEdgeAlignedRight">
|
||||
<MenuItem Header="{x:Static lang:Resources.Menu_Edit}" Command="{Binding EditCommand}"/>
|
||||
<MenuItem Header="{x:Static lang:Resources.Menu_Delete}" Command="{Binding DeleteCommand}"/>
|
||||
</MenuFlyout>
|
||||
</Button.Flyout>
|
||||
</Button>
|
||||
</Grid>
|
||||
|
||||
<!-- Cards top to bottom, UI-virtualized for large columns. -->
|
||||
<ItemsControl Grid.Row="1" ItemsSource="{Binding Cards}">
|
||||
<ItemsControl.Template>
|
||||
<ControlTemplate>
|
||||
<ScrollViewer HorizontalScrollBarVisibility="Disabled"
|
||||
VerticalScrollBarVisibility="Auto">
|
||||
<ItemsPresenter Name="PART_ItemsPresenter"
|
||||
ItemsPanel="{TemplateBinding ItemsPanel}"/>
|
||||
</ScrollViewer>
|
||||
</ControlTemplate>
|
||||
</ItemsControl.Template>
|
||||
<ItemsControl.ItemsPanel>
|
||||
<ItemsPanelTemplate>
|
||||
<VirtualizingStackPanel/>
|
||||
</ItemsPanelTemplate>
|
||||
</ItemsControl.ItemsPanel>
|
||||
<ItemsControl.ItemTemplate>
|
||||
<DataTemplate x:DataType="vm:CardViewModel">
|
||||
<Panel Margin="0,0,0,8">
|
||||
<!-- The card body opens the editor. -->
|
||||
<Button Command="{Binding EditCommand}"
|
||||
HorizontalAlignment="Stretch" HorizontalContentAlignment="Stretch"
|
||||
VerticalContentAlignment="Top"
|
||||
Background="{DynamicResource CardBackgroundBrush}"
|
||||
Foreground="{DynamicResource CardForegroundBrush}"
|
||||
FontWeight="Normal"
|
||||
BorderBrush="{DynamicResource PanelBorderBrush}" BorderThickness="1"
|
||||
CornerRadius="4" Padding="10,8" Cursor="Hand">
|
||||
<StackPanel Spacing="6">
|
||||
<TextBlock TextWrapping="Wrap" Margin="0,0,24,0">
|
||||
<Run Text="{Binding IdText}" FontWeight="Bold"/><Run Text="{Binding TitleSuffix}"/>
|
||||
</TextBlock>
|
||||
<TextBlock Text="{Binding Excerpt}" IsVisible="{Binding HasExcerpt}"
|
||||
TextWrapping="Wrap" FontSize="12" Opacity="0.8"
|
||||
FontWeight="Normal"/>
|
||||
<ItemsControl ItemsSource="{Binding Tags}" IsVisible="{Binding HasTags}">
|
||||
<ItemsControl.ItemsPanel>
|
||||
<ItemsPanelTemplate>
|
||||
<WrapPanel/>
|
||||
</ItemsPanelTemplate>
|
||||
</ItemsControl.ItemsPanel>
|
||||
<ItemsControl.ItemTemplate>
|
||||
<DataTemplate x:DataType="vm:TagBadgeViewModel">
|
||||
<Border Background="{Binding Background}" CornerRadius="10"
|
||||
Padding="8,1" Margin="0,0,4,4">
|
||||
<TextBlock Text="{Binding Name}" Foreground="{Binding Foreground}"
|
||||
FontSize="11" FontWeight="Normal"/>
|
||||
</Border>
|
||||
</DataTemplate>
|
||||
</ItemsControl.ItemTemplate>
|
||||
</ItemsControl>
|
||||
</StackPanel>
|
||||
</Button>
|
||||
|
||||
<!-- Card menu: delete, move to column. -->
|
||||
<Button HorizontalAlignment="Right" VerticalAlignment="Top" Margin="0,4,4,0"
|
||||
Theme="{StaticResource BorderlessButton}" Padding="4"
|
||||
ToolTip.Tip="{x:Static lang:Resources.Menu_More}">
|
||||
<icons:PackIconLucide Kind="Ellipsis" Width="14" Height="14"/>
|
||||
<Button.Flyout>
|
||||
<MenuFlyout Placement="BottomEdgeAlignedRight">
|
||||
<MenuItem Header="{x:Static lang:Resources.Menu_Delete}"
|
||||
Command="{Binding DeleteCommand}"/>
|
||||
<MenuItem Header="{x:Static lang:Resources.Menu_MoveTo}"
|
||||
ItemsSource="{Binding MoveTargets}">
|
||||
<MenuItem.ItemContainerTheme>
|
||||
<ControlTheme TargetType="MenuItem"
|
||||
BasedOn="{StaticResource {x:Type MenuItem}}"
|
||||
x:DataType="vm:MoveTargetViewModel">
|
||||
<Setter Property="Header" Value="{Binding Title}"/>
|
||||
<Setter Property="Command" Value="{Binding Command}"/>
|
||||
<Setter Property="CommandParameter" Value="{Binding ColumnId}"/>
|
||||
<Setter Property="IsEnabled" Value="{Binding IsEnabled}"/>
|
||||
</ControlTheme>
|
||||
</MenuItem.ItemContainerTheme>
|
||||
</MenuItem>
|
||||
</MenuFlyout>
|
||||
</Button.Flyout>
|
||||
</Button>
|
||||
</Panel>
|
||||
</DataTemplate>
|
||||
</ItemsControl.ItemTemplate>
|
||||
</ItemsControl>
|
||||
</Grid>
|
||||
</Border>
|
||||
</DataTemplate>
|
||||
</ItemsControl.ItemTemplate>
|
||||
</ItemsControl>
|
||||
</ScrollViewer>
|
||||
</Grid>
|
||||
</UserControl>
|
||||
@@ -0,0 +1,11 @@
|
||||
using Avalonia.Controls;
|
||||
|
||||
namespace YKanBan.Views.Board;
|
||||
|
||||
public partial class BoardView : UserControl
|
||||
{
|
||||
public BoardView()
|
||||
{
|
||||
InitializeComponent();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Platform.Storage;
|
||||
using YKanBan.ViewModels.Dialogs;
|
||||
using YKanBan.Views.Dialogs;
|
||||
|
||||
namespace YKanBan.Views;
|
||||
|
||||
/// <summary>
|
||||
/// Shows dialog view models as modal windows. A <c>XxxDialogViewModel</c> in
|
||||
/// <c>YKanBan.ViewModels.Dialogs</c> is shown by the <c>XxxDialog</c> window in
|
||||
/// <c>YKanBan.Views.Dialogs</c>. Each dialog is owned by the top-most open
|
||||
/// window, so nested modals (the tag picker inside the card editor, a discard
|
||||
/// confirmation above it) center on their direct parent.
|
||||
/// </summary>
|
||||
public sealed class DialogService : IDialogService
|
||||
{
|
||||
private readonly Stack<Window> _owners = new();
|
||||
|
||||
/// <summary>
|
||||
/// Sets the main window as the bottom of the owner stack.
|
||||
/// </summary>
|
||||
/// <param name="mainWindow">The main window.</param>
|
||||
public void Attach(Window mainWindow)
|
||||
{
|
||||
_owners.Clear();
|
||||
_owners.Push(mainWindow);
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public async Task<bool> ShowAsync(DialogViewModelBase dialog)
|
||||
{
|
||||
if (!_owners.TryPeek(out Window? owner))
|
||||
{
|
||||
throw new InvalidOperationException("The dialog service has no main window attached.");
|
||||
}
|
||||
|
||||
DialogWindow window = CreateWindow(dialog);
|
||||
window.DataContext = dialog;
|
||||
|
||||
// FlowDirection does not inherit across windows, so every modal gets it explicitly.
|
||||
window.FlowDirection = App.UiFlowDirection;
|
||||
|
||||
_owners.Push(window);
|
||||
try
|
||||
{
|
||||
return await window.ShowDialog<bool>(owner);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_owners.Pop();
|
||||
}
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public async Task<string?> PickSaveFilePathAsync(string suggestedFileName)
|
||||
{
|
||||
if (!_owners.TryPeek(out Window? owner))
|
||||
{
|
||||
throw new InvalidOperationException("The dialog service has no main window attached.");
|
||||
}
|
||||
|
||||
IStorageFile? file = await owner.StorageProvider.SaveFilePickerAsync(new FilePickerSaveOptions
|
||||
{
|
||||
SuggestedFileName = suggestedFileName,
|
||||
DefaultExtension = "md",
|
||||
ShowOverwritePrompt = true,
|
||||
FileTypeChoices =
|
||||
[
|
||||
new FilePickerFileType(YKanBan.Resources.Export_FileTypeMarkdown) { Patterns = ["*.md"] },
|
||||
],
|
||||
});
|
||||
return file?.TryGetLocalPath();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates the window class matching a dialog view model by naming convention.
|
||||
/// </summary>
|
||||
/// <param name="dialog">The dialog view model.</param>
|
||||
/// <returns>The window.</returns>
|
||||
private static DialogWindow CreateWindow(DialogViewModelBase dialog)
|
||||
{
|
||||
string viewName = typeof(ConfirmDialog).Namespace + "." + dialog.GetType().Name.Replace("ViewModel", "", StringComparison.Ordinal);
|
||||
Type? viewType = typeof(DialogService).Assembly.GetType(viewName);
|
||||
if (viewType is null || !typeof(DialogWindow).IsAssignableFrom(viewType))
|
||||
{
|
||||
throw new InvalidOperationException($"No dialog window '{viewName}' for {dialog.GetType().Name}.");
|
||||
}
|
||||
return (DialogWindow)Activator.CreateInstance(viewType)!;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
<dialogs:DialogWindow xmlns="https://github.com/avaloniaui"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:vm="using:YKanBan.ViewModels.Dialogs"
|
||||
xmlns:board="using:YKanBan.ViewModels.Board"
|
||||
xmlns:dialogs="using:YKanBan.Views.Dialogs"
|
||||
xmlns:lang="using:YKanBan"
|
||||
xmlns:icons="using:IconPacks.Avalonia.Lucide"
|
||||
x:Class="YKanBan.Views.Dialogs.CardEditorDialog"
|
||||
x:DataType="vm:CardEditorDialogViewModel"
|
||||
x:Name="Root"
|
||||
Title="{Binding Title}"
|
||||
SizeToContent="Manual" CanResize="True"
|
||||
Width="600" Height="560" MinWidth="440" MinHeight="420"
|
||||
WindowStartupLocation="CenterOwner">
|
||||
|
||||
<Grid Margin="20" RowDefinitions="Auto,Auto,*,Auto,Auto,Auto,Auto" RowSpacing="12">
|
||||
|
||||
<!-- Read-only id and timestamps; not shown while the card does not exist yet. -->
|
||||
<WrapPanel Grid.Row="0" IsVisible="{Binding IsExisting}" Orientation="Horizontal">
|
||||
<TextBlock Text="{Binding IdText}" FontWeight="Bold" Margin="0,0,16,0"/>
|
||||
<TextBlock Text="{Binding CreatedText}" Opacity="0.7" Margin="0,0,16,0"/>
|
||||
<TextBlock Text="{Binding ModifiedText}" Opacity="0.7"/>
|
||||
</WrapPanel>
|
||||
|
||||
<StackPanel Grid.Row="1" Spacing="4">
|
||||
<TextBlock Text="{x:Static lang:Resources.Field_Title}"/>
|
||||
<TextBox Text="{Binding CardTitle}" Watermark="{x:Static lang:Resources.CardEditor_TitleWatermark}"/>
|
||||
</StackPanel>
|
||||
|
||||
<Grid Grid.Row="2" RowDefinitions="Auto,*" RowSpacing="4">
|
||||
<TextBlock Grid.Row="0" Text="{x:Static lang:Resources.Field_Content}"/>
|
||||
<TextBox Grid.Row="1" Text="{Binding Content}" AcceptsReturn="True" TextWrapping="Wrap"
|
||||
VerticalAlignment="Stretch"
|
||||
VerticalContentAlignment="Top"/>
|
||||
</Grid>
|
||||
|
||||
<StackPanel Grid.Row="3" Spacing="6">
|
||||
<TextBlock Text="{x:Static lang:Resources.Field_Tags}"/>
|
||||
<ItemsControl ItemsSource="{Binding Tags}">
|
||||
<ItemsControl.ItemsPanel>
|
||||
<ItemsPanelTemplate>
|
||||
<WrapPanel/>
|
||||
</ItemsPanelTemplate>
|
||||
</ItemsControl.ItemsPanel>
|
||||
<ItemsControl.ItemTemplate>
|
||||
<DataTemplate x:DataType="board:TagBadgeViewModel">
|
||||
<Border Background="{Binding Background}" CornerRadius="10" Padding="8,2,4,2"
|
||||
Margin="0,0,6,6" ToolTip.Tip="{Binding Description}">
|
||||
<StackPanel Orientation="Horizontal" Spacing="2">
|
||||
<TextBlock Text="{Binding Name}" Foreground="{Binding Foreground}"
|
||||
VerticalAlignment="Center" FontSize="12"/>
|
||||
<Button Command="{Binding #Root.((vm:CardEditorDialogViewModel)DataContext).RemoveTagCommand}"
|
||||
CommandParameter="{Binding}"
|
||||
Theme="{StaticResource BorderlessButton}" Padding="2"
|
||||
ToolTip.Tip="{x:Static lang:Resources.CardEditor_RemoveTag}">
|
||||
<icons:PackIconLucide Kind="X" Width="12" Height="12" Foreground="{Binding Foreground}"/>
|
||||
</Button>
|
||||
</StackPanel>
|
||||
</Border>
|
||||
</DataTemplate>
|
||||
</ItemsControl.ItemTemplate>
|
||||
</ItemsControl>
|
||||
<Button Command="{Binding AddTagCommand}" HorizontalAlignment="Left">
|
||||
<StackPanel Orientation="Horizontal" Spacing="6">
|
||||
<icons:PackIconLucide Kind="Plus" Width="14" Height="14"/>
|
||||
<TextBlock Text="{x:Static lang:Resources.CardEditor_AddTag}"/>
|
||||
</StackPanel>
|
||||
</Button>
|
||||
</StackPanel>
|
||||
|
||||
<TextBlock Grid.Row="4" Text="{Binding ErrorMessage}" IsVisible="{Binding HasError}"
|
||||
Foreground="{DynamicResource ErrorTextBrush}" TextWrapping="Wrap"/>
|
||||
|
||||
<StackPanel Grid.Row="6" Orientation="Horizontal" HorizontalAlignment="Right" Spacing="8">
|
||||
<Button Content="{x:Static lang:Resources.Common_Ok}" Command="{Binding ConfirmCommand}"
|
||||
Classes="Primary" MinWidth="90"/>
|
||||
<Button Content="{x:Static lang:Resources.Common_Cancel}" Command="{Binding CancelCommand}"
|
||||
MinWidth="90" IsCancel="True"/>
|
||||
</StackPanel>
|
||||
</Grid>
|
||||
</dialogs:DialogWindow>
|
||||
@@ -0,0 +1,9 @@
|
||||
namespace YKanBan.Views.Dialogs;
|
||||
|
||||
public partial class CardEditorDialog : DialogWindow
|
||||
{
|
||||
public CardEditorDialog()
|
||||
{
|
||||
InitializeComponent();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
<dialogs:DialogWindow xmlns="https://github.com/avaloniaui"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:vm="using:YKanBan.ViewModels.Dialogs"
|
||||
xmlns:dialogs="using:YKanBan.Views.Dialogs"
|
||||
xmlns:lang="using:YKanBan"
|
||||
x:Class="YKanBan.Views.Dialogs.ColumnEditorDialog"
|
||||
x:DataType="vm:ColumnEditorDialogViewModel"
|
||||
Title="{Binding Title}"
|
||||
SizeToContent="Height" Width="440"
|
||||
WindowStartupLocation="CenterOwner">
|
||||
|
||||
<StackPanel Margin="20" Spacing="14">
|
||||
<StackPanel Spacing="4">
|
||||
<TextBlock Text="{x:Static lang:Resources.Field_Title}"/>
|
||||
<TextBox Text="{Binding ColumnTitle}"/>
|
||||
</StackPanel>
|
||||
<StackPanel Spacing="4">
|
||||
<TextBlock Text="{x:Static lang:Resources.Field_Description}"/>
|
||||
<TextBox Text="{Binding Description}" AcceptsReturn="True" TextWrapping="Wrap"
|
||||
MinHeight="72" MaxHeight="200"/>
|
||||
</StackPanel>
|
||||
|
||||
<TextBlock Text="{Binding ErrorMessage}" IsVisible="{Binding HasError}"
|
||||
Foreground="{DynamicResource ErrorTextBrush}" TextWrapping="Wrap"/>
|
||||
|
||||
<StackPanel Orientation="Horizontal" HorizontalAlignment="Right" Spacing="8">
|
||||
<Button Content="{x:Static lang:Resources.Common_Ok}" Command="{Binding ConfirmCommand}"
|
||||
Classes="Primary" MinWidth="90" IsDefault="True"/>
|
||||
<Button Content="{x:Static lang:Resources.Common_Cancel}" Command="{Binding CancelCommand}"
|
||||
MinWidth="90" IsCancel="True"/>
|
||||
</StackPanel>
|
||||
</StackPanel>
|
||||
</dialogs:DialogWindow>
|
||||
@@ -0,0 +1,9 @@
|
||||
namespace YKanBan.Views.Dialogs;
|
||||
|
||||
public partial class ColumnEditorDialog : DialogWindow
|
||||
{
|
||||
public ColumnEditorDialog()
|
||||
{
|
||||
InitializeComponent();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
<dialogs:DialogWindow xmlns="https://github.com/avaloniaui"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:vm="using:YKanBan.ViewModels.Dialogs"
|
||||
xmlns:dialogs="using:YKanBan.Views.Dialogs"
|
||||
xmlns:lang="using:YKanBan"
|
||||
x:Class="YKanBan.Views.Dialogs.ColumnWidthDialog"
|
||||
x:DataType="vm:ColumnWidthDialogViewModel"
|
||||
Title="{x:Static lang:Resources.ColumnWidth_Title}"
|
||||
Width="360"
|
||||
WindowStartupLocation="CenterOwner">
|
||||
|
||||
<StackPanel Margin="20" Spacing="10">
|
||||
<RadioButton GroupName="Width" Content="{Binding NarrowLabel}" IsChecked="{Binding IsNarrow}"/>
|
||||
<RadioButton GroupName="Width" Content="{Binding StandardLabel}" IsChecked="{Binding IsStandard}"/>
|
||||
<RadioButton GroupName="Width" Content="{Binding WideLabel}" IsChecked="{Binding IsWide}"/>
|
||||
<RadioButton GroupName="Width" Content="{x:Static lang:Resources.ColumnWidth_Custom}" IsChecked="{Binding IsCustom}"/>
|
||||
<StackPanel Orientation="Horizontal" Spacing="8" Margin="28,0,0,0" IsEnabled="{Binding IsCustom}">
|
||||
<NumericUpDown Value="{Binding CustomPixels}" Minimum="{Binding MinPixels}" Maximum="{Binding MaxPixels}"
|
||||
Increment="10" FormatString="0" Width="140"/>
|
||||
<TextBlock Text="{Binding RangeLabel}" VerticalAlignment="Center" Opacity="0.7"/>
|
||||
</StackPanel>
|
||||
|
||||
<StackPanel Orientation="Horizontal" HorizontalAlignment="Right" Spacing="8" Margin="0,8,0,0">
|
||||
<Button Content="{x:Static lang:Resources.Common_Ok}" Command="{Binding ConfirmCommand}"
|
||||
Classes="Primary" MinWidth="90" IsDefault="True"/>
|
||||
<Button Content="{x:Static lang:Resources.Common_Cancel}" Command="{Binding CancelCommand}"
|
||||
MinWidth="90" IsCancel="True"/>
|
||||
</StackPanel>
|
||||
</StackPanel>
|
||||
</dialogs:DialogWindow>
|
||||
@@ -0,0 +1,9 @@
|
||||
namespace YKanBan.Views.Dialogs;
|
||||
|
||||
public partial class ColumnWidthDialog : DialogWindow
|
||||
{
|
||||
public ColumnWidthDialog()
|
||||
{
|
||||
InitializeComponent();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
<dialogs:DialogWindow xmlns="https://github.com/avaloniaui"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:vm="using:YKanBan.ViewModels.Dialogs"
|
||||
xmlns:dialogs="using:YKanBan.Views.Dialogs"
|
||||
xmlns:lang="using:YKanBan"
|
||||
x:Class="YKanBan.Views.Dialogs.ConfirmDialog"
|
||||
x:DataType="vm:ConfirmDialogViewModel"
|
||||
Title="{x:Static lang:Resources.Confirm_Title}"
|
||||
MinWidth="360" MaxWidth="520"
|
||||
WindowStartupLocation="CenterOwner">
|
||||
|
||||
<StackPanel Margin="20" Spacing="16">
|
||||
<TextBlock Text="{Binding Message}" TextWrapping="Wrap"/>
|
||||
<StackPanel Orientation="Horizontal" HorizontalAlignment="Right" Spacing="8">
|
||||
<Button Content="{Binding ConfirmLabel}" Command="{Binding ConfirmCommand}"
|
||||
Classes="Danger" MinWidth="90" IsDefault="True"/>
|
||||
<Button Content="{x:Static lang:Resources.Common_Cancel}" Command="{Binding CancelCommand}"
|
||||
MinWidth="90" IsCancel="True"/>
|
||||
</StackPanel>
|
||||
</StackPanel>
|
||||
</dialogs:DialogWindow>
|
||||
@@ -0,0 +1,9 @@
|
||||
namespace YKanBan.Views.Dialogs;
|
||||
|
||||
public partial class ConfirmDialog : DialogWindow
|
||||
{
|
||||
public ConfirmDialog()
|
||||
{
|
||||
InitializeComponent();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Threading;
|
||||
using Avalonia.VisualTree;
|
||||
using YKanBan.ViewModels.Dialogs;
|
||||
|
||||
namespace YKanBan.Views.Dialogs;
|
||||
|
||||
/// <summary>
|
||||
/// Base class of the windows shown by <see cref="DialogService"/>: a standard
|
||||
/// Avalonia window centered on its owner that closes when its
|
||||
/// <see cref="DialogViewModelBase"/> asks, with the result as the dialog result.
|
||||
/// The title bar close button is routed to the view model's cancel path, so a
|
||||
/// dialog with unsaved changes can ask before discarding them.
|
||||
/// On opening, the first visible, enabled and editable text box takes the
|
||||
/// focus with its text selected; dialogs without one leave the focus alone.
|
||||
/// </summary>
|
||||
public class DialogWindow : Window
|
||||
{
|
||||
private DialogViewModelBase? _viewModel;
|
||||
private bool _closeRequested;
|
||||
private bool _cancelPending;
|
||||
|
||||
public DialogWindow()
|
||||
{
|
||||
WindowStartupLocation = WindowStartupLocation.CenterOwner;
|
||||
ShowInTaskbar = false;
|
||||
CanResize = false;
|
||||
SizeToContent = SizeToContent.WidthAndHeight;
|
||||
}
|
||||
|
||||
/// <summary>Styles the subclasses as plain windows.</summary>
|
||||
protected override Type StyleKeyOverride => typeof(Window);
|
||||
|
||||
protected override void OnDataContextChanged(EventArgs e)
|
||||
{
|
||||
base.OnDataContextChanged(e);
|
||||
if (_viewModel is not null)
|
||||
{
|
||||
_viewModel.CloseRequested -= OnCloseRequested;
|
||||
}
|
||||
_viewModel = DataContext as DialogViewModelBase;
|
||||
if (_viewModel is not null)
|
||||
{
|
||||
_viewModel.CloseRequested += OnCloseRequested;
|
||||
}
|
||||
}
|
||||
|
||||
protected override void OnOpened(EventArgs e)
|
||||
{
|
||||
base.OnOpened(e);
|
||||
|
||||
// Wait for the first layout pass so visibility and enabled state are settled.
|
||||
Dispatcher.UIThread.Post(FocusFirstTextBox, DispatcherPriority.Loaded);
|
||||
}
|
||||
|
||||
private void FocusFirstTextBox()
|
||||
{
|
||||
TextBox? target = this.GetVisualDescendants().OfType<TextBox>()
|
||||
.FirstOrDefault(box => box.IsEffectivelyVisible && box.IsEffectivelyEnabled && box.Focusable && !box.IsReadOnly);
|
||||
if (target is not null && target.Focus())
|
||||
{
|
||||
target.SelectAll();
|
||||
}
|
||||
}
|
||||
|
||||
protected override async void OnClosing(WindowClosingEventArgs e)
|
||||
{
|
||||
base.OnClosing(e);
|
||||
|
||||
// Only the user's close button goes through the view model; shutdown and
|
||||
// owner closing are let through.
|
||||
if (_closeRequested || _viewModel is null || e.CloseReason != WindowCloseReason.WindowClosing)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
e.Cancel = true;
|
||||
if (_cancelPending)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_cancelPending = true;
|
||||
try
|
||||
{
|
||||
await _viewModel.RequestCancelAsync();
|
||||
}
|
||||
finally
|
||||
{
|
||||
_cancelPending = false;
|
||||
}
|
||||
}
|
||||
|
||||
protected override void OnClosed(EventArgs e)
|
||||
{
|
||||
base.OnClosed(e);
|
||||
if (_viewModel is not null)
|
||||
{
|
||||
_viewModel.CloseRequested -= OnCloseRequested;
|
||||
}
|
||||
}
|
||||
|
||||
private void OnCloseRequested(object? sender, bool result)
|
||||
{
|
||||
_closeRequested = true;
|
||||
Close(result);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
<dialogs:DialogWindow xmlns="https://github.com/avaloniaui"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:vm="using:YKanBan.ViewModels.Dialogs"
|
||||
xmlns:dialogs="using:YKanBan.Views.Dialogs"
|
||||
xmlns:lang="using:YKanBan"
|
||||
x:Class="YKanBan.Views.Dialogs.MessageDialog"
|
||||
x:DataType="vm:MessageDialogViewModel"
|
||||
Title="{Binding Title}"
|
||||
MinWidth="360" MaxWidth="560"
|
||||
WindowStartupLocation="CenterOwner">
|
||||
|
||||
<StackPanel Margin="20" Spacing="12">
|
||||
<TextBlock Text="{Binding Message}" TextWrapping="Wrap"/>
|
||||
<SelectableTextBlock Text="{Binding Details}" IsVisible="{Binding HasDetails}"
|
||||
TextWrapping="Wrap" FontSize="12" Opacity="0.7"/>
|
||||
<Button Content="{x:Static lang:Resources.Common_Ok}" Command="{Binding OkCommand}"
|
||||
HorizontalAlignment="Right" MinWidth="90" IsDefault="True" IsCancel="True"/>
|
||||
</StackPanel>
|
||||
</dialogs:DialogWindow>
|
||||
@@ -0,0 +1,9 @@
|
||||
namespace YKanBan.Views.Dialogs;
|
||||
|
||||
public partial class MessageDialog : DialogWindow
|
||||
{
|
||||
public MessageDialog()
|
||||
{
|
||||
InitializeComponent();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
<dialogs:DialogWindow xmlns="https://github.com/avaloniaui"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:vm="using:YKanBan.ViewModels.Dialogs"
|
||||
xmlns:dialogs="using:YKanBan.Views.Dialogs"
|
||||
xmlns:lang="using:YKanBan"
|
||||
x:Class="YKanBan.Views.Dialogs.TagEditorDialog"
|
||||
x:DataType="vm:TagEditorDialogViewModel"
|
||||
x:Name="Root"
|
||||
Title="{Binding Title}"
|
||||
SizeToContent="Height" Width="440"
|
||||
WindowStartupLocation="CenterOwner">
|
||||
|
||||
<StackPanel Margin="20" Spacing="14">
|
||||
<StackPanel Spacing="4">
|
||||
<TextBlock Text="{x:Static lang:Resources.Field_Name}"/>
|
||||
<TextBox Text="{Binding Name}"/>
|
||||
</StackPanel>
|
||||
|
||||
<StackPanel Spacing="6">
|
||||
<TextBlock Text="{x:Static lang:Resources.TagEditor_ColorLabel}"/>
|
||||
<StackPanel Orientation="Horizontal" Spacing="8">
|
||||
<TextBox Text="{Binding Color}" Width="120" Watermark="{x:Static lang:Resources.Field_Color}"/>
|
||||
<Border Width="28" Height="28" CornerRadius="4" Background="{Binding ColorPreview}"
|
||||
BorderBrush="{DynamicResource PanelBorderBrush}" BorderThickness="1"/>
|
||||
</StackPanel>
|
||||
<ItemsControl ItemsSource="{Binding Swatches}">
|
||||
<ItemsControl.ItemsPanel>
|
||||
<ItemsPanelTemplate>
|
||||
<StackPanel Orientation="Horizontal" Spacing="6"/>
|
||||
</ItemsPanelTemplate>
|
||||
</ItemsControl.ItemsPanel>
|
||||
<ItemsControl.ItemTemplate>
|
||||
<DataTemplate x:DataType="vm:ColorSwatch">
|
||||
<Button Command="{Binding #Root.((vm:TagEditorDialogViewModel)DataContext).PickSwatchCommand}"
|
||||
CommandParameter="{Binding Hex}"
|
||||
ToolTip.Tip="{Binding Hex}"
|
||||
Width="24" Height="24" Padding="0" CornerRadius="4"
|
||||
Background="{Binding Brush}"
|
||||
BorderBrush="{DynamicResource PanelBorderBrush}" BorderThickness="1"/>
|
||||
</DataTemplate>
|
||||
</ItemsControl.ItemTemplate>
|
||||
</ItemsControl>
|
||||
</StackPanel>
|
||||
|
||||
<StackPanel Spacing="4">
|
||||
<TextBlock Text="{x:Static lang:Resources.Field_Description}"/>
|
||||
<TextBox Text="{Binding Description}" AcceptsReturn="True" TextWrapping="Wrap"
|
||||
MinHeight="72" MaxHeight="200"/>
|
||||
</StackPanel>
|
||||
|
||||
<TextBlock Text="{Binding ErrorMessage}" IsVisible="{Binding HasError}"
|
||||
Foreground="{DynamicResource ErrorTextBrush}" TextWrapping="Wrap"/>
|
||||
|
||||
<StackPanel Orientation="Horizontal" HorizontalAlignment="Right" Spacing="8">
|
||||
<Button Content="{x:Static lang:Resources.Common_Ok}" Command="{Binding ConfirmCommand}"
|
||||
Classes="Primary" MinWidth="90" IsDefault="True"/>
|
||||
<Button Content="{x:Static lang:Resources.Common_Cancel}" Command="{Binding CancelCommand}"
|
||||
MinWidth="90" IsCancel="True"/>
|
||||
</StackPanel>
|
||||
</StackPanel>
|
||||
</dialogs:DialogWindow>
|
||||
@@ -0,0 +1,9 @@
|
||||
namespace YKanBan.Views.Dialogs;
|
||||
|
||||
public partial class TagEditorDialog : DialogWindow
|
||||
{
|
||||
public TagEditorDialog()
|
||||
{
|
||||
InitializeComponent();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
<dialogs:DialogWindow xmlns="https://github.com/avaloniaui"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:vm="using:YKanBan.ViewModels.Dialogs"
|
||||
xmlns:board="using:YKanBan.ViewModels.Board"
|
||||
xmlns:dialogs="using:YKanBan.Views.Dialogs"
|
||||
xmlns:lang="using:YKanBan"
|
||||
xmlns:icons="using:IconPacks.Avalonia.Lucide"
|
||||
x:Class="YKanBan.Views.Dialogs.TagPickerDialog"
|
||||
x:DataType="vm:TagPickerDialogViewModel"
|
||||
x:Name="Root"
|
||||
Title="{x:Static lang:Resources.TagPicker_Title}"
|
||||
SizeToContent="Manual" CanResize="True"
|
||||
Width="460" Height="560" MinWidth="380" MinHeight="440"
|
||||
WindowStartupLocation="CenterOwner">
|
||||
|
||||
<Grid Margin="20" RowDefinitions="Auto,*,Auto,Auto" RowSpacing="12">
|
||||
|
||||
<TextBox Grid.Row="0" Text="{Binding FilterText}" Watermark="{x:Static lang:Resources.TagPicker_FilterWatermark}">
|
||||
<TextBox.InnerLeftContent>
|
||||
<icons:PackIconLucide Kind="Search" Width="14" Height="14" Margin="8,0,0,0" Opacity="0.6"
|
||||
VerticalAlignment="Center"/>
|
||||
</TextBox.InnerLeftContent>
|
||||
</TextBox>
|
||||
|
||||
<!-- Existing tags not yet on the card; one click picks a tag. -->
|
||||
<Border Grid.Row="1" BorderBrush="{DynamicResource PanelBorderBrush}" BorderThickness="1" CornerRadius="4">
|
||||
<Panel>
|
||||
<ListBox ItemsSource="{Binding FilteredTags}" Background="Transparent">
|
||||
<ListBox.ItemTemplate>
|
||||
<DataTemplate x:DataType="board:TagBadgeViewModel">
|
||||
<Button Command="{Binding #Root.((vm:TagPickerDialogViewModel)DataContext).PickCommand}"
|
||||
CommandParameter="{Binding}"
|
||||
Theme="{StaticResource BorderlessButton}"
|
||||
HorizontalAlignment="Stretch" HorizontalContentAlignment="Left" Padding="4">
|
||||
<StackPanel Orientation="Horizontal" Spacing="10">
|
||||
<Border Background="{Binding Background}" CornerRadius="10" Padding="8,2">
|
||||
<TextBlock Text="{Binding Name}" Foreground="{Binding Foreground}" FontSize="12"/>
|
||||
</Border>
|
||||
<TextBlock Text="{Binding Description}" Opacity="0.7" VerticalAlignment="Center"
|
||||
TextTrimming="CharacterEllipsis"/>
|
||||
</StackPanel>
|
||||
</Button>
|
||||
</DataTemplate>
|
||||
</ListBox.ItemTemplate>
|
||||
</ListBox>
|
||||
<TextBlock Text="{x:Static lang:Resources.TagPicker_NoMatches}" IsVisible="{Binding NoMatches}"
|
||||
HorizontalAlignment="Center" VerticalAlignment="Center" Opacity="0.6"/>
|
||||
</Panel>
|
||||
</Border>
|
||||
|
||||
<!-- New tag: written to the tags table right away, even if the card edit is cancelled. -->
|
||||
<StackPanel Grid.Row="2" Spacing="8">
|
||||
<TextBlock Text="{x:Static lang:Resources.TagPicker_NewTag}" FontWeight="SemiBold"/>
|
||||
<Grid ColumnDefinitions="*,Auto,Auto" ColumnSpacing="8">
|
||||
<TextBox Grid.Column="0" Text="{Binding NewName}" Watermark="{x:Static lang:Resources.Field_Name}"/>
|
||||
<TextBox Grid.Column="1" Text="{Binding NewColor}" Width="100"
|
||||
Watermark="{x:Static lang:Resources.Field_Color}"/>
|
||||
<Border Grid.Column="2" Width="28" Height="28" CornerRadius="4"
|
||||
Background="{Binding NewColorPreview}"
|
||||
BorderBrush="{DynamicResource PanelBorderBrush}" BorderThickness="1"/>
|
||||
</Grid>
|
||||
<TextBox Text="{Binding NewDescription}" Watermark="{x:Static lang:Resources.Field_Description}"/>
|
||||
<TextBlock Text="{Binding ErrorMessage}" IsVisible="{Binding HasError}"
|
||||
Foreground="{DynamicResource ErrorTextBrush}" TextWrapping="Wrap"/>
|
||||
<Button Command="{Binding CreateCommand}" HorizontalAlignment="Left">
|
||||
<StackPanel Orientation="Horizontal" Spacing="6">
|
||||
<icons:PackIconLucide Kind="Plus" Width="14" Height="14"/>
|
||||
<TextBlock Text="{x:Static lang:Resources.TagPicker_Create}"/>
|
||||
</StackPanel>
|
||||
</Button>
|
||||
</StackPanel>
|
||||
|
||||
<Button Grid.Row="3" Content="{x:Static lang:Resources.Common_Cancel}" Command="{Binding CancelCommand}"
|
||||
HorizontalAlignment="Right" MinWidth="90" IsCancel="True"/>
|
||||
</Grid>
|
||||
</dialogs:DialogWindow>
|
||||
@@ -0,0 +1,9 @@
|
||||
namespace YKanBan.Views.Dialogs;
|
||||
|
||||
public partial class TagPickerDialog : DialogWindow
|
||||
{
|
||||
public TagPickerDialog()
|
||||
{
|
||||
InitializeComponent();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
<UserControl xmlns="https://github.com/avaloniaui"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:vm="using:YKanBan.ViewModels.ErrorPages"
|
||||
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="1000" d:DesignHeight="640"
|
||||
x:Class="YKanBan.Views.ErrorPages.OpenFailedPageView"
|
||||
x:DataType="vm:OpenFailedPageViewModel">
|
||||
|
||||
<StackPanel HorizontalAlignment="Center" VerticalAlignment="Center" Spacing="12"
|
||||
MaxWidth="720" Margin="32">
|
||||
<TextBlock Text="{x:Static lang:Resources.Error_OpenFailed_Title}"
|
||||
FontSize="20" FontWeight="SemiBold" HorizontalAlignment="Center"/>
|
||||
<TextBlock Text="{Binding Message}"
|
||||
TextWrapping="Wrap" HorizontalAlignment="Center" TextAlignment="Center"/>
|
||||
<TextBlock Text="{x:Static lang:Resources.Error_OpenFailed_Details}" FontWeight="SemiBold"/>
|
||||
<!-- English diagnostics stay left-to-right whatever the UI flow direction. -->
|
||||
<TextBox Text="{Binding Details, Mode=OneWay}"
|
||||
IsReadOnly="True" TextWrapping="Wrap" AcceptsReturn="True"
|
||||
FlowDirection="LeftToRight"
|
||||
FontFamily="Consolas,Menlo,monospace" MaxHeight="240"/>
|
||||
</StackPanel>
|
||||
</UserControl>
|
||||
@@ -0,0 +1,11 @@
|
||||
using Avalonia.Controls;
|
||||
|
||||
namespace YKanBan.Views.ErrorPages;
|
||||
|
||||
public partial class OpenFailedPageView : UserControl
|
||||
{
|
||||
public OpenFailedPageView()
|
||||
{
|
||||
InitializeComponent();
|
||||
}
|
||||
}
|
||||
@@ -37,7 +37,7 @@ public partial class MainWindow : Window
|
||||
{
|
||||
DataContext = new SettingsDialogViewModel(App.Services.Config, App.StartupLanguage),
|
||||
};
|
||||
await dialog.ShowDialog(this);
|
||||
await ShowModalAsync(dialog);
|
||||
}
|
||||
|
||||
/// <summary>Shows the about dialog centered on this window.</summary>
|
||||
@@ -47,6 +47,18 @@ public partial class MainWindow : Window
|
||||
{
|
||||
DataContext = new AboutDialogViewModel(),
|
||||
};
|
||||
await dialog.ShowDialog(this);
|
||||
await ShowModalAsync(dialog);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Shows a modal window owned by this window. Every modal goes through here:
|
||||
/// FlowDirection does not inherit across windows, so it is applied explicitly.
|
||||
/// </summary>
|
||||
/// <param name="dialog">The modal window to show.</param>
|
||||
/// <returns>A task completing when the dialog closes.</returns>
|
||||
private Task ShowModalAsync(Window dialog)
|
||||
{
|
||||
dialog.FlowDirection = App.UiFlowDirection;
|
||||
return dialog.ShowDialog(this);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
<UserControl xmlns="https://github.com/avaloniaui"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:vm="using:YKanBan.ViewModels.Tags"
|
||||
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.Tags.TagsView"
|
||||
x:DataType="vm:TagsViewModel">
|
||||
|
||||
<Grid RowDefinitions="Auto,*" RowSpacing="8">
|
||||
|
||||
<!-- Toolbar: tag total on the left, new tag on the right. -->
|
||||
<Grid Grid.Row="0" ColumnDefinitions="*,Auto">
|
||||
<TextBlock Grid.Column="0" Text="{Binding Summary}" VerticalAlignment="Center" Opacity="0.7"/>
|
||||
<Button Grid.Column="1" Command="{Binding AddTagCommand}">
|
||||
<StackPanel Orientation="Horizontal" Spacing="6">
|
||||
<icons:PackIconLucide Kind="Plus" Width="16" Height="16"/>
|
||||
<TextBlock Text="{x:Static lang:Resources.Tags_AddTag}"/>
|
||||
</StackPanel>
|
||||
</Button>
|
||||
</Grid>
|
||||
|
||||
<!-- Tag list: badge, description, usage count, edit and delete. -->
|
||||
<Border Grid.Row="1" BorderBrush="{DynamicResource PanelBorderBrush}" BorderThickness="1" CornerRadius="6">
|
||||
<Panel>
|
||||
<ItemsControl ItemsSource="{Binding Tags}">
|
||||
<ItemsControl.Template>
|
||||
<ControlTemplate>
|
||||
<ScrollViewer HorizontalScrollBarVisibility="Disabled" VerticalScrollBarVisibility="Auto">
|
||||
<ItemsPresenter Name="PART_ItemsPresenter" ItemsPanel="{TemplateBinding ItemsPanel}"/>
|
||||
</ScrollViewer>
|
||||
</ControlTemplate>
|
||||
</ItemsControl.Template>
|
||||
<ItemsControl.ItemsPanel>
|
||||
<ItemsPanelTemplate>
|
||||
<VirtualizingStackPanel/>
|
||||
</ItemsPanelTemplate>
|
||||
</ItemsControl.ItemsPanel>
|
||||
<ItemsControl.ItemTemplate>
|
||||
<DataTemplate x:DataType="vm:TagRowViewModel">
|
||||
<Border BorderBrush="{DynamicResource PanelBorderBrush}" BorderThickness="0,0,0,1"
|
||||
Padding="16,10">
|
||||
<Grid ColumnDefinitions="240,*,Auto,Auto" ColumnSpacing="16">
|
||||
<Border Grid.Column="0" HorizontalAlignment="Left" VerticalAlignment="Center"
|
||||
Background="{Binding Badge.Background}" CornerRadius="10" Padding="10,2"
|
||||
ToolTip.Tip="{Binding ColorText}">
|
||||
<TextBlock Text="{Binding Badge.Name}" Foreground="{Binding Badge.Foreground}"
|
||||
FontSize="12" TextTrimming="CharacterEllipsis"/>
|
||||
</Border>
|
||||
<TextBlock Grid.Column="1" Text="{Binding Description}" VerticalAlignment="Center"
|
||||
Opacity="0.75" TextTrimming="CharacterEllipsis"/>
|
||||
<TextBlock Grid.Column="2" Text="{Binding UsageText}" VerticalAlignment="Center"
|
||||
Opacity="0.7"/>
|
||||
<StackPanel Grid.Column="3" Orientation="Horizontal" Spacing="4">
|
||||
<Button Command="{Binding EditCommand}" Theme="{StaticResource BorderlessButton}"
|
||||
Padding="6" ToolTip.Tip="{x:Static lang:Resources.Menu_Edit}">
|
||||
<icons:PackIconLucide Kind="Pencil" Width="14" Height="14"/>
|
||||
</Button>
|
||||
<Button Command="{Binding DeleteCommand}" Theme="{StaticResource BorderlessButton}"
|
||||
Padding="6" ToolTip.Tip="{x:Static lang:Resources.Menu_Delete}">
|
||||
<icons:PackIconLucide Kind="Trash2" Width="14" Height="14"/>
|
||||
</Button>
|
||||
</StackPanel>
|
||||
</Grid>
|
||||
</Border>
|
||||
</DataTemplate>
|
||||
</ItemsControl.ItemTemplate>
|
||||
</ItemsControl>
|
||||
<TextBlock Text="{x:Static lang:Resources.Tags_Empty}" IsVisible="{Binding IsEmpty}"
|
||||
HorizontalAlignment="Center" VerticalAlignment="Center" Opacity="0.6"/>
|
||||
</Panel>
|
||||
</Border>
|
||||
</Grid>
|
||||
</UserControl>
|
||||
@@ -0,0 +1,11 @@
|
||||
using Avalonia.Controls;
|
||||
|
||||
namespace YKanBan.Views.Tags;
|
||||
|
||||
public partial class TagsView : UserControl
|
||||
{
|
||||
public TagsView()
|
||||
{
|
||||
InitializeComponent();
|
||||
}
|
||||
}
|
||||
@@ -48,10 +48,14 @@
|
||||
</Grid>
|
||||
</Border>
|
||||
|
||||
<!-- Tags and board tabs; their contents arrive with the corresponding features. -->
|
||||
<!-- Board and tags tabs. -->
|
||||
<TabControl Grid.Row="1" Margin="8">
|
||||
<TabItem Header="{x:Static lang:Resources.Tab_Board}"/>
|
||||
<TabItem Header="{x:Static lang:Resources.Tab_Tags}"/>
|
||||
<TabItem Header="{x:Static lang:Resources.Tab_Board}">
|
||||
<ContentControl Content="{Binding Board}" Margin="0,8,0,0"/>
|
||||
</TabItem>
|
||||
<TabItem Header="{x:Static lang:Resources.Tab_Tags}">
|
||||
<ContentControl Content="{Binding Tags}" Margin="0,8,0,0"/>
|
||||
</TabItem>
|
||||
</TabControl>
|
||||
|
||||
</Grid>
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<OutputType>WinExe</OutputType>
|
||||
<TargetFramework>net9.0</TargetFramework>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<Version>0.1.0</Version>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
@@ -37,19 +37,19 @@
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Avalonia" Version="11.3.6" />
|
||||
<PackageReference Include="Avalonia.Desktop" Version="11.3.6" />
|
||||
<PackageReference Include="Avalonia.Themes.Fluent" Version="11.3.6" />
|
||||
<PackageReference Include="Avalonia.Fonts.Inter" Version="11.3.6" />
|
||||
<PackageReference Include="Avalonia" Version="11.3.22" />
|
||||
<PackageReference Include="Avalonia.Desktop" Version="11.3.22" />
|
||||
<PackageReference Include="Avalonia.Themes.Fluent" Version="11.3.22" />
|
||||
<PackageReference Include="Avalonia.Fonts.Inter" Version="11.3.22" />
|
||||
<!--Condition below is needed to remove Avalonia.Diagnostics package from build output in Release configuration.-->
|
||||
<PackageReference Include="Avalonia.Diagnostics" Version="11.3.6">
|
||||
<PackageReference Include="Avalonia.Diagnostics" Version="11.3.22">
|
||||
<IncludeAssets Condition="'$(Configuration)' != 'Debug'">None</IncludeAssets>
|
||||
<PrivateAssets Condition="'$(Configuration)' != 'Debug'">All</PrivateAssets>
|
||||
</PackageReference>
|
||||
<PackageReference Include="CommunityToolkit.Mvvm" Version="8.2.1" />
|
||||
<PackageReference Include="Semi.Avalonia" Version="11.2.1.10" />
|
||||
<PackageReference Include="Semi.Avalonia" Version="11.3.22" />
|
||||
<PackageReference Include="IconPacks.Avalonia.Lucide" Version="2.0.0" />
|
||||
<PackageReference Include="Microsoft.Data.Sqlite" Version="9.0.20" />
|
||||
<PackageReference Include="Microsoft.Data.Sqlite" Version="10.0.12" />
|
||||
<PackageReference Include="Pidgin" Version="3.5.1" />
|
||||
<PackageReference Include="Newtonsoft.Json" Version="13.0.4" />
|
||||
</ItemGroup>
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
# YKanBan 人工验收清单
|
||||
|
||||
> 对应 PLAN §9 各里程碑的"人工"验证项。按计划 §7.1,窗口、模态、点击流、数据绑定、主题切换、状态页渲染不写自动化测试,一律按本清单人工验证。
|
||||
> 默认在本地 Windows 执行;Linux / macOS 行为验证按 §7.2 推迟至程序完工后,届时用同一清单逐项复核。
|
||||
|
||||
## 准备
|
||||
|
||||
- [ ] `dotnet build` 与 `dotnet test` 通过
|
||||
- [ ] 准备一个空文件夹 `<demo>` 作为演示工作区;以下 `ykanban` 均指 `dotnet run --project YKanBan --` 或发布产物中的可执行文件
|
||||
- [ ] 记下 `app.json` 位置(Windows:`%APPDATA%\YKanBan\app.json`),验收前备份或删除,保证从默认值开始
|
||||
|
||||
## A. 计划指定的四项(M7 必验)
|
||||
|
||||
### A1 语言切换重启生效
|
||||
|
||||
- [ ] 设置 → 语言改为简体中文 → 显示"重启后生效"提示;当前界面**不**变化
|
||||
- [ ] 确认关闭后,退出程序 → `app.json` 中 `Language` 为 `zh-Hans`
|
||||
- [ ] 重启 → 全部界面文本(顶部区、两个 tab、各模态、错误页、排序项、确认对话框)为中文,无残留英文硬编码
|
||||
- [ ] 切回英文 → 重启后恢复英文
|
||||
- [ ] 中文下新初始化的工作区预置列为 待办 / 进行中 / 已完成;切回英文后这些列名**不变**(已是数据)
|
||||
|
||||
### A2 导出语言跟随界面
|
||||
|
||||
- [ ] 英文界面导出:默认文件名 `<工作区名>-export-yyyyMMdd-HHmmss.md`(精确到秒);文件内模板文字为英文,时间格式 `yyyy-MM-dd HH:mm:ss`
|
||||
- [ ] 中文界面导出:默认文件名 `<工作区名>-导出-yyyyMMdd-HHmmss.md`;模板文字为中文,时间格式 `yyyy年M月d日 HH:mm`
|
||||
- [ ] 保存对话框的文件类型名随语言(Markdown document / Markdown 文档)
|
||||
- [ ] 看板处于搜索筛选、非默认排序时导出:文件仍含**全部**列与卡片,列与卡片均按 id 升序;空列保留;无标题卡片为 `### #id`
|
||||
- [ ] 标签总表含全部标签(含未使用的),使用数正确;标签名含 `` ` ``、`|`、换行时转义符合 §5.8
|
||||
- [ ] 文件为 UTF-8 无 BOM;取消保存对话框不写任何文件;保存到无权限位置时弹"导出失败"消息框
|
||||
|
||||
### A3 主题三态切换
|
||||
|
||||
- [ ] 设置 → 主题 亮色 / 暗色 / 跟随系统 依次切换:**即时生效**,无重启提示
|
||||
- [ ] 每种主题下检查:主窗口、看板列与卡片、标签 tab、全部模态、全部错误页颜色完整切换,无亮底暗字/暗底亮字残留
|
||||
- [ ] 标签徽章在两种主题下均显示原色(§5.9 例外),文字颜色保持可读
|
||||
- [ ] 跟随系统:程序运行中切换 Windows 深浅色 → 程序跟随变化
|
||||
- [ ] 重启后主题保持上次选择
|
||||
|
||||
### A4 app.json 多实例脏写
|
||||
|
||||
- [ ] 同时打开两个实例(不同工作区)。实例 1 改排序,实例 2 改列宽;先关实例 1、后关实例 2 → `app.json` 为实例 2 的完整设置(后退出者覆盖,实例 1 的排序改动丢失——已接受)
|
||||
- [ ] 打开两个实例,只在实例 1 改设置;先关实例 1,再关**未改过设置**的实例 2 → `app.json` 保持实例 1 写入的内容(未改设置的实例不写盘)
|
||||
- [ ] 处于错误页(例如参数错误页)的实例退出时不写 `app.json`(可先删除 `app.json`,退出后确认文件未被创建)
|
||||
- [ ] `app.json` 写成非法 JSON → 启动正常、使用默认值,生成 `app.json.bak`;改一次设置退出后 `app.json` 恢复为合法内容
|
||||
- [ ] `app.json` 中单个字段非法(如 `"Theme": "pink"`、列宽 `9999`)→ 仅该字段回退默认,其余设置保留,不生成 `.bak`
|
||||
|
||||
## B. 启动与错误页(M4 / M4R)
|
||||
|
||||
- [ ] 无参数、两个参数、`--help`、`-x`、空字符串参数 → 参数错误页,显示 `Usage: ykanban <path>`
|
||||
- [ ] 不存在的路径、指向文件的路径 → 目录不存在页
|
||||
- [ ] 相对路径(如 `ykanban .`)按当前目录解析
|
||||
- [ ] 无 `.ykanban` 的文件夹 → 未初始化页;点"初始化"后进入看板,预置三列
|
||||
- [ ] 初始化失败(如只读文件夹)→ 工作区打开失败页
|
||||
- [ ] 同一工作区开第二个实例 → 锁冲突页,无任何操作按钮;关闭第一个实例后可正常打开
|
||||
- [ ] 工作区数据库 `user_version` 改为更高值 → 打开失败页,提示版本过新,英文详情可选中复制
|
||||
- [ ] 把 `ykanban.db` 换成垃圾内容 → 打开失败页(数据库无法打开/损坏)
|
||||
- [ ] 窗口标题:正常时 `工作区名 - YKanBan`,错误页时仅 `YKanBan`
|
||||
- [ ] 顶部区:工作区名 + 小一号完整路径;右侧 导出 / 设置 / 关于 同排
|
||||
|
||||
## C. 看板 tab(M5)
|
||||
|
||||
- [ ] 新建列、编辑列(标题 + 描述);空标题、重名(含仅大小写不同,如 `Done` / `done`)→ 模态内提示错误,模态不关、输入保留
|
||||
- [ ] 删除列:确认框提示将删除 N 张卡片;确认后列与卡片一并删除
|
||||
- [ ] 新建卡片、点击卡片编辑:标题可空;内容多行;`#id` / 创建时间 / 修改时间只读显示(新建时不显示)
|
||||
- [ ] 编辑确认但内容未变 → 修改时间不变;改动后确认 → 修改时间刷新
|
||||
- [ ] 有未保存改动时取消或点标题栏关闭 → 丢弃确认(开关开启时)
|
||||
- [ ] 卡片菜单"移动到列":卡片移动,修改时间**不**变
|
||||
- [ ] 删除卡片:确认框(开关开启时)
|
||||
- [ ] 卡片条目:`#id` 加粗与标题同行;无标题只显示 `#id`;内容约 200 字截断;标签彩色徽章;不显示时间
|
||||
- [ ] 标签区:× 移除;"添加标签"嵌套模态可筛选、选中即添加、可反复打开;嵌套模态中新建标签**立即写库**——外层取消后该标签仍出现在标签 tab
|
||||
- [ ] 列宽:窄 240 / 标准 320 / 宽 480 / 手动 160–720;全局生效,重启保持
|
||||
- [ ] 排序:id 升序 / 最后修改时间降序 / 标题升序(空标题在前);只影响卡片,列始终 id 序;重启保持
|
||||
- [ ] 大数据量:用脚本向一列灌入约 10000 张卡片,滚动流畅、打开工作区无明显卡顿(虚拟化)
|
||||
- [ ] 所有模态在父窗口居中;使用系统原生标题栏
|
||||
- [ ] 打开带输入框的模态时,第一个输入框自动获得焦点并全选
|
||||
|
||||
## D. 标签 tab 与搜索(M6)
|
||||
|
||||
- [ ] 标签 tab 条目:颜色徽章 + 名称 + 描述 + 使用数;顶部显示标签总数;无标签时显示空状态文字
|
||||
- [ ] 新建标签:预置色块或手输 `#RRGGBB`;非法颜色、空名、重名(仅大小写不同也算)→ 模态内提示
|
||||
- [ ] 重命名、改色、改描述后,看板上的徽章同步更新
|
||||
- [ ] 删除标签:确认框提示"将从 N 张卡片移除该标签";删除后卡片保留、只是去掉该标签
|
||||
- [ ] 看板写库(编辑/移动/删除卡片等)后切到标签 tab,使用数已更新
|
||||
- [ ] 搜索仅在点"搜索"或按回车时执行;输入过程中不执行、不报错
|
||||
- [ ] 筛选后空列保留显示;× 清空并显示全部;空白表达式 = 全部
|
||||
- [ ] 非法表达式(如 `bug AND`、`tag:`、`(a`、`id:0`)→ 错误对话框"查询表达式有误,详情:…"+ 英文详情,父窗口居中;关闭后搜索框保留原文,看板保持上次结果
|
||||
- [ ] 筛选状态下写库:按**上次成功**的表达式刷新(即使搜索框已改成别的文字);新建但不匹配的卡片不显示
|
||||
- [ ] USAGE.md 搜索语法示例表逐条实测结果与文档一致
|
||||
|
||||
## E. 设置与关于(M4)
|
||||
|
||||
- [ ] 四个确认开关分别关闭后,对应操作不再弹确认;重启保持
|
||||
- [ ] 关于:应用名、版本号、仓库链接(可点击打开浏览器)、许可证
|
||||
|
||||
## F. 发布(M7,视网络条件推迟)
|
||||
|
||||
- [ ] 在代码托管平台手动触发 `Build` workflow;四个 RID 作业均 build → test → 上传产物
|
||||
- [ ] 产物:`YKanBan-<版本>-win-x64.zip`、`-linux-x64.tar.gz`、`-osx-x64.tar.gz`、`-osx-arm64.tar.gz`
|
||||
- [ ] Windows:解压后 `YKanBan.exe <path>` 可直接运行(自包含,无需安装 .NET)
|
||||
- [ ] Linux:解压后 `./YKanBan <path>` 可运行(可执行位保留)
|
||||
- [ ] macOS:解除隔离后 `open -a YKanBan --args <path>` 与直接运行包内可执行文件均可用;双击 `.app` 只显示参数错误页
|
||||
- [ ] 故意让某平台测试失败 → 该 RID 无产物,其余 RID 不受影响
|
||||
+138
-58
@@ -1,32 +1,52 @@
|
||||
# YKanBan 项目计划(v1.8)
|
||||
# YKanBan 项目计划(v1.9)
|
||||
|
||||
> 本文档是 YKanBan 的完整项目计划,由需求讨论定稿,供执行者照此实施。
|
||||
> 所有设计决策均为定稿结论;如实施中发现问题,应回到计划维护者处修订,而不是自行偏离。
|
||||
|
||||
### v1.9 修订摘要(相对 v1.8)
|
||||
|
||||
- 目标框架定为 **net10.0 LTS**(.NET 9 于 2026-11-10 结束支持),Microsoft.Data.Sqlite 随之升 10.x(§7)
|
||||
- `columns.title` / `tags.name` 唯一约束改为 `COLLATE NOCASE`;首个发布前 schema v1 未冻结,可原地修改(§3)
|
||||
- 搜索:定义 `word` 字符集;`id:` 值须为正整数;限定符值不得为裸 `AND`/`OR`;大小写折叠改为 Unicode(C# 自定义 SQL 函数)(§6)
|
||||
- 排序 combobox 仅作用于卡片,列固定 id 序;选项收敛为 id 升序 / 最后修改时间降序 / 标题升序(§3)
|
||||
- 筛选状态下写库后自动重新应用最近一次成功的表达式(§6.3)
|
||||
- 嵌套模态中新建标签立即写库,作为编辑工作单元的明确例外(§5.4)
|
||||
- app.json:仅脏时写盘;字段级非法值回退默认(§4.3)
|
||||
- 新增"工作区打开失败页"(schema 版本过新 / 数据库无法打开 / IO 与权限错误)(§4.4)
|
||||
- 网络共享明确不支持;命令行参数边界;macOS 无参启动行为写入文档(§2.3、§4.1、附录)
|
||||
- 补充:导出转义规则、卡片列表虚拟化、模态窗口 FlowDirection、`Resources` 类名使用规则、CI osx-x64 运行器(§5、§7、§8)
|
||||
- 依赖:Avalonia 11.3.6 → 11.3.22,Semi.Avalonia 11.2.1.10 → 11.3.22(§7)
|
||||
- 里程碑:标注 M0–M4 已完成,新增 **M4R(v1.9 回补)**(§9)
|
||||
|
||||
## 1. 项目概述
|
||||
|
||||
个人使用的本地/离线看板工具。跨平台桌面应用(Windows / Linux / macOS),类 Git 的工作方式:在被管理项目根目录下创建 `.ykanban` 文件夹存储看板数据。Avalonia UI,MVVM 模式。每个 YKanBan 进程管理一个工作区,可多实例并行(同一工作区由锁文件互斥)。界面默认英文,附简体中文(ResX,切换重启生效,见 §8);主题支持亮色/暗色/跟随系统(默认跟随系统,即时生效,见 §5.9)。
|
||||
|
||||
仓库:<https://code.blumia.cn/yyc12345/YKanBan>(计划正本位于仓库 `docs/PLAN.md`)
|
||||
|
||||
## 2. 存储设计
|
||||
|
||||
### 2.1 存储模型(类 Git)
|
||||
|
||||
- 每个工作区(定义见 §4)= 一个其下存在 `.ykanban` 的路径;`.ykanban/` 内含 `ykanban.db`(SQLite 数据库)与 `ykanban.lock`(锁文件)
|
||||
- 打开文件夹时**只检查当前目录**是否存在 `.ykanban`,不向上递归查找;不存在则询问用户是否在当前目录初始化
|
||||
- 打开工作区时**只检查参数路径本身**是否存在 `.ykanban`,不向上递归查找;不存在则显示未初始化页(见 §4.4),由用户点击初始化按钮在该路径初始化
|
||||
|
||||
### 2.2 数据库配置
|
||||
|
||||
- `PRAGMA journal_mode=WAL` + `PRAGMA synchronous=NORMAL`
|
||||
- 每个连接显式 `PRAGMA foreign_keys=ON`(Microsoft.Data.Sqlite 默认关闭,不开则外键与 CASCADE 均不生效)
|
||||
- 每个连接注册搜索用的大小写折叠自定义函数(见 §6.2)
|
||||
- 不做退出时 checkpoint
|
||||
- 备份/迁移必须同时复制 `ykanban.db`、`ykanban.db-wal`、`ykanban.db-shm` 三个文件(此要求写入 USAGE.md)
|
||||
- `PRAGMA user_version` 管理 schema 版本,启动时按版本增量迁移
|
||||
- `PRAGMA user_version` 管理 schema 版本,启动时按版本增量迁移;数据库版本高于程序支持版本 → 抛类型化异常,显示工作区打开失败页(见 §4.4)
|
||||
- **schema 冻结时点**:首个对外发布(M7 产物)之前,schema v1 可原地修改,开发期数据库直接重建,无需写迁移;发布后任何 schema 变更必须走 `user_version` 增量迁移
|
||||
|
||||
### 2.3 独占访问
|
||||
|
||||
- 每个 `.ykanban` 同一时刻仅允许一个 YKanBan 实例打开
|
||||
- 机制:独占打开 `ykanban.lock`(.NET `FileStream` + `FileShare.None`)持有至退出;锁文件内写 PID/机器名/时间用于诊断;程序崩溃/断电由 OS 自动释放,无残留问题
|
||||
- 锁冲突场景:同机多实例指向同一工作区,或他机经网络共享打开同一 `.ykanban`;界面显示锁冲突页,不提供其他操作
|
||||
- 机制:独占打开 `ykanban.lock`(.NET `FileStream` + `FileShare.None`)持有至退出;锁文件内写 PID/机器名/时间,仅供事后人工诊断(持锁期间冲突方无法读取,锁冲突页不展示这些信息);程序崩溃/断电由 OS 自动释放,无残留问题
|
||||
- 锁冲突场景:同机多实例指向同一工作区;界面显示锁冲突页,不提供其他操作
|
||||
- **网络共享明确不支持**:SQLite WAL 依赖共享内存,无法在网络文件系统上工作;Unix 上 `FileShare.None` 底层为建议锁,经 NFS/SMB 亦不可靠。此限制写入 USAGE.md,程序不做检测
|
||||
|
||||
### 2.4 与 Git 的关系
|
||||
|
||||
@@ -38,28 +58,31 @@
|
||||
|
||||
```
|
||||
columns: id INTEGER PK AUTOINCREMENT,
|
||||
title TEXT NOT NULL UNIQUE CHECK (length(title) > 0),
|
||||
title TEXT NOT NULL CHECK (length(title) > 0),
|
||||
description TEXT NOT NULL DEFAULT '',
|
||||
created_at INT NOT NULL, updated_at INT NOT NULL
|
||||
created_at INT NOT NULL, updated_at INT NOT NULL,
|
||||
UNIQUE (title COLLATE NOCASE) ← 仅唯一性 NOCASE,列本身保持 BINARY(排序按码点)
|
||||
cards: id INTEGER PK AUTOINCREMENT,
|
||||
column_id INT NOT NULL → columns.id ON DELETE CASCADE,
|
||||
title TEXT NOT NULL DEFAULT '',
|
||||
content TEXT NOT NULL DEFAULT '',
|
||||
created_at INT NOT NULL, updated_at INT NOT NULL
|
||||
tags: id INTEGER PK AUTOINCREMENT,
|
||||
name TEXT NOT NULL UNIQUE CHECK (length(name) > 0),
|
||||
name TEXT NOT NULL CHECK (length(name) > 0),
|
||||
color TEXT NOT NULL CHECK (GLOB '#'+六位十六进制,即 #RRGGBB 形态),
|
||||
description TEXT NOT NULL DEFAULT ''
|
||||
description TEXT NOT NULL DEFAULT '',
|
||||
UNIQUE (name COLLATE NOCASE)
|
||||
card_tags: (card_id, tag_id) 复合主键,双向 ON DELETE CASCADE
|
||||
```
|
||||
|
||||
行为约定:
|
||||
|
||||
- 数据校验尽量在 DDL 层完成(CHECK / UNIQUE / FOREIGN KEY),保证入库即合法:
|
||||
- `columns.title`:非空、全表唯一(BINARY 严格比较),无字符集限制
|
||||
- `tags.name`:仅要求非空串,**完全放开**——无字符集/长度限制,允许空格、emoji、保留字符;UI 输入不做 trim
|
||||
- `columns.title`:非空、全表唯一(NOCASE:ASCII 字母大小写不敏感,`Done` 与 `done` 不能共存;非 ASCII 字母按原样比较),无字符集限制
|
||||
- `tags.name`:非空、全表唯一(同上 NOCASE);除此之外**完全放开**——无字符集/长度限制,允许空格、emoji、保留字符;UI 输入不做 trim
|
||||
- `tags.color`:仅接受 `#RRGGBB` 形态(GLOB 校验)
|
||||
- 所有 description 字段无长度上限
|
||||
- 违反约束(空标题、重名)时:在当前模态内显示本地化错误提示,模态不关闭、保留用户输入(UI 按类型化异常映射资源键,见 §8.2)
|
||||
- 时间戳刷新规则:
|
||||
- `cards.updated_at` 仅在卡片编辑模态点"确认"写入时刷新(新建卡片时 created_at = updated_at)
|
||||
- 菜单"移动到列"只改 `column_id`,不刷新卡片 updated_at
|
||||
@@ -74,8 +97,14 @@ card_tags: (card_id, tag_id) 复合主键,双向 ON DELETE CASCADE
|
||||
| 删 card | → 该卡的 card_tags |
|
||||
| 删 tag | → 相关 card_tags(= 卡片卸载该标签,卡片保留) |
|
||||
|
||||
- 禁止手动排序:列内/列间顺序由显示规则计算(id 默认 / 创建时间 / 最后修改时间 / 标题字母序),界面随时可切换、全局一份存 `app.json`(见 §4.3);所有排序一律以 id 升序兜底;标题排序按码点(BINARY collation)
|
||||
- 无标题的唯一表示是空串(`title TEXT NOT NULL DEFAULT ''`);无标题卡片列内不显示占位标题;按标题排序时视为空串
|
||||
- 禁止手动排序,顺序由显示规则计算:
|
||||
- **列**:固定按 id 升序,不受排序选项影响(与导出一致)
|
||||
- **卡片**(列内):界面排序 combobox 三选一,全局一份存 `app.json`(见 §4.3):
|
||||
- id 升序(默认)
|
||||
- 最后修改时间降序(最近修改在上)
|
||||
- 标题升序(按码点,BINARY collation;空标题视为空串、排最前)
|
||||
- 所有排序一律以 id 升序兜底
|
||||
- 无标题的唯一表示是空串(`title TEXT NOT NULL DEFAULT ''`);无标题卡片列内不显示占位标题
|
||||
- 删列 → 级联删卡(UI 二次确认,提示将删 N 张卡片);卡片硬删除(二次确认)
|
||||
- tag 永不自动清理(`tags` 表保留无引用标签),配标签管理界面
|
||||
- 初始化预置三列:初始化时按当前语言直接从 ResX 资源读取(英文 To Do / In Progress / Done;中文 待办 / 进行中 / 已完成),随**创建时刻**的语言写入,此后即为数据、不再随语言切换变化(见 §8)
|
||||
@@ -88,22 +117,30 @@ card_tags: (card_id, tag_id) 复合主键,双向 ON DELETE CASCADE
|
||||
### 4.1 实例模型与启动
|
||||
|
||||
- 每个 YKanBan 进程独立管理一个工作区;多实例可并行运行;同一工作区由锁文件互斥(见 §2.3)
|
||||
- `ykanban <path>`:本实例打开该工作区(主启动方式)
|
||||
- `ykanban`(无参数)或非法参数:显示**参数错误页**(全窗口错误页之一,见 §4.4)
|
||||
- `ykanban <path>`:本实例打开该工作区(唯一启动方式)
|
||||
- 参数规则:
|
||||
- 恰好一个位置参数为合法;相对路径以进程当前工作目录解析为绝对路径
|
||||
- 无参数、多于一个参数、或参数以 `-` 开头(含 `--help` 等任何选项形式)→ **参数错误页**
|
||||
- 路径不存在或存在但不是目录 → 目录不存在页
|
||||
- macOS 双击 `.app` 时无参数,只会显示参数错误页——已接受(纯命令行定位);USAGE.md 说明 macOS 启动方式(`open -a YKanBan --args <path>` 或直接运行包内可执行文件)
|
||||
- 窗口标题:`工作区名 - YKanBan`;无有效工作区(错误页状态)时仅 `YKanBan`
|
||||
|
||||
### 4.2 连接管理
|
||||
|
||||
- 单连接 + 单锁:打开工作区成功即持有,进程生命周期内不释放;正常退出时释放,崩溃/断电由 OS 自动释放
|
||||
- 打开顺序:先取锁,再打开数据库(初始化同理:创建 `.ykanban` → 取锁 → 建库)
|
||||
|
||||
### 4.3 全局配置
|
||||
|
||||
全局配置为 `app.json`(Newtonsoft.Json 13.0.4),位置 `%APPDATA%/YKanBan/`(各平台等价目录):
|
||||
|
||||
- 强类型根对象 `AppConfig` 整体序列化,根含 `"version": 1` 迁移钩子
|
||||
- 字段:语言(`Language`,`"en"` 默认)、主题(`Theme`,`"FollowSystem"` 默认)、卡片排序选择、列宽、四类确认开关
|
||||
- 写入时机:**应用退出时一次性写盘**(直接写,不做原子替换);崩溃/断电丢失当次会话的设置变更(已接受:配置低价值)
|
||||
- 读取:文件缺失 → 默认值启动照常运行(下次退出自然创建);解析失败 → 备份为 `app.json.bak` → 以默认值启动
|
||||
- 字段:语言(`Language`:`"en"` 默认 / `"zh-Hans"`)、主题(`Theme`:`"follow-system"` 默认 / `"light"` / `"dark"`)、卡片排序选择(`"id"` 默认 / `"updated-at"` / `"title"`)、列宽、四类确认开关;枚举值序列化为 kebab-case 字符串
|
||||
- 写入时机:**应用退出时,仅当本实例在会话内修改过任一设置(脏标记)才整体写盘**(直接写,不做原子替换);错误页状态的实例、未改过设置的实例退出时不写。多实例均改过设置时后退出者覆盖(已接受);崩溃/断电丢失当次会话的设置变更(已接受:配置低价值)
|
||||
- 读取:
|
||||
- 文件缺失 → 默认值启动照常运行(下次脏退出时自然创建)
|
||||
- JSON 本身无法解析 → 备份为 `app.json.bak`(覆盖旧备份)→ 以默认值启动
|
||||
- JSON 完好但个别字段非法(未知枚举值、未知语言、列宽越界 160–720、类型不符等)→ **仅该字段回退默认值**,其余字段保留,不生成备份
|
||||
|
||||
### 4.4 全窗口错误页体系
|
||||
|
||||
@@ -111,10 +148,14 @@ card_tags: (card_id, tag_id) 复合主键,双向 ON DELETE CASCADE
|
||||
|
||||
| 错误页 | 触发条件 | 内容 |
|
||||
|---|---|---|
|
||||
| 参数错误页 | 无参数 / 非法参数启动 | 参数错误提示 + 正确用法说明(`ykanban <path>`) |
|
||||
| 目录不存在页 | 参数路径不存在 | 提示 |
|
||||
| 参数错误页 | 参数不合法(见 §4.1) | 参数错误提示 + 正确用法说明(`ykanban <path>`) |
|
||||
| 目录不存在页 | 参数路径不存在或不是目录 | 提示 |
|
||||
| 未初始化页 | 路径存在但无 `.ykanban` | 提示 + 初始化按钮(唯一带操作的错误页) |
|
||||
| 锁冲突页 | 锁文件被占用 | 仅提示,无任何操作 |
|
||||
| 工作区打开失败页 | schema 版本高于程序支持版本;数据库无法打开/损坏;IO 或权限错误(含初始化失败) | 按异常类型显示本地化提示 + 只读可复制的英文异常详情;无其他操作 |
|
||||
|
||||
- 未初始化页点击初始化失败 → 切换至工作区打开失败页
|
||||
- 未被识别的异常类型归入工作区打开失败页的通用提示
|
||||
|
||||
正常视图 = 顶部显示区域 + TabControl(见 §5)。
|
||||
|
||||
@@ -135,8 +176,9 @@ card_tags: (card_id, tag_id) 复合主键,双向 ON DELETE CASCADE
|
||||
**看板选项卡**:
|
||||
|
||||
- 搜索栏(点击搜索按钮才执行,无实时搜索,带 × 一键清空);右侧依次:新增列按钮、列宽调整按钮、排序 combobox
|
||||
- 列宽:模态选择预设窄/标准/宽或手动像素值(范围 160–720,默认"标准"= 320),全局生效,持久化到 app.json
|
||||
- 列宽:模态选择预设窄/标准/宽或手动像素值(窄 = 240 / 标准 = 320 / 宽 = 480;手动范围 160–720,默认"标准"),全局生效,持久化到 app.json
|
||||
- 看板区域(与 GitHub Projects 基本一致):列左→右横排,卡片上→下展开;**无拖拽**
|
||||
- 列内卡片列表必须使用 UI 虚拟化(如 `VirtualizingStackPanel`),满足 10000 张卡片量级的流畅显示
|
||||
- 列右上角:+新建卡片、⋯菜单(编辑、删除);"编辑" = 标题 + description 编辑模态
|
||||
- 卡右上角:⋯菜单(删除、移动到列…);点击卡片本体 → 编辑模态
|
||||
- 卡片条目显示 4 样内容:`#id`(加粗)与标题同行(无标题则仅 `#61`;有标题如 `#61 Foo bar`)、内容按固定字数截断(约 200 字)、标签列于内容下方(彩色徽章:颜色 + 名称)。不显示时间戳
|
||||
@@ -146,16 +188,18 @@ card_tags: (card_id, tag_id) 复合主键,双向 ON DELETE CASCADE
|
||||
非 SPA。新增列 / 新增卡片 / 编辑卡片 / 各类删除确认等操作一律通过模态对话框弹出。
|
||||
|
||||
- 所有模态窗口在父窗口中央弹出(Avalonia `WindowStartupLocation="CenterOwner"` + `ShowDialog(owner)`)
|
||||
- 所有模态窗口与主窗口一样设置 `FlowDirection`(FlowDirection 不跨窗口继承,见 §8.3)
|
||||
- 搜索表达式错误对话框:纯提示型模态(无确认语义),同样父窗口居中(见 §6.2)
|
||||
- 新增列 / 编辑列模态:标题(必填,受 DDL 非空+唯一约束)+ description(可空)
|
||||
- 新增列 / 编辑列模态:标题(必填,受 DDL 非空+唯一约束,违反时模态内提示,见 §3)+ description(可空)
|
||||
|
||||
### 5.4 卡片编辑模态
|
||||
|
||||
- 字段:标题(可空,空串 = 无标题)、内容(多行)、标签区、只读 `#id` / 创建时间 / 修改时间(新增时未生成则不显示)
|
||||
- 底部:确认(当前数据一次性写入数据库)/ 取消(丢弃更改)
|
||||
- 编辑对话框是一个工作单元:确认时一次性落库(单事务,见 §3),取消不产生任何写入;其余操作(删除、移动等)仍即时写库
|
||||
- 编辑对话框是一个工作单元:确认时一次性落库(单事务,见 §3),取消不产生任何卡片/指派写入;其余操作(删除、移动等)仍即时写库
|
||||
- 确认时内容无变化 → 不写库、不刷新时间戳
|
||||
- 标签指派:编辑模态标签区显示已指派标签(各带 × 移除),"添加标签"按钮弹**嵌套模态** = 已有标签搜索/列表 + 新建标签入口,选中即添加,可反复打开继续添加下一个
|
||||
- **例外**:嵌套模态中新建的标签**立即写入 `tags` 表**(标签是全局实体);外层编辑取消时仅丢弃指派关系,新建的标签保留(与"tag 永不自动清理"一致)
|
||||
|
||||
### 5.5 确认对话框开关
|
||||
|
||||
@@ -171,36 +215,43 @@ card_tags: (card_id, tag_id) 复合主键,双向 ON DELETE CASCADE
|
||||
|
||||
### 5.7 关于模态
|
||||
|
||||
应用名、版本号、仓库链接、许可证。入口 = 顶部显示区域右侧,与导出、设置按钮同排。
|
||||
应用名、版本号、仓库链接(<https://code.blumia.cn/yyc12345/YKanBan>)、许可证。入口 = 顶部显示区域右侧,与导出、设置按钮同排。
|
||||
|
||||
### 5.8 导出
|
||||
|
||||
- 点击后弹系统保存文件对话框,默认文件名按当前语言生成(模式为资源键,**精确到秒**):英文 `MyRepo-export-20260930-142537.md`;中文 `MyRepo-导出-20260930-142537.md`
|
||||
- 人类可读格式,无回导需求;模板文本直接读取 ResX 资源(见 §8),导出语言跟随当前界面语言:
|
||||
- 人类可读格式,无回导需求;模板文本直接读取 ResX 资源(见 §8),导出语言跟随当前界面语言
|
||||
- 导出范围为工作区全量数据,不受当前搜索筛选与卡片排序选项影响:列按 id 升序,列内卡片按 id 升序
|
||||
- 全文时间戳(导出时间与卡片创建/修改时间)格式随语言:英文 `yyyy-MM-dd HH:mm:ss`;中文 `yyyy年M月d日 HH:mm`
|
||||
- 结构示例(英文时间格式):
|
||||
|
||||
```markdown
|
||||
# 工作区名
|
||||
> 导出时间:2026-09-30 14:25:37 (全文时间戳——导出时间与卡片创建/修改时间——格式随语言:英文 yyyy-MM-dd HH:mm:ss;中文 yyyy年M月d日 HH:mm)
|
||||
> 导出时间:2026-09-30 14:25:37
|
||||
|
||||
## 列:进行中 (列按 id 序,标题后附卡片数;列 description 紧随标题下显示)
|
||||
## 列:进行中 (1) (标题后附卡片数;列 description 紧随标题下显示)
|
||||
|
||||
### #61 Foo bar
|
||||
正文内容…
|
||||
|
||||
- 标签:`bug` `ui`
|
||||
- 创建:2026-09-01 10:00 修改:2026-09-28 18:30
|
||||
- 创建:2026-09-01 10:00:00 修改:2026-09-28 18:30:00
|
||||
|
||||
## 标签总表
|
||||
| 名称 | 颜色 | 描述 | 使用数 |
|
||||
```
|
||||
|
||||
- 空列也保留(体现看板结构);无标题卡片以 `### #61` 呈现
|
||||
- 转义规则:
|
||||
- 标签名以行内代码呈现,定界反引号数量 = 名称内最长连续反引号串长度 + 1(名称以反引号开头/结尾时两侧加空格)
|
||||
- 标签总表单元格内 `|` → `\|`,换行 → `<br>`
|
||||
- 卡片正文与列 description **原样输出**(接受其中 Markdown 结构干扰文档层级,已接受)
|
||||
|
||||
### 5.9 主题(亮 / 暗 / 跟随系统)
|
||||
|
||||
- 三态选项:亮色 / 暗色 / 跟随系统,**默认跟随系统**
|
||||
- 机制:`Application.Current.RequestedThemeVariant` = `ThemeVariant.Light / Dark / Default`(Default = 继承系统偏好);Semi.Avalonia 两套配色经标准 ThemeVariant 机制生效,运行时切换**即时生效**(含支持平台上窗口标题栏装饰变体)
|
||||
- 持久化:`AppConfig.Theme`(`"FollowSystem"` 默认 / `"Light"` / `"Dark"`)入 app.json,退出时落盘;启动时在主窗口创建前读取应用
|
||||
- 持久化:`AppConfig.Theme`(`"follow-system"` 默认 / `"light"` / `"dark"`)入 app.json,按 §4.3 脏标记规则退出时落盘;启动时在主窗口创建前读取应用
|
||||
- **自定义颜色硬规则**:界面中任何自定义 Brush/Color 资源必须以 `ThemeDictionaries` 成对定义 Light/Dark 两份并经 `DynamicResource` 引用,禁止裸用 `StaticResource` 引颜色,保证主题切换时界面完整变色
|
||||
- 例外:标签颜色是用户数据(固定 `#RRGGBB`),两种主题下均直接显示原色,不做暗色变体
|
||||
|
||||
@@ -221,18 +272,30 @@ orExpr := andExpr ( OR andExpr )*
|
||||
andExpr := operand ( (AND)? operand )* ← 空格相邻 = 隐式 AND
|
||||
operand := atom | '(' orExpr ')'
|
||||
atom := word | phrase | qualifier
|
||||
qualifier := key ':' (word | phrase)
|
||||
qualifier := key ':' value
|
||||
key := tag | title | content | id | column
|
||||
value := word | phrase (tag/title/content/column)
|
||||
| '#'? digit+ (id:十进制正整数,可带前缀 #)
|
||||
word := 一个或多个字符,不含空白及 ( ) " : \ ;且不等于 AND / OR
|
||||
phrase := '"' 任意文本 '"' (内部支持转义:\" → 字面引号,\\ → 字面反斜杠)
|
||||
```
|
||||
|
||||
- 裸词中出现 `:` 时其左侧必须是合法 key,否则为"未知限定符"错误;含 `:` `(` `)` `\` 等字符的搜索值须用引号(如 `"http://x"`)
|
||||
|
||||
### 6.2 语义
|
||||
|
||||
- `AND`(含隐式空格)优先于 `OR`,括号强制结合
|
||||
- 仅大写 `AND`/`OR` 为运算符,小写即普通裸词;搜索字面量大写 AND/OR 需加引号(写入文档)
|
||||
- Atom 语义:裸词/短语 → 标题**或**内容子串匹配;`tag:` 标签精确匹配;`column:` 列标题精确匹配(列名 UNIQUE,无歧义);`title:` / `content:` 字段子串;`id:` 精确匹配;全部不区分大小写;引号支持含空格值
|
||||
- Atom 语义:裸词/短语 → 标题**或**内容子串匹配;`tag:` 标签名精确匹配;`column:` 列标题精确匹配;`title:` / `content:` 字段子串;`id:` 精确匹配;引号支持含空格值
|
||||
- **大小写折叠**:全部匹配不区分大小写,采用 Unicode 折叠——每个连接注册 C# 自定义 SQL 函数(`ToLowerInvariant` 后按 Ordinal 做子串/相等比较),不使用 `LIKE`(因而 `%` `_` 无通配含义,无需转义)。注:唯一约束 NOCASE 仅折叠 ASCII,故 `Ä` 与 `ä` 可作为两个标签共存而 `tag:ä` 同时匹配二者——已接受
|
||||
- 短语内部转义:`\"` → 字面引号,`\\` → 字面反斜杠;搜索含空格/保留字符/字面 `AND` 等特殊标签名时,用(必要时转义的)引号值(写入文档)
|
||||
- **严格校验**:非法表达式弹出错误对话框,不执行搜索。非法集合:括号不配对、运算符悬空(`bug AND`)、连续运算符(`a AND OR b`)、限定符无值(`tag:`)、短语引号未闭合、无效转义(`tag:"a\x"`)、未知限定符 key(合法 key 仅 tag / title / content / id / column)
|
||||
- **严格校验**:非法表达式弹出错误对话框,不执行搜索。非法集合:
|
||||
- 括号不配对
|
||||
- 运算符悬空(`bug AND`)、连续运算符(`a AND OR b`)
|
||||
- 限定符无值(`tag:`)、限定符值为裸 `AND`/`OR`(`tag:AND`,须写 `tag:"AND"`)
|
||||
- 短语引号未闭合、无效转义(`tag:"a\x"`)、裸词中出现 `\`
|
||||
- 未知限定符 key(合法 key 仅 tag / title / content / id / column)
|
||||
- `id:` 值不是十进制正整数(`id:abc`、`id:0`、`id:"61"`)
|
||||
- 错误对话框:模态、父窗口居中;文案 = 资源模板"查询表达式有误,详情:{0}"(i18n),{0} 处拼接解析器返回的**非 i18n 英文错误描述串**(对位置信息无要求)
|
||||
- 空查询与纯空白查询 = 合法(显示全部)
|
||||
- 无时间维度;解析器按可扩展限定符表设计(预留 `created:`、`NOT` 等扩展点)
|
||||
@@ -242,17 +305,19 @@ phrase := '"' 任意文本 '"' (内部支持转义:\" → 字面引号,
|
||||
|
||||
- 点搜索按钮才执行(校验也仅发生在点击时,无实时报错);空查询 = 全显;筛选后空列保留显示(维持看板结构感);搜索状态在会话内自然存续
|
||||
- 表达式非法时:错误对话框关闭后,搜索框保留原文待修改,看板维持上一次筛选结果(错误不破坏现状)
|
||||
- **写库后刷新**:任何写库操作(增删改卡片/列/标签、移动、指派)完成后,以"最近一次成功执行的表达式"(而非搜索框当前文本)重新查询刷新看板;不再匹配的卡片立即消失,新建但不匹配的卡片不显示
|
||||
|
||||
## 7. 技术选型
|
||||
|
||||
版本已经 NuGet 实测调研锁定:
|
||||
|
||||
| 包 | 版本 | 备注 |
|
||||
| 包 / 框架 | 版本 | 备注 |
|
||||
|---|---|---|
|
||||
| Avalonia | **11.3.6 锁定** | 不允许升级 |
|
||||
| Semi.Avalonia | 11.2.1.10 | 11.3.x 全系依赖 Avalonia ≥ 11.3.7 会强制升级,故降用 11.2 线最新;含亮/暗两套配色 |
|
||||
| 目标框架 | **net10.0** | LTS;主项目与测试项目一致 |
|
||||
| Avalonia | **11.3.22 锁定** | 由 11.3.6 升至 11.3 线最新补丁(修复间接依赖 Tmds.DBus.Protocol 0.21.2 的 NU1903 高危通告,随之为 0.21.3);不升 12.x |
|
||||
| Semi.Avalonia | 11.3.22 | 与 Avalonia 同版本号配套;含亮/暗两套配色 |
|
||||
| IconPacks.Avalonia.Lucide | 2.0.0 | 仅此子库,不装全库 IconPacks.Avalonia |
|
||||
| Microsoft.Data.Sqlite | 9.0.20 | 与 net9.0 对齐;手写 SQL |
|
||||
| Microsoft.Data.Sqlite | 10.0.x | 与 net10.0 对齐,取迁移时 10.0 线最新补丁并在 csproj 锁定具体版本;手写 SQL |
|
||||
| Pidgin | 3.5.1 | 搜索 Lexer + Parser |
|
||||
| MSTest | 4.4.1 | 遇问题降 3.11.1 |
|
||||
| Newtonsoft.Json | 13.0.4 | app.json 序列化 |
|
||||
@@ -260,18 +325,19 @@ phrase := '"' 任意文本 '"' (内部支持转义:\" → 字面引号,
|
||||
|
||||
### 7.1 工程结构(单项目原则)
|
||||
|
||||
沿用现有 `YKanBan/` 项目**原地改造**(清理模板内容),重组为(同步更新 `YKanBan.slnx`):
|
||||
沿用现有 `YKanBan/` 项目**原地改造**(M0 已完成),结构为(`YKanBan.slnx` 同步):
|
||||
|
||||
- `YKanBan`:唯一应用项目——模型、schema/迁移、仓库层、搜索解析、导出、平台服务层、Avalonia UI(MVVM);持有全部 ResX 资源;全部包依赖进同一 csproj
|
||||
- `YKanBan.Tests`:MSTest 测试库,引用主项目(连带引入 Avalonia 依赖);纪律规则:**不编写任何 UI 交互测试**(窗口、模态、点击流、数据绑定、主题切换、状态页渲染一律人工验证;不引入 headless UI 测试基础设施)
|
||||
|
||||
**测试范围**:解析器(成功文法全分支 + **错误检测全分支**(每个非法输入断言解析失败且错误消息非空)+ SQL 编译)、schema/DDL 约束实测、`user_version` 迁移、PRAGMA 生效、锁文件独占与释放、app.json 缺失/损坏降级、CRUD 与三条级联链、编辑确认事务原子性、**命令行参数解析**(无参/合法/非法三分支)、导出结构与本地化断言(直接设 `Resources.Culture` 断言 en / zh-Hans 真实输出)。一切测试在本地 Windows 运行。
|
||||
**测试范围**:解析器(成功文法全分支 + **错误检测全分支**(每个非法输入断言解析失败且错误消息非空)+ SQL 编译 + Unicode 大小写折叠)、schema/DDL 约束实测(含 NOCASE 唯一性)、`user_version` 迁移(含版本过新抛类型化异常)、PRAGMA 生效、锁文件独占与释放、app.json 缺失/损坏降级/字段级回退/脏标记写盘、CRUD 与三条级联链、编辑确认事务原子性、**命令行参数解析**(无参/合法/非法/相对路径/选项形式)、导出结构、转义与本地化断言(直接设 `Resources.Culture` 断言 en / zh-Hans 真实输出)。一切测试在本地 Windows 运行。
|
||||
|
||||
### 7.2 平台与发布
|
||||
|
||||
- 锁文件等平台相关代码集中于跨平台接口的平台服务层(内部组织习惯,非强制架构)
|
||||
- 发布目标:win-x64 / linux-x64 / osx-x64 / osx-arm64
|
||||
- **单一 GitHub workflow**:仅 `workflow_dispatch` 手动触发;4 RID 矩阵,每个平台作业依次执行 **build → test → 测试通过后上传该 RID 的 artifact**(压缩包);测试失败该 RID 不出产物;不创建 GitHub Release
|
||||
- 运行器:osx-x64 作业须使用 Intel 运行器(`macos-15-intel`;`macos-13` 已下线),osx-arm64 用 `macos-15`,其余用 `windows-latest` / `ubuntu-latest`
|
||||
- 开发机访问不到 GitHub:**禁止任何依赖 push 触发的 CI**
|
||||
- 开发期测试策略:一切验证在**本地 Windows** 进行(`dotnet build` + `dotnet test`);各里程碑的"单测/人工"验证均指本地 Windows 执行;Linux/macOS 行为验证**无限期推迟**至程序完工后(明确接受平台 bug 风险)
|
||||
|
||||
@@ -280,42 +346,56 @@ phrase := '"' 任意文本 '"' (内部支持转义:\" → 字面引号,
|
||||
### 8.1 语言与资源
|
||||
|
||||
- 支持语言:**英文(默认)+ 简体中文(zh-Hans)**,仅此两种
|
||||
- ResX 位于唯一主项目:`Resources.resx`(英文 neutral,missing key 回落英文)+ `Resources.zh-Hans.resx`;XAML 用 `{x:Static lang:Resources.Key}`
|
||||
- ResX 位于唯一主项目(`Assets/Locales/`):`Resources.resx`(英文 neutral,missing key 回落英文)+ `Resources.zh-Hans.resx`;XAML 用 `{x:Static lang:Resources.Key}`
|
||||
- 公共 Resources 类用跨平台 MSBuild 方案生成(`Generator=MSBuild:Compile` + `StronglyTypedFileName`(写入 obj/)+ `StronglyTypedNamespace` + `StronglyTypedClassName=Resources` + `PublicClass=true`),不用 VS 专属生成器
|
||||
- **类名使用规则**:生成类 `Resources` 与 Avalonia 实例属性 `StyledElement.Resources` / `Application.Resources` 同名;在控件、Window、Application 的代码隐藏中一律写全限定名 `YKanBan.Resources`,禁止裸写 `Resources.Key`(否则会解析到实例属性)
|
||||
- M4 起硬性规则:**所有 UI 文本一律资源键**,英文文本也只写在 Resources.resx,禁止硬编码
|
||||
|
||||
### 8.2 资源访问与异常策略
|
||||
|
||||
- 需要本地化文本的代码(Markdown 导出生成器、初始化预置列名等)**直接读取 ResX 资源**(`Resources` 类全局可用);导出测试可直接设 `Resources.Culture` 断言 en / zh-Hans 真实输出
|
||||
- 异常策略:异常消息**一律英文、永不本地化**——异常携带本地化文本是坏实践(抛出与显示时刻 culture 不一致、日志难检索);对需区分展示的场景(锁冲突、未初始化、目录不存在、schema 版本问题等)定义**类型化异常**,UI 按异常类型映射资源键显示本地化文案
|
||||
- 异常策略:异常消息**一律英文、永不本地化**——异常携带本地化文本是坏实践(抛出与显示时刻 culture 不一致、日志难检索);对需区分展示的场景(锁冲突、未初始化、目录不存在、schema 版本过新、数据库无法打开、约束冲突等)定义**类型化异常**,UI 按异常类型映射资源键显示本地化文案
|
||||
|
||||
### 8.3 语言切换与启动时序
|
||||
|
||||
- `AppConfig.Language`(`"en"` 默认)存 app.json;设置模态中切换(英文/简体中文)并提示"重启后生效"
|
||||
- 启动时序:读 app.json → 在 `OnFrameworkInitializationCompleted` **创建主窗口之前**设置 `Resources.Culture = new CultureInfo(language)` → 同时按 `CultureInfo.TextInfo.IsRightToLeft` 检测并设置主窗口 `FlowDirection`
|
||||
- `AppConfig.Language`(`"en"` 默认 / `"zh-Hans"`)存 app.json;设置模态中切换(英文/简体中文)并提示"重启后生效"
|
||||
- 启动时序:读 app.json → 在 `OnFrameworkInitializationCompleted` **创建主窗口之前**设置 `Resources.Culture = new CultureInfo(language)` → 同时按 `CultureInfo.TextInfo.IsRightToLeft` 检测 `FlowDirection`,应用于主窗口及**每个模态窗口**(FlowDirection 不跨窗口继承)
|
||||
- **RTL 检测代码必须实现**——当前两语言均为 LTR 也不许省略,作为未来语言扩展的基础设施
|
||||
- 与 app.json 退出写盘策略天然吻合:切换语言 → 退出时落盘 → 重启生效
|
||||
- 与 app.json 退出写盘策略天然吻合:切换语言(置脏)→ 退出时落盘 → 重启生效
|
||||
|
||||
## 9. 里程碑
|
||||
|
||||
| 阶段 | 内容 | 验证 |
|
||||
|---|---|---|
|
||||
| M0 工程重组 | 现有项目原地改造(清理模板内容)+ 新建 `YKanBan.Tests`、按版本表装依赖 | 本地 Windows build + test 通过 |
|
||||
| M1 基础设施 | 工作区 schema(含 CHECK/UNIQUE 约束)+ user_version 迁移、PRAGMA、锁文件、app.json、命令行参数解析(无参/合法/非法)、初始化预置三列(列名直接读 ResX) | 单测 |
|
||||
| M2 仓库层 | CRUD/移动/级联/标签指派、单连接生命周期 | 单测 |
|
||||
| M3 搜索与导出 | Pidgin 解析器(严格校验,非法输入返回英文错误消息)、查询→SQL 编译、Markdown 导出(直接读 ResX,en / zh-Hans 输出均有测试) | 单测(成功与错误全分支) |
|
||||
| M4 GUI 框架 | 主题/图标接入、主窗口布局(顶部区 + TabControl + **全窗口错误页体系**,含参数错误页)、设置/关于模态;**ResX 基础设施、语言设置项、RTL/FlowDirection 检测、全 UI 文本资源化(硬规则生效);亮/暗/跟随系统主题基础设施与设置项、ThemeDictionaries 颜色硬规则** | 人工 |
|
||||
| M5 看板界面 | 看板 tab 全部交互与模态 | 人工 |
|
||||
| M6 标签与搜索集成 | 标签 tab、搜索执行与空列保留、导出接线(含文件名/时间戳 i18n 模式) | 人工 |
|
||||
| M7 发布与文档 | 单一 workflow(4 RID 矩阵 build→test→artifact)文件就绪(结构自查)、根目录 USAGE.md、README(引用 USAGE.md)、人工验收清单(含语言切换重启生效、导出语言跟随界面、主题三态切换三项) | workflow 结构自查通过;实际触发与产物验证视网络条件推迟 |
|
||||
| 阶段 | 状态 | 内容 | 验证 |
|
||||
|---|---|---|---|
|
||||
| M0 工程重组 | 已完成 | 现有项目原地改造(清理模板内容)+ 新建 `YKanBan.Tests`、按版本表装依赖 | 本地 Windows build + test 通过 |
|
||||
| M1 基础设施 | 已完成 | 工作区 schema(含 CHECK/UNIQUE 约束)+ user_version 迁移、PRAGMA、锁文件、app.json、命令行参数解析、**ResX 资源基础设施与类型化异常**、初始化预置三列(列名直接读 ResX) | 单测 |
|
||||
| M2 仓库层 | 已完成 | CRUD/移动/级联/标签指派、单连接生命周期 | 单测 |
|
||||
| M3 搜索与导出 | 已完成 | Pidgin 解析器(严格校验,非法输入返回英文错误消息)、查询→SQL 编译、Markdown 导出(直接读 ResX,en / zh-Hans 输出均有测试) | 单测(成功与错误全分支) |
|
||||
| M4 GUI 框架 | 已完成 | 主题/图标接入、主窗口布局(顶部区 + TabControl + 全窗口错误页体系)、设置/关于模态;全 UI 文本资源化(硬规则生效)、语言设置项、RTL/FlowDirection 检测;亮/暗/跟随系统主题基础设施与设置项、ThemeDictionaries 颜色硬规则 | 人工 |
|
||||
| **M4R v1.9 回补** | 已完成 | 见下方清单 | 本地 Windows build + test 通过;新增页面人工 |
|
||||
| M5 看板界面 | 已完成(待人工验收) | 看板 tab 全部交互与模态(含约束冲突模态内提示、卡片列表虚拟化、嵌套模态新建标签立即写库、写库后按最近成功表达式刷新) | 人工 |
|
||||
| M6 标签与搜索集成 | 已完成(待人工验收) | 标签 tab、搜索执行与空列保留、导出接线(含文件名/时间戳 i18n 模式) | 人工 |
|
||||
| M7 发布与文档 | 已完成(待人工验收;workflow 实际触发推迟) | 单一 workflow(4 RID 矩阵 build→test→artifact,osx-x64 用 Intel 运行器)文件就绪(结构自查)、根目录 USAGE.md、README(引用 USAGE.md)、人工验收清单(含语言切换重启生效、导出语言跟随界面、主题三态切换、app.json 多实例脏写四项) | workflow 结构自查通过;实际触发与产物验证视网络条件推迟 |
|
||||
|
||||
依赖链:M0 → M1 → M2 → M3 → M4 → M5 → M6 → M7
|
||||
**M4R 清单**(v1.9 对已完成里程碑的回补,进入 M5 前完成):
|
||||
|
||||
1. TFM 迁移至 net10.0(主项目与测试项目),Microsoft.Data.Sqlite 升至 10.0 线最新补丁并锁定
|
||||
2. schema v1 原地修改:`columns.title` / `tags.name` 加 `COLLATE NOCASE`;补 NOCASE 唯一性测试
|
||||
3. 搜索:按 §6.1 收紧 `word` 字符集、`id:` 正整数校验、限定符值禁裸 `AND`/`OR`;匹配改用注册的 Unicode 折叠自定义函数(替换 LIKE/lower 方案,若现有实现使用);补对应成功/错误分支测试
|
||||
4. 排序选项删除"创建时间"(`CardSortOption.CreatedAt`);`updated-at` 为降序;列排序固定 id 升序
|
||||
5. app.json:脏标记写盘、字段级非法值回退;补测试
|
||||
6. 导出:§5.8 转义规则与时间格式核对;补测试
|
||||
7. 新增工作区打开失败页(§4.4),接入 `SchemaVersionException` 等类型化异常;命令行参数按 §4.1 边界核对
|
||||
8. 模态窗口 FlowDirection 设置(§8.3);代码隐藏中 `Resources` 全限定名核查(§8.1)
|
||||
|
||||
依赖链:M0 → M1 → M2 → M3 → M4 → M4R → M5 → M6 → M7
|
||||
|
||||
## 附录:用户文档(USAGE.md)
|
||||
|
||||
`README.md` 引用根目录 `USAGE.md`;`USAGE.md` 必载以下四项:
|
||||
`README.md` 引用根目录 `USAGE.md`;`USAGE.md` 必载以下五项:
|
||||
|
||||
1. `.ykanban` 不应提交进 Git,建议加入全局 gitignore
|
||||
2. 备份/迁移必须同时复制 `ykanban.db`、`ykanban.db-wal`、`ykanban.db-shm` 三个文件
|
||||
3. 搜索语法全文(文法、语义、转义规则、保留字、严格校验与非法表达式清单、错误对话框行为,见 §6)
|
||||
4. 命令行启动规则(`ykanban <path>`;无参数/非法参数 → 参数错误页,见 §4.1)
|
||||
2. 备份/迁移必须同时复制 `ykanban.db`、`ykanban.db-wal`、`ykanban.db-shm` 三个文件;不支持将工作区放在网络共享(SMB/NFS)上
|
||||
3. 搜索语法全文(文法、语义、`word` 字符集、转义规则、保留字、大小写折叠、严格校验与非法表达式清单、错误对话框行为,见 §6)
|
||||
4. 命令行启动规则(`ykanban <path>`;参数规则与各错误页,见 §4.1)
|
||||
5. macOS 启动方式(`open -a YKanBan --args <path>` 或直接运行包内可执行文件;双击 `.app` 只会显示参数错误页)
|
||||
@@ -0,0 +1,24 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>CFBundleName</key>
|
||||
<string>YKanBan</string>
|
||||
<key>CFBundleDisplayName</key>
|
||||
<string>YKanBan</string>
|
||||
<key>CFBundleIdentifier</key>
|
||||
<string>cn.blumia.code.yyc12345.ykanban</string>
|
||||
<key>CFBundleExecutable</key>
|
||||
<string>YKanBan</string>
|
||||
<key>CFBundlePackageType</key>
|
||||
<string>APPL</string>
|
||||
<key>CFBundleShortVersionString</key>
|
||||
<string>@VERSION@</string>
|
||||
<key>CFBundleVersion</key>
|
||||
<string>@VERSION@</string>
|
||||
<key>CFBundleInfoDictionaryVersion</key>
|
||||
<string>6.0</string>
|
||||
<key>NSHighResolutionCapable</key>
|
||||
<true/>
|
||||
</dict>
|
||||
</plist>
|
||||
Executable
+58
@@ -0,0 +1,58 @@
|
||||
#!/usr/bin/env bash
|
||||
# Packs one published RID into a release archive.
|
||||
#
|
||||
# packaging/package.sh <rid> <publish-dir> <output-dir> <version>
|
||||
#
|
||||
# win-x64 -> YKanBan-<version>-win-x64.zip (folder YKanBan-<version>-win-x64/)
|
||||
# linux-x64 -> YKanBan-<version>-linux-x64.tar.gz (folder YKanBan-<version>-linux-x64/)
|
||||
# osx-* -> YKanBan-<version>-<rid>.tar.gz (YKanBan.app bundle, ad-hoc signed when codesign exists)
|
||||
#
|
||||
# tar.gz keeps the executable bit, which a plain zip artifact upload would lose.
|
||||
set -euo pipefail
|
||||
|
||||
if [ "$#" -ne 4 ]; then
|
||||
echo "usage: $0 <rid> <publish-dir> <output-dir> <version>" >&2
|
||||
exit 2
|
||||
fi
|
||||
|
||||
rid="$1"
|
||||
publish_dir="$(cd "$2" && pwd)"
|
||||
mkdir -p "$3"
|
||||
output_dir="$(cd "$3" && pwd)"
|
||||
version="$4"
|
||||
script_dir="$(cd "$(dirname "$0")" && pwd)"
|
||||
name="YKanBan-${version}-${rid}"
|
||||
staging="$(mktemp -d)"
|
||||
trap 'rm -rf "$staging"' EXIT
|
||||
|
||||
case "$rid" in
|
||||
win-*)
|
||||
cp -R "$publish_dir" "$staging/$name"
|
||||
# Compress-Archive is available on every Windows host, unlike zip.
|
||||
powershell -NoProfile -Command \
|
||||
"Compress-Archive -Path '$(cygpath -w "$staging/$name" 2>/dev/null || echo "$staging/$name")' -DestinationPath '$(cygpath -w "$output_dir/$name.zip" 2>/dev/null || echo "$output_dir/$name.zip")' -Force"
|
||||
;;
|
||||
linux-*)
|
||||
cp -R "$publish_dir" "$staging/$name"
|
||||
chmod +x "$staging/$name/YKanBan"
|
||||
tar -C "$staging" -czf "$output_dir/$name.tar.gz" "$name"
|
||||
;;
|
||||
osx-*)
|
||||
app="$staging/YKanBan.app"
|
||||
mkdir -p "$app/Contents/MacOS"
|
||||
cp -R "$publish_dir/." "$app/Contents/MacOS/"
|
||||
chmod +x "$app/Contents/MacOS/YKanBan"
|
||||
sed "s/@VERSION@/${version}/g" "$script_dir/macos/Info.plist" > "$app/Contents/Info.plist"
|
||||
if command -v codesign > /dev/null 2>&1; then
|
||||
# Ad-hoc signature: unsigned arm64 code does not run at all.
|
||||
codesign --force --deep --sign - "$app"
|
||||
fi
|
||||
tar -C "$staging" -czf "$output_dir/$name.tar.gz" YKanBan.app
|
||||
;;
|
||||
*)
|
||||
echo "unsupported RID: $rid" >&2
|
||||
exit 2
|
||||
;;
|
||||
esac
|
||||
|
||||
echo "packed $rid -> $output_dir"
|
||||
Reference in new issue
Block a user