6 Commits
119 changed files with 4549 additions and 1097 deletions

No files matched your search

+1 -1
View File
@@ -18,7 +18,7 @@ indent_size = 4
tab_width = 4 tab_width = 4
# New line preferences # New line preferences
insert_final_newline = false insert_final_newline = true
#### .NET Coding Conventions #### #### .NET Coding Conventions ####
[*.{cs,vb}] [*.{cs,vb}]
+56
View File
@@ -0,0 +1,56 @@
name: Build
# Manual trigger only. There is no push/pull_request trigger on purpose:
# the project must not depend on push-triggered CI.
on:
workflow_dispatch:
# Least privilege: the workflow only reads the repository and uploads artifacts.
permissions:
contents: read
jobs:
build:
name: ${{ matrix.rid }}
runs-on: ${{ matrix.os }}
strategy:
# One failing RID must not cancel the others.
fail-fast: false
matrix:
include:
- rid: win-x64
os: windows-latest
- rid: linux-x64
os: ubuntu-latest
- rid: osx-arm64
os: macos-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Setup .NET
uses: actions/setup-dotnet@v4
with:
dotnet-version: 9.0.x
- name: Restore
run: dotnet restore YKanBan.slnx
- name: Build
run: dotnet build YKanBan.slnx -c Release --no-restore
# A failing test fails the job, so the publish and upload steps below are
# skipped and this RID produces no artifact.
- name: Test
run: dotnet test YKanBan.slnx -c Release --no-build --no-restore
- name: Publish
run: dotnet publish YKanBan/YKanBan.csproj -c Release -r ${{ matrix.rid }} --self-contained true -o publish/${{ matrix.rid }}
- name: Upload artifact
uses: actions/upload-artifact@v4
with:
name: YKanBan-${{ matrix.rid }}
path: publish/${{ matrix.rid }}
if-no-files-found: error
+11 -2
View File
@@ -1,5 +1,14 @@
# YKanBan # YKanBan
My personal used local/offline kanban. A personal, local/offline kanban board. Cross-platform desktop app built with Avalonia UI and MVVM. Each workspace stores its data in a `.ykanban` folder at the project root, Git-style.
WIP. See [USAGE.md](USAGE.md) for workspaces, backups, the search syntax and command-line usage.
## Build and test
```
dotnet build YKanBan.slnx
dotnet test YKanBan.slnx
```
Packages are pinned in `YKanBan/YKanBan.csproj`.
+91
View File
@@ -0,0 +1,91 @@
# YKanBan Usage
YKanBan is a local/offline kanban board. It works like Git in one respect: all data for a managed project lives in a `.ykanban` folder at the project root, so the board travels with the project folder.
## 1. Workspace
- A **workspace** is a folder that directly contains a `.ykanban` directory. Only the given folder is checked; parent folders are never searched.
- `.ykanban` contains `ykanban.db` (the SQLite database with the board, cards and tags) and `ykanban.lock` (the exclusive lock file).
- A workspace is opened by exactly one YKanBan instance at a time. Opening the same workspace a second time shows the lock-conflict page.
### Command line
```
ykanban <path>
```
- `<path>` is the workspace folder to open.
- Starting without arguments, or with invalid arguments, shows the argument error page.
- If the path does not exist, the folder-missing page is shown.
- If the folder exists but has no `.ykanban`, the not-initialized page is shown with an **Initialize Workspace** button. Initializing creates the database and seeds the preset columns and tags in the current interface language.
## 2. Do not commit `.ykanban` to Git
`.ykanban` holds machine-local state and a lock file; it should not be committed. Add it to your **global** gitignore so it is ignored in every repository:
```
# ~/.gitignore_global (or %USERPROFILE%\.gitignore_global on Windows)
.ykanban/
```
Then enable the global ignore file once:
```
git config --global core.excludesFile ~/.gitignore_global
```
## 3. Backing up and migrating a workspace
The database runs in SQLite WAL mode. A workspace is therefore **three files**, not one: `ykanban.db`, `ykanban.db-wal` and `ykanban.db-shm`.
To back up or move a workspace, copy **all three files together** while YKanBan is closed. Copying only `ykanban.db` can lose the most recent changes.
## 4. Search syntax
The board search runs only when you press the search button (or press Enter in the search box); there is no live search. A blank query shows everything. The clear button (×) empties the box and restores the full board.
Search keywords (`AND`, `OR`) and qualifier keys are fixed English grammar and are **never localized**.
### 4.1 Grammar
```
query := orExpr
orExpr := andExpr ( OR andExpr )*
andExpr := operand ( (AND)? operand )* // adjacent terms are an implicit AND
operand := atom | '(' orExpr ')'
atom := word | phrase | qualifier
qualifier := key ':' (word | phrase)
key := tag | title | content | id | column
phrase := '"' any text '"' // escapes: \" to literal quote and \\ to literal backslash
```
### 4.2 Semantics
- `AND` (explicit or by adjacency) binds tighter than `OR`; parentheses force grouping.
- Only uppercase `AND` / `OR` are operators. Lowercase `and` / `or` are plain words. To search for the literal words `AND` or `OR`, quote them, for example `"AND"`.
- A bare word or phrase matches a **substring of the title OR the content**.
- `tag:NAME` matches a tag by its **exact** name.
- `column:TITLE` matches a column by its **exact** title.
- `title:TEXT` matches a substring of the card title, and `content:TEXT` matches a substring of the card content.
- `id:N` matches a card by its **exact** numeric id.
- All matching is case-insensitive (SQLite ASCII semantics).
- Quotes allow values with spaces, for example `tag:"release notes"` or `column:"In Progress"`.
- Inside a phrase, `\"` produces a literal quote and `\\` a literal backslash.
### 4.3 Strict validation
An invalid expression opens a modal error dialog and **does not run the search**. The error dialog is centered on the parent window; its text is a localized "query expression is invalid" message plus the parser's non-localized English detail. After closing it, the search box keeps what you typed and the board keeps the previous results.
The following are invalid:
- unbalanced parentheses, for example `(a` or `a)`;
- a dangling operator, for example `bug AND`;
- consecutive operators, for example `a AND OR b`;
- a qualifier without a value, for example `tag:`;
- an unterminated phrase, for example `"abc`;
- an invalid escape inside a phrase (a backslash not followed by `"` or `\`), for example `tag:"a\x"`;
- an unknown qualifier key. Only `tag`, `title`, `content`, `id` and `column` are valid, and the key is case-sensitive, so `Tag:x` is an error. A word whose colon is not preceded by an identifier (for example `:foo`) is treated as plain text.
## 5. Export
The **Export** button writes a human-readable Markdown snapshot of the whole board (columns, cards and the tag table) to a file you choose. The suggested file name and the timestamps in the document follow the current interface language. The export is read-only; there is no import.
+16 -33
View File
@@ -1,5 +1,6 @@
using System.Globalization; using System.Globalization;
using System.Text; using System.Text;
using YKanBan.Export; using YKanBan.Export;
using YKanBan.Models; using YKanBan.Models;
@@ -14,8 +15,7 @@ namespace YKanBan.Tests.Export;
/// </summary> /// </summary>
[TestClass] [TestClass]
[DoNotParallelize] [DoNotParallelize]
public class MarkdownExporterTests public class MarkdownExporterTests {
{
private static readonly DateTimeOffset ExportedAt = new(2026, 9, 30, 14, 25, 37, TimeSpan.Zero); private static readonly DateTimeOffset ExportedAt = new(2026, 9, 30, 14, 25, 37, TimeSpan.Zero);
/// <summary> /// <summary>
@@ -46,8 +46,7 @@ public class MarkdownExporterTests
/// Builds the board fixture: one working column with two cards, one empty column and two tags. /// Builds the board fixture: one working column with two cards, one empty column and two tags.
/// </summary> /// </summary>
/// <returns>The columns, cards and tag/usage tuples.</returns> /// <returns>The columns, cards and tag/usage tuples.</returns>
private static (IReadOnlyList<ColumnModel> Columns, IReadOnlyList<CardModel> Cards, IReadOnlyList<(TagModel, long)> Tags) CreateBoard() private static (IReadOnlyList<ColumnModel> Columns, IReadOnlyList<CardModel> Cards, IReadOnlyList<(TagModel, long)> Tags) CreateBoard() {
{
long created = UnixTimeOf(2026, 9, 1, 10, 0); long created = UnixTimeOf(2026, 9, 1, 10, 0);
long updated = UnixTimeOf(2026, 9, 28, 18, 30); long updated = UnixTimeOf(2026, 9, 28, 18, 30);
@@ -71,8 +70,7 @@ public class MarkdownExporterTests
/// Renders the fixture board with the exporter under the current culture. /// Renders the fixture board with the exporter under the current culture.
/// </summary> /// </summary>
/// <returns>The produced Markdown document.</returns> /// <returns>The produced Markdown document.</returns>
private static string ExportBoard() private static string ExportBoard() {
{
(IReadOnlyList<ColumnModel> columns, IReadOnlyList<CardModel> cards, IReadOnlyList<(TagModel, long)> tags) = CreateBoard(); (IReadOnlyList<ColumnModel> columns, IReadOnlyList<CardModel> cards, IReadOnlyList<(TagModel, long)> tags) = CreateBoard();
return MarkdownExporter.Export("MyRepo", columns, cards, tags, ExportedAt); return MarkdownExporter.Export("MyRepo", columns, cards, tags, ExportedAt);
} }
@@ -82,8 +80,7 @@ public class MarkdownExporterTests
/// </summary> /// </summary>
/// <param name="culture">The UI culture.</param> /// <param name="culture">The UI culture.</param>
/// <returns>The expected Markdown document.</returns> /// <returns>The expected Markdown document.</returns>
private static string BuildExpected(CultureInfo culture) private static string BuildExpected(CultureInfo culture) {
{
string created = Local(2026, 9, 1, 10, 0).ToString(Resources.Export_CardTimePattern, 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 updated = Local(2026, 9, 28, 18, 30).ToString(Resources.Export_CardTimePattern, culture);
@@ -133,38 +130,30 @@ public class MarkdownExporterTests
/// Asserts that the exporter output matches the resource-built expected document. /// Asserts that the exporter output matches the resource-built expected document.
/// </summary> /// </summary>
/// <param name="culture">The UI culture to test.</param> /// <param name="culture">The UI culture to test.</param>
private static void AssertOutputMatches(CultureInfo culture) private static void AssertOutputMatches(CultureInfo culture) {
{
CultureInfo? original = Resources.Culture; CultureInfo? original = Resources.Culture;
try try {
{
Resources.Culture = culture; Resources.Culture = culture;
Assert.AreEqual(Normalize(BuildExpected(culture)), Normalize(ExportBoard())); Assert.AreEqual(Normalize(BuildExpected(culture)), Normalize(ExportBoard()));
} } finally {
finally
{
Resources.Culture = original; Resources.Culture = original;
} }
} }
[TestMethod] [TestMethod]
public void EnglishOutputMatchesTemplate() public void EnglishOutputMatchesTemplate() {
{
AssertOutputMatches(new CultureInfo("en")); AssertOutputMatches(new CultureInfo("en"));
} }
[TestMethod] [TestMethod]
public void ChineseOutputMatchesTemplate() public void ChineseOutputMatchesTemplate() {
{
AssertOutputMatches(new CultureInfo("zh-Hans")); AssertOutputMatches(new CultureInfo("zh-Hans"));
} }
[TestMethod] [TestMethod]
public void FileNameFollowsLanguage() public void FileNameFollowsLanguage() {
{
CultureInfo? original = Resources.Culture; CultureInfo? original = Resources.Culture;
try try {
{
Resources.Culture = new CultureInfo("en"); Resources.Culture = new CultureInfo("en");
Assert.AreEqual( Assert.AreEqual(
string.Format(Resources.Culture, Resources.Export_FileNamePattern, "MyRepo", ExportedAt), string.Format(Resources.Culture, Resources.Export_FileNamePattern, "MyRepo", ExportedAt),
@@ -174,19 +163,15 @@ public class MarkdownExporterTests
Assert.AreEqual( Assert.AreEqual(
string.Format(Resources.Culture, Resources.Export_FileNamePattern, "MyRepo", ExportedAt), string.Format(Resources.Culture, Resources.Export_FileNamePattern, "MyRepo", ExportedAt),
MarkdownExporter.BuildFileName("MyRepo", ExportedAt)); MarkdownExporter.BuildFileName("MyRepo", ExportedAt));
} } finally {
finally
{
Resources.Culture = original; Resources.Culture = original;
} }
} }
[TestMethod] [TestMethod]
public void TagTableCellsEscapePipesAndLineBreaks() public void TagTableCellsEscapePipesAndLineBreaks() {
{
CultureInfo? original = Resources.Culture; CultureInfo? original = Resources.Culture;
try try {
{
Resources.Culture = new CultureInfo("en"); Resources.Culture = new CultureInfo("en");
var tag = new TagModel(1, "a|b", RgbColor.Parse("#112233"), "first\nsecond"); var tag = new TagModel(1, "a|b", RgbColor.Parse("#112233"), "first\nsecond");
string markdown = MarkdownExporter.Export( string markdown = MarkdownExporter.Export(
@@ -197,9 +182,7 @@ public class MarkdownExporterTests
ExportedAt); ExportedAt);
StringAssert.Contains(markdown, "| a\\|b | #112233 | first second | 0 |"); StringAssert.Contains(markdown, "| a\\|b | #112233 | first second | 0 |");
} } finally {
finally
{
Resources.Culture = original; Resources.Culture = original;
} }
} }
@@ -7,32 +7,27 @@ namespace YKanBan.Tests.Launching;
/// three branches: no argument, one valid path, and invalid input. /// three branches: no argument, one valid path, and invalid input.
/// </summary> /// </summary>
[TestClass] [TestClass]
public class LaunchArgumentsTests public class LaunchArgumentsTests {
{
[TestMethod] [TestMethod]
public void NoArgumentsIsRejected() public void NoArgumentsIsRejected() {
{
Assert.IsFalse(LaunchArguments.TryParse([], out string? path)); Assert.IsFalse(LaunchArguments.TryParse([], out string? path));
Assert.IsNull(path); Assert.IsNull(path);
} }
[TestMethod] [TestMethod]
public void BlankArgumentIsRejected() public void BlankArgumentIsRejected() {
{
Assert.IsFalse(LaunchArguments.TryParse([" "], out string? path)); Assert.IsFalse(LaunchArguments.TryParse([" "], out string? path));
Assert.IsNull(path); Assert.IsNull(path);
} }
[TestMethod] [TestMethod]
public void MoreThanOneArgumentIsRejected() public void MoreThanOneArgumentIsRejected() {
{
Assert.IsFalse(LaunchArguments.TryParse(["a", "b"], out string? path)); Assert.IsFalse(LaunchArguments.TryParse(["a", "b"], out string? path));
Assert.IsNull(path); Assert.IsNull(path);
} }
[TestMethod] [TestMethod]
public void SinglePathIsAccepted() public void SinglePathIsAccepted() {
{
bool parsed = LaunchArguments.TryParse([@"C:\Repo\MyProject"], out string? path); bool parsed = LaunchArguments.TryParse([@"C:\Repo\MyProject"], out string? path);
Assert.IsTrue(parsed); Assert.IsTrue(parsed);
Assert.AreEqual(@"C:\Repo\MyProject", path); Assert.AreEqual(@"C:\Repo\MyProject", path);
+9 -18
View File
@@ -7,11 +7,9 @@ namespace YKanBan.Tests.Models;
/// boundary in both directions. /// boundary in both directions.
/// </summary> /// </summary>
[TestClass] [TestClass]
public class RgbColorTests public class RgbColorTests {
{
[TestMethod] [TestMethod]
public void ParseSplitsComponents() public void ParseSplitsComponents() {
{
RgbColor color = RgbColor.Parse("#102030"); RgbColor color = RgbColor.Parse("#102030");
Assert.AreEqual((byte)0x10, color.R); Assert.AreEqual((byte)0x10, color.R);
Assert.AreEqual((byte)0x20, color.G); Assert.AreEqual((byte)0x20, color.G);
@@ -22,8 +20,7 @@ public class RgbColorTests
[DataRow("#a1B2c3")] [DataRow("#a1B2c3")]
[DataRow("#A1B2C3")] [DataRow("#A1B2C3")]
[DataRow("#a1b2c3")] [DataRow("#a1b2c3")]
public void ParseIsCaseInsensitive(string text) public void ParseIsCaseInsensitive(string text) {
{
Assert.AreEqual(new RgbColor(0xA1, 0xB2, 0xC3), RgbColor.Parse(text)); Assert.AreEqual(new RgbColor(0xA1, 0xB2, 0xC3), RgbColor.Parse(text));
} }
@@ -36,41 +33,35 @@ public class RgbColorTests
[DataRow("#12345g")] [DataRow("#12345g")]
[DataRow(" #112233")] [DataRow(" #112233")]
[DataRow("#112233 ")] [DataRow("#112233 ")]
public void ParseRejectsMalformedText(string text) public void ParseRejectsMalformedText(string text) {
{
Assert.ThrowsExactly<FormatException>(() => RgbColor.Parse(text)); Assert.ThrowsExactly<FormatException>(() => RgbColor.Parse(text));
} }
[TestMethod] [TestMethod]
public void TryParseRejectsNull() public void TryParseRejectsNull() {
{
Assert.IsFalse(RgbColor.TryParse(null, out RgbColor color)); Assert.IsFalse(RgbColor.TryParse(null, out RgbColor color));
Assert.AreEqual(default, color); Assert.AreEqual(default, color);
} }
[TestMethod] [TestMethod]
public void TryParseAcceptsValidText() public void TryParseAcceptsValidText() {
{
Assert.IsTrue(RgbColor.TryParse("#010203", out RgbColor color)); Assert.IsTrue(RgbColor.TryParse("#010203", out RgbColor color));
Assert.AreEqual(new RgbColor(1, 2, 3), color); Assert.AreEqual(new RgbColor(1, 2, 3), color);
} }
[TestMethod] [TestMethod]
public void ToStringUsesCanonicalLowercase() public void ToStringUsesCanonicalLowercase() {
{
Assert.AreEqual("#ff0a00", new RgbColor(0xFF, 0x0A, 0x00).ToString()); Assert.AreEqual("#ff0a00", new RgbColor(0xFF, 0x0A, 0x00).ToString());
} }
[TestMethod] [TestMethod]
public void TextRoundTrips() public void TextRoundTrips() {
{
var color = new RgbColor(0x12, 0xAB, 0xCD); var color = new RgbColor(0x12, 0xAB, 0xCD);
Assert.AreEqual(color, RgbColor.Parse(color.ToString())); Assert.AreEqual(color, RgbColor.Parse(color.ToString()));
} }
[TestMethod] [TestMethod]
public void EqualityComparesComponents() public void EqualityComparesComponents() {
{
Assert.AreEqual(new RgbColor(1, 2, 3), new RgbColor(1, 2, 3)); Assert.AreEqual(new RgbColor(1, 2, 3), new RgbColor(1, 2, 3));
Assert.AreNotEqual(new RgbColor(1, 2, 3), new RgbColor(1, 2, 4)); Assert.AreNotEqual(new RgbColor(1, 2, 3), new RgbColor(1, 2, 4));
} }
+2 -4
View File
@@ -7,15 +7,13 @@ namespace YKanBan.Tests;
/// application project and that the test runner can discover and execute tests. /// application project and that the test runner can discover and execute tests.
/// </summary> /// </summary>
[TestClass] [TestClass]
public class ProjectReferenceTests public class ProjectReferenceTests {
{
/// <summary> /// <summary>
/// Verifies that a type defined in the application assembly can be /// Verifies that a type defined in the application assembly can be
/// referenced from the test project. /// referenced from the test project.
/// </summary> /// </summary>
[TestMethod] [TestMethod]
public void ApplicationAssemblyIsReferenceable() public void ApplicationAssemblyIsReferenceable() {
{
Assert.IsNotNull(typeof(App)); Assert.IsNotNull(typeof(App));
} }
} }
+7 -14
View File
@@ -7,8 +7,7 @@ namespace YKanBan.Tests.Search;
/// records compare by reference for their Terms collections by design (see the /// records compare by reference for their Terms collections by design (see the
/// YYC MARK note in SearchNodes.cs), so tests provide equality explicitly. /// YYC MARK note in SearchNodes.cs), so tests provide equality explicitly.
/// </summary> /// </summary>
public sealed class SearchNodeComparer : IEqualityComparer<SearchNode> public sealed class SearchNodeComparer : IEqualityComparer<SearchNode> {
{
/// <summary> /// <summary>
/// Gets the shared comparer instance. /// Gets the shared comparer instance.
/// </summary> /// </summary>
@@ -20,19 +19,15 @@ public sealed class SearchNodeComparer : IEqualityComparer<SearchNode>
/// <param name="x">The first node.</param> /// <param name="x">The first node.</param>
/// <param name="y">The second node.</param> /// <param name="y">The second node.</param>
/// <returns><see langword="true"/> when the nodes are structurally equal.</returns> /// <returns><see langword="true"/> when the nodes are structurally equal.</returns>
public bool Equals(SearchNode? x, SearchNode? y) public bool Equals(SearchNode? x, SearchNode? y) {
{ if (ReferenceEquals(x, y)) {
if (ReferenceEquals(x, y))
{
return true; return true;
} }
if (x is null || y is null || x.GetType() != y.GetType()) if (x is null || y is null || x.GetType() != y.GetType()) {
{
return false; return false;
} }
return (x, y) switch return (x, y) switch {
{
(SearchNode.Or a, SearchNode.Or b) => SequencesEqual(a.Terms, b.Terms), (SearchNode.Or a, SearchNode.Or b) => SequencesEqual(a.Terms, b.Terms),
(SearchNode.And a, SearchNode.And b) => SequencesEqual(a.Terms, b.Terms), (SearchNode.And a, SearchNode.And b) => SequencesEqual(a.Terms, b.Terms),
(SearchNode.FreeText a, SearchNode.FreeText b) => a.Text == b.Text, (SearchNode.FreeText a, SearchNode.FreeText b) => a.Text == b.Text,
@@ -58,10 +53,8 @@ public sealed class SearchNodeComparer : IEqualityComparer<SearchNode>
/// <param name="x">The first sequence.</param> /// <param name="x">The first sequence.</param>
/// <param name="y">The second sequence.</param> /// <param name="y">The second sequence.</param>
/// <returns><see langword="true"/> when both sequences match element-wise.</returns> /// <returns><see langword="true"/> when both sequences match element-wise.</returns>
private static bool SequencesEqual(IReadOnlyList<SearchNode> x, IReadOnlyList<SearchNode> y) private static bool SequencesEqual(IReadOnlyList<SearchNode> x, IReadOnlyList<SearchNode> y) {
{ if (x.Count != y.Count) {
if (x.Count != y.Count)
{
return false; return false;
} }
return x.Zip(y).All(pair => Instance.Equals(pair.First, pair.Second)); return x.Zip(y).All(pair => Instance.Equals(pair.First, pair.Second));
+39 -78
View File
@@ -8,15 +8,13 @@ namespace YKanBan.Tests.Search;
/// <see cref="SearchSyntaxException"/>). /// <see cref="SearchSyntaxException"/>).
/// </summary> /// </summary>
[TestClass] [TestClass]
public class SearchQueryParserTests public class SearchQueryParserTests {
{
/// <summary> /// <summary>
/// Parses and asserts structural equality against the expected AST. /// Parses and asserts structural equality against the expected AST.
/// </summary> /// </summary>
/// <param name="expected">The expected AST.</param> /// <param name="expected">The expected AST.</param>
/// <param name="text">The search text.</param> /// <param name="text">The search text.</param>
private static void AssertParsesTo(SearchNode expected, string text) private static void AssertParsesTo(SearchNode expected, string text) {
{
SearchNode? parsed = SearchQueryParser.Parse(text); SearchNode? parsed = SearchQueryParser.Parse(text);
Assert.IsNotNull(parsed, $"Blank-looking input: '{text}'."); Assert.IsNotNull(parsed, $"Blank-looking input: '{text}'.");
Assert.AreEqual(expected, parsed, SearchNodeComparer.Instance); Assert.AreEqual(expected, parsed, SearchNodeComparer.Instance);
@@ -26,53 +24,46 @@ public class SearchQueryParserTests
/// Asserts that the input violates the grammar. /// Asserts that the input violates the grammar.
/// </summary> /// </summary>
/// <param name="text">The search text.</param> /// <param name="text">The search text.</param>
private static void AssertSyntaxError(string text) private static void AssertSyntaxError(string text) {
{
Assert.ThrowsExactly<SearchSyntaxException>(() => SearchQueryParser.Parse(text)); Assert.ThrowsExactly<SearchSyntaxException>(() => SearchQueryParser.Parse(text));
} }
#region Successful parses #region Successful parses
[TestMethod] [TestMethod]
public void BlankInputReturnsNull() public void BlankInputReturnsNull() {
{
Assert.IsNull(SearchQueryParser.Parse(string.Empty)); Assert.IsNull(SearchQueryParser.Parse(string.Empty));
Assert.IsNull(SearchQueryParser.Parse(" ")); Assert.IsNull(SearchQueryParser.Parse(" "));
} }
[TestMethod] [TestMethod]
public void SingleWordIsFreeText() public void SingleWordIsFreeText() {
{
AssertParsesTo(new SearchNode.FreeText("login"), "login"); AssertParsesTo(new SearchNode.FreeText("login"), "login");
} }
[TestMethod] [TestMethod]
public void AdjacentWordsAreImplicitAnd() public void AdjacentWordsAreImplicitAnd() {
{
AssertParsesTo( AssertParsesTo(
new SearchNode.And([new SearchNode.FreeText("fix"), new SearchNode.FreeText("login")]), new SearchNode.And([new SearchNode.FreeText("fix"), new SearchNode.FreeText("login")]),
"fix login"); "fix login");
} }
[TestMethod] [TestMethod]
public void ExplicitAndKeyword() public void ExplicitAndKeyword() {
{
AssertParsesTo( AssertParsesTo(
new SearchNode.And([new SearchNode.FreeText("a"), new SearchNode.FreeText("b")]), new SearchNode.And([new SearchNode.FreeText("a"), new SearchNode.FreeText("b")]),
"a AND b"); "a AND b");
} }
[TestMethod] [TestMethod]
public void OrKeyword() public void OrKeyword() {
{
AssertParsesTo( AssertParsesTo(
new SearchNode.Or([new SearchNode.FreeText("a"), new SearchNode.FreeText("b")]), new SearchNode.Or([new SearchNode.FreeText("a"), new SearchNode.FreeText("b")]),
"a OR b"); "a OR b");
} }
[TestMethod] [TestMethod]
public void ImplicitAndBindsTighterThanOr() public void ImplicitAndBindsTighterThanOr() {
{
AssertParsesTo( AssertParsesTo(
new SearchNode.Or([ new SearchNode.Or([
new SearchNode.And([new SearchNode.FreeText("a"), new SearchNode.FreeText("b")]), new SearchNode.And([new SearchNode.FreeText("a"), new SearchNode.FreeText("b")]),
@@ -81,8 +72,7 @@ public class SearchQueryParserTests
} }
[TestMethod] [TestMethod]
public void ParenthesesForceGrouping() public void ParenthesesForceGrouping() {
{
AssertParsesTo( AssertParsesTo(
new SearchNode.And([ new SearchNode.And([
new SearchNode.FreeText("a"), new SearchNode.FreeText("a"),
@@ -91,16 +81,14 @@ public class SearchQueryParserTests
} }
[TestMethod] [TestMethod]
public void NestedParenthesesCollapse() public void NestedParenthesesCollapse() {
{
AssertParsesTo( AssertParsesTo(
new SearchNode.Or([new SearchNode.FreeText("a"), new SearchNode.FreeText("b")]), new SearchNode.Or([new SearchNode.FreeText("a"), new SearchNode.FreeText("b")]),
"((a OR b))"); "((a OR b))");
} }
[TestMethod] [TestMethod]
public void LowercaseKeywordsArePlainWords() public void LowercaseKeywordsArePlainWords() {
{
AssertParsesTo( AssertParsesTo(
new SearchNode.And([ new SearchNode.And([
new SearchNode.FreeText("a"), new SearchNode.FreeText("a"),
@@ -111,14 +99,12 @@ public class SearchQueryParserTests
} }
[TestMethod] [TestMethod]
public void PhraseIsFreeText() public void PhraseIsFreeText() {
{
AssertParsesTo(new SearchNode.FreeText("hello world"), "\"hello world\""); AssertParsesTo(new SearchNode.FreeText("hello world"), "\"hello world\"");
} }
[TestMethod] [TestMethod]
public void QuotedOperatorKeywordIsFreeText() public void QuotedOperatorKeywordIsFreeText() {
{
// A quoted AND/OR is literal text, not an operator. // A quoted AND/OR is literal text, not an operator.
AssertParsesTo(new SearchNode.FreeText("AND"), "\"AND\""); AssertParsesTo(new SearchNode.FreeText("AND"), "\"AND\"");
AssertParsesTo( AssertParsesTo(
@@ -127,54 +113,46 @@ public class SearchQueryParserTests
} }
[TestMethod] [TestMethod]
public void PhraseSupportsEscapes() public void PhraseSupportsEscapes() {
{
// Escaped quote and escaped backslash. // Escaped quote and escaped backslash.
AssertParsesTo(new SearchNode.FreeText("a\"b"), "\"a\\\"b\""); AssertParsesTo(new SearchNode.FreeText("a\"b"), "\"a\\\"b\"");
AssertParsesTo(new SearchNode.FreeText("a\\b"), "\"a\\\\b\""); AssertParsesTo(new SearchNode.FreeText("a\\b"), "\"a\\\\b\"");
} }
[TestMethod] [TestMethod]
public void TagQualifier() public void TagQualifier() {
{
AssertParsesTo(new SearchNode.TagName("bug"), "tag:bug"); AssertParsesTo(new SearchNode.TagName("bug"), "tag:bug");
} }
[TestMethod] [TestMethod]
public void TagQualifierAcceptsPhraseValue() public void TagQualifierAcceptsPhraseValue() {
{
AssertParsesTo(new SearchNode.TagName("a b"), "tag:\"a b\""); AssertParsesTo(new SearchNode.TagName("a b"), "tag:\"a b\"");
} }
[TestMethod] [TestMethod]
public void QualifierValueMayContainColons() public void QualifierValueMayContainColons() {
{
AssertParsesTo(new SearchNode.TagName("a:b"), "tag:a:b"); AssertParsesTo(new SearchNode.TagName("a:b"), "tag:a:b");
} }
[TestMethod] [TestMethod]
public void TitleAndContentQualifiers() public void TitleAndContentQualifiers() {
{
AssertParsesTo(new SearchNode.FieldText(SearchField.Title, "foo"), "title:foo"); AssertParsesTo(new SearchNode.FieldText(SearchField.Title, "foo"), "title:foo");
AssertParsesTo(new SearchNode.FieldText(SearchField.Content, "foo"), "content:foo"); AssertParsesTo(new SearchNode.FieldText(SearchField.Content, "foo"), "content:foo");
} }
[TestMethod] [TestMethod]
public void ColumnQualifierAcceptsPhraseValue() public void ColumnQualifierAcceptsPhraseValue() {
{
AssertParsesTo(new SearchNode.ColumnTitle("To Do"), "column:\"To Do\""); AssertParsesTo(new SearchNode.ColumnTitle("To Do"), "column:\"To Do\"");
} }
[TestMethod] [TestMethod]
public void IdQualifierParsesNumber() public void IdQualifierParsesNumber() {
{
AssertParsesTo(new SearchNode.CardId(42), "id:42"); AssertParsesTo(new SearchNode.CardId(42), "id:42");
AssertParsesTo(new SearchNode.CardId(12), "id:\"12\""); AssertParsesTo(new SearchNode.CardId(12), "id:\"12\"");
} }
[TestMethod] [TestMethod]
public void ColonWithoutKeyPrefixIsFreeText() public void ColonWithoutKeyPrefixIsFreeText() {
{
AssertParsesTo(new SearchNode.FreeText(":foo"), ":foo"); AssertParsesTo(new SearchNode.FreeText(":foo"), ":foo");
} }
@@ -183,106 +161,89 @@ public class SearchQueryParserTests
#region Strict failures #region Strict failures
[TestMethod] [TestMethod]
public void UnterminatedPhraseIsAnError() public void UnterminatedPhraseIsAnError() {
{
AssertSyntaxError("\"abc def"); AssertSyntaxError("\"abc def");
} }
[TestMethod] [TestMethod]
public void TrailingUnterminatedPhraseIsAnError() public void TrailingUnterminatedPhraseIsAnError() {
{
AssertSyntaxError("a \"abc"); AssertSyntaxError("a \"abc");
} }
[TestMethod] [TestMethod]
public void InvalidEscapeInPhraseIsAnError() public void InvalidEscapeInPhraseIsAnError() {
{
// A bare backslash (not followed by a quote or another backslash) is invalid. // A bare backslash (not followed by a quote or another backslash) is invalid.
AssertSyntaxError("\"a\\b\""); AssertSyntaxError("\"a\\b\"");
} }
[TestMethod] [TestMethod]
public void InvalidEscapeInQualifierPhraseIsAnError() public void InvalidEscapeInQualifierPhraseIsAnError() {
{
AssertSyntaxError("tag:\"a\\x\""); AssertSyntaxError("tag:\"a\\x\"");
} }
[TestMethod] [TestMethod]
public void UnbalancedOpenParenIsAnError() public void UnbalancedOpenParenIsAnError() {
{
AssertSyntaxError("(a"); AssertSyntaxError("(a");
} }
[TestMethod] [TestMethod]
public void StrayCloseParenIsAnError() public void StrayCloseParenIsAnError() {
{
AssertSyntaxError("a)"); AssertSyntaxError("a)");
} }
[TestMethod] [TestMethod]
public void EmptyParensAreAnError() public void EmptyParensAreAnError() {
{
AssertSyntaxError("()"); AssertSyntaxError("()");
} }
[TestMethod] [TestMethod]
public void DanglingOrIsAnError() public void DanglingOrIsAnError() {
{
AssertSyntaxError("a OR"); AssertSyntaxError("a OR");
} }
[TestMethod] [TestMethod]
public void DanglingAndIsAnError() public void DanglingAndIsAnError() {
{
AssertSyntaxError("a AND"); AssertSyntaxError("a AND");
} }
[TestMethod] [TestMethod]
public void LeadingAndIsAnError() public void LeadingAndIsAnError() {
{
AssertSyntaxError("AND a"); AssertSyntaxError("AND a");
} }
[TestMethod] [TestMethod]
public void OperatorAtOperandPositionIsAnError() public void OperatorAtOperandPositionIsAnError() {
{
AssertSyntaxError("a AND OR b"); AssertSyntaxError("a AND OR b");
} }
[TestMethod] [TestMethod]
public void QualifierWithoutValueIsAnError() public void QualifierWithoutValueIsAnError() {
{
AssertSyntaxError("tag:"); AssertSyntaxError("tag:");
} }
[TestMethod] [TestMethod]
public void SpacedQualifierValueIsAnError() public void SpacedQualifierValueIsAnError() {
{
AssertSyntaxError("tag: bug"); AssertSyntaxError("tag: bug");
} }
[TestMethod] [TestMethod]
public void NonNumericIdIsAnError() public void NonNumericIdIsAnError() {
{
AssertSyntaxError("id:12x"); AssertSyntaxError("id:12x");
} }
[TestMethod] [TestMethod]
public void UnknownQualifierKeyIsAnError() public void UnknownQualifierKeyIsAnError() {
{
AssertSyntaxError("foo:bar"); AssertSyntaxError("foo:bar");
} }
[TestMethod] [TestMethod]
public void QualifierKeysAreCaseSensitive() public void QualifierKeysAreCaseSensitive() {
{
// "Tag" is a key-like prefix but not the known lowercase "tag", so it is unknown. // "Tag" is a key-like prefix but not the known lowercase "tag", so it is unknown.
AssertSyntaxError("Tag:x"); AssertSyntaxError("Tag:x");
} }
[TestMethod] [TestMethod]
public void SyntaxErrorCarriesDescriptiveMessage() public void SyntaxErrorCarriesDescriptiveMessage() {
{
SearchSyntaxException exception = Assert.ThrowsExactly<SearchSyntaxException>( SearchSyntaxException exception = Assert.ThrowsExactly<SearchSyntaxException>(
() => SearchQueryParser.Parse("a AND")); () => SearchQueryParser.Parse("a AND"));
Assert.IsFalse(string.IsNullOrEmpty(exception.Message)); Assert.IsFalse(string.IsNullOrEmpty(exception.Message));
+18 -34
View File
@@ -1,4 +1,5 @@
using Microsoft.Data.Sqlite; using Microsoft.Data.Sqlite;
using YKanBan.Search; using YKanBan.Search;
using YKanBan.Storage.Workspace; using YKanBan.Storage.Workspace;
using YKanBan.Tests.TestUtilities; using YKanBan.Tests.TestUtilities;
@@ -10,22 +11,18 @@ namespace YKanBan.Tests.Search;
/// workspace database. /// workspace database.
/// </summary> /// </summary>
[TestClass] [TestClass]
public class SearchSqlCompilerTests public class SearchSqlCompilerTests {
{
/// <summary> /// <summary>
/// Owns a workspace with a fixed card/tag fixture. /// Owns a workspace with a fixed card/tag fixture.
/// </summary> /// </summary>
private sealed class SearchFixture : IDisposable private sealed class SearchFixture : IDisposable {
{
public TempDirectory Directory { get; } = new(); public TempDirectory Directory { get; } = new();
public SqliteConnection Connection { get; } public SqliteConnection Connection { get; }
public SearchFixture() public SearchFixture() {
{
WorkspaceInitializer.Initialize(Directory.FullPath); WorkspaceInitializer.Initialize(Directory.FullPath);
using (SqliteConnection setup = SqliteTestHelper.OpenWorkspace(Directory.FullPath)) using (SqliteConnection setup = SqliteTestHelper.OpenWorkspace(Directory.FullPath)) {
{
// Columns: 1 "To Do", 2 "In Progress". // Columns: 1 "To Do", 2 "In Progress".
SqliteTestHelper.Exec(setup, "INSERT INTO columns (title, description, created_at, updated_at) VALUES ('To Do', '', 1, 1);"); SqliteTestHelper.Exec(setup, "INSERT INTO columns (title, description, created_at, updated_at) VALUES ('To Do', '', 1, 1);");
SqliteTestHelper.Exec(setup, "INSERT INTO columns (title, description, created_at, updated_at) VALUES ('In Progress', '', 1, 1);"); SqliteTestHelper.Exec(setup, "INSERT INTO columns (title, description, created_at, updated_at) VALUES ('In Progress', '', 1, 1);");
@@ -54,38 +51,33 @@ public class SearchSqlCompilerTests
/// </summary> /// </summary>
/// <param name="queryText">The search text.</param> /// <param name="queryText">The search text.</param>
/// <returns>The matching card ids in id order.</returns> /// <returns>The matching card ids in id order.</returns>
public List<long> Search(string queryText) public List<long> Search(string queryText) {
{
SearchNode? query = SearchQueryParser.Parse(queryText); SearchNode? query = SearchQueryParser.Parse(queryText);
Assert.IsNotNull(query, "Blank fixture queries are not expected here."); Assert.IsNotNull(query, "Blank fixture queries are not expected here.");
CompiledSearch compiled = SearchSqlCompiler.Compile(query); CompiledSearch compiled = SearchSqlCompiler.Compile(query);
using var command = Connection.CreateCommand(); using var command = Connection.CreateCommand();
command.CommandText = $"SELECT c.id FROM cards c WHERE {compiled.Predicate} ORDER BY c.id ASC;"; command.CommandText = $"SELECT c.id FROM cards c WHERE {compiled.Predicate} ORDER BY c.id ASC;";
foreach ((string name, object value) in compiled.Parameters) foreach ((string name, object value) in compiled.Parameters) {
{
command.Parameters.AddWithValue(name, value); command.Parameters.AddWithValue(name, value);
} }
using var reader = command.ExecuteReader(); using var reader = command.ExecuteReader();
var ids = new List<long>(); var ids = new List<long>();
while (reader.Read()) while (reader.Read()) {
{
ids.Add(reader.GetInt64(0)); ids.Add(reader.GetInt64(0));
} }
return ids; return ids;
} }
public void Dispose() public void Dispose() {
{
Connection.Dispose(); Connection.Dispose();
Directory.Dispose(); Directory.Dispose();
} }
} }
[TestMethod] [TestMethod]
public void FreeTextMatchesTitleOrContentCaseInsensitively() public void FreeTextMatchesTitleOrContentCaseInsensitively() {
{
using var fixture = new SearchFixture(); using var fixture = new SearchFixture();
CollectionAssert.AreEqual(new[] { 2L }, fixture.Search("apple")); CollectionAssert.AreEqual(new[] { 2L }, fixture.Search("apple"));
CollectionAssert.AreEqual(new[] { 1L }, fixture.Search("login")); CollectionAssert.AreEqual(new[] { 1L }, fixture.Search("login"));
@@ -94,8 +86,7 @@ public class SearchSqlCompilerTests
} }
[TestMethod] [TestMethod]
public void FieldQualifiersScopeToTheirField() public void FieldQualifiersScopeToTheirField() {
{
using var fixture = new SearchFixture(); using var fixture = new SearchFixture();
CollectionAssert.AreEqual(new[] { 2L }, fixture.Search("title:apple")); CollectionAssert.AreEqual(new[] { 2L }, fixture.Search("title:apple"));
CollectionAssert.AreEqual(new[] { 3L }, fixture.Search("content:banana")); CollectionAssert.AreEqual(new[] { 3L }, fixture.Search("content:banana"));
@@ -103,8 +94,7 @@ public class SearchSqlCompilerTests
} }
[TestMethod] [TestMethod]
public void TagQualifierMatchesExactlyAndCaseInsensitively() public void TagQualifierMatchesExactlyAndCaseInsensitively() {
{
using var fixture = new SearchFixture(); using var fixture = new SearchFixture();
CollectionAssert.AreEqual(new[] { 1L }, fixture.Search("tag:bug")); CollectionAssert.AreEqual(new[] { 1L }, fixture.Search("tag:bug"));
CollectionAssert.AreEqual(new[] { 2L, 3L }, fixture.Search("tag:ui")); CollectionAssert.AreEqual(new[] { 2L, 3L }, fixture.Search("tag:ui"));
@@ -116,8 +106,7 @@ public class SearchSqlCompilerTests
} }
[TestMethod] [TestMethod]
public void ColumnQualifierMatchesColumnTitleExactly() public void ColumnQualifierMatchesColumnTitleExactly() {
{
using var fixture = new SearchFixture(); using var fixture = new SearchFixture();
CollectionAssert.AreEqual(new[] { 1L, 4L }, fixture.Search("column:\"to do\"")); CollectionAssert.AreEqual(new[] { 1L, 4L }, fixture.Search("column:\"to do\""));
CollectionAssert.AreEqual(new[] { 2L, 3L }, fixture.Search("column:\"in progress\"")); CollectionAssert.AreEqual(new[] { 2L, 3L }, fixture.Search("column:\"in progress\""));
@@ -128,16 +117,14 @@ public class SearchSqlCompilerTests
} }
[TestMethod] [TestMethod]
public void IdQualifierMatchesExactly() public void IdQualifierMatchesExactly() {
{
using var fixture = new SearchFixture(); using var fixture = new SearchFixture();
CollectionAssert.AreEqual(new[] { 3L }, fixture.Search("id:3")); CollectionAssert.AreEqual(new[] { 3L }, fixture.Search("id:3"));
Assert.AreEqual(0, fixture.Search("id:99").Count); Assert.AreEqual(0, fixture.Search("id:99").Count);
} }
[TestMethod] [TestMethod]
public void AndOrCombination() public void AndOrCombination() {
{
using var fixture = new SearchFixture(); using var fixture = new SearchFixture();
CollectionAssert.AreEqual(new[] { 2L, 3L }, fixture.Search("apple OR banana")); CollectionAssert.AreEqual(new[] { 2L, 3L }, fixture.Search("apple OR banana"));
CollectionAssert.AreEqual(new[] { 2L }, fixture.Search("apple AND id:2")); CollectionAssert.AreEqual(new[] { 2L }, fixture.Search("apple AND id:2"));
@@ -145,8 +132,7 @@ public class SearchSqlCompilerTests
} }
[TestMethod] [TestMethod]
public void ParenthesizedGrouping() public void ParenthesizedGrouping() {
{
using var fixture = new SearchFixture(); using var fixture = new SearchFixture();
// (apple OR banana) hits cards 2,3; intersected with column "In Progress" (2,3). // (apple OR banana) hits cards 2,3; intersected with column "In Progress" (2,3).
@@ -157,16 +143,14 @@ public class SearchSqlCompilerTests
} }
[TestMethod] [TestMethod]
public void LikeWildcardsInUserTextMatchLiterally() public void LikeWildcardsInUserTextMatchLiterally() {
{
using var fixture = new SearchFixture(); using var fixture = new SearchFixture();
CollectionAssert.AreEqual(new[] { 4L }, fixture.Search("100%")); CollectionAssert.AreEqual(new[] { 4L }, fixture.Search("100%"));
CollectionAssert.AreEqual(new[] { 4L }, fixture.Search("a_b")); CollectionAssert.AreEqual(new[] { 4L }, fixture.Search("a_b"));
} }
[TestMethod] [TestMethod]
public void CompiledPredicateUsesNamedParameters() public void CompiledPredicateUsesNamedParameters() {
{
CompiledSearch compiled = SearchSqlCompiler.Compile(new SearchNode.FreeText("x")); CompiledSearch compiled = SearchSqlCompiler.Compile(new SearchNode.FreeText("x"));
StringAssert.Contains(compiled.Predicate, "$p0"); StringAssert.Contains(compiled.Predicate, "$p0");
@@ -8,11 +8,9 @@ namespace YKanBan.Tests.Storage.AppData;
/// degradation on a missing or corrupt file. /// degradation on a missing or corrupt file.
/// </summary> /// </summary>
[TestClass] [TestClass]
public class AppConfigStoreTests public class AppConfigStoreTests {
{
[TestMethod] [TestMethod]
public void LoadMissingFileReturnsDefaults() public void LoadMissingFileReturnsDefaults() {
{
using var directory = new TempDirectory(); using var directory = new TempDirectory();
var store = new AppConfigStore(Path.Combine(directory.FullPath, "app.json")); var store = new AppConfigStore(Path.Combine(directory.FullPath, "app.json"));
@@ -21,9 +19,10 @@ public class AppConfigStoreTests
Assert.AreEqual(AppConfig.CurrentFormatVersion, config.Version); Assert.AreEqual(AppConfig.CurrentFormatVersion, config.Version);
Assert.AreEqual(AppConfig.DefaultLanguage, config.Language); Assert.AreEqual(AppConfig.DefaultLanguage, config.Language);
Assert.AreEqual(ThemeOption.FollowSystem, config.Theme); Assert.AreEqual(ThemeOption.FollowSystem, config.Theme);
Assert.AreEqual(CardSortOption.Id, config.Sort.Card); Assert.AreEqual(SortOption.IdAscending, config.Display.CardSort);
Assert.AreEqual(ColumnWidthPreset.Standard, config.ColumnWidth.Preset); Assert.AreEqual(SortOption.IdAscending, config.Display.ColumnSort);
Assert.AreEqual(320, config.ColumnWidth.CustomPixels); Assert.AreEqual(ColumnWidthPreset.Standard, config.Display.ColumnWidth.Preset);
Assert.AreEqual(320, config.Display.ColumnWidth.CustomPixels);
Assert.IsTrue(config.Confirmations.DeleteCard); Assert.IsTrue(config.Confirmations.DeleteCard);
Assert.IsTrue(config.Confirmations.DeleteColumn); Assert.IsTrue(config.Confirmations.DeleteColumn);
Assert.IsTrue(config.Confirmations.DeleteTag); Assert.IsTrue(config.Confirmations.DeleteTag);
@@ -31,8 +30,7 @@ public class AppConfigStoreTests
} }
[TestMethod] [TestMethod]
public void LoadCorruptFileBacksUpAndReturnsDefaults() public void LoadCorruptFileBacksUpAndReturnsDefaults() {
{
using var directory = new TempDirectory(); using var directory = new TempDirectory();
string path = Path.Combine(directory.FullPath, "app.json"); string path = Path.Combine(directory.FullPath, "app.json");
File.WriteAllText(path, "{ this is not valid json"); File.WriteAllText(path, "{ this is not valid json");
@@ -46,8 +44,7 @@ public class AppConfigStoreTests
} }
[TestMethod] [TestMethod]
public void LoadJsonNullReturnsDefaults() public void LoadJsonNullReturnsDefaults() {
{
using var directory = new TempDirectory(); using var directory = new TempDirectory();
string path = Path.Combine(directory.FullPath, "app.json"); string path = Path.Combine(directory.FullPath, "app.json");
File.WriteAllText(path, "null"); File.WriteAllText(path, "null");
@@ -57,8 +54,7 @@ public class AppConfigStoreTests
} }
[TestMethod] [TestMethod]
public void LoadReadsKebabCaseKeysAndEnumValues() public void LoadReadsKebabCaseKeysAndEnumValues() {
{
using var directory = new TempDirectory(); using var directory = new TempDirectory();
string path = Path.Combine(directory.FullPath, "app.json"); string path = Path.Combine(directory.FullPath, "app.json");
File.WriteAllText(path, $$""" File.WriteAllText(path, $$"""
@@ -66,8 +62,11 @@ public class AppConfigStoreTests
"version": {{AppConfig.CurrentFormatVersion}}, "version": {{AppConfig.CurrentFormatVersion}},
"language": "zh-Hans", "language": "zh-Hans",
"theme": "dark", "theme": "dark",
"sort": { "card": "title" }, "display": {
"column-width": { "preset": "custom", "custom-pixels": 400 }, "column-width": { "preset": "custom", "custom-pixels": 400 },
"card-sort": "title-asc",
"column-sort": "id-desc"
},
"confirmations": { "confirmations": {
"delete-card": false, "delete-card": false,
"delete-column": false, "delete-column": false,
@@ -82,9 +81,10 @@ public class AppConfigStoreTests
Assert.AreEqual("zh-Hans", config.Language); Assert.AreEqual("zh-Hans", config.Language);
Assert.AreEqual(ThemeOption.Dark, config.Theme); Assert.AreEqual(ThemeOption.Dark, config.Theme);
Assert.AreEqual(CardSortOption.Title, config.Sort.Card); Assert.AreEqual(SortOption.TitleAscending, config.Display.CardSort);
Assert.AreEqual(ColumnWidthPreset.Custom, config.ColumnWidth.Preset); Assert.AreEqual(SortOption.IdDescending, config.Display.ColumnSort);
Assert.AreEqual(400, config.ColumnWidth.CustomPixels); Assert.AreEqual(ColumnWidthPreset.Custom, config.Display.ColumnWidth.Preset);
Assert.AreEqual(400, config.Display.ColumnWidth.CustomPixels);
Assert.IsFalse(config.Confirmations.DeleteCard); Assert.IsFalse(config.Confirmations.DeleteCard);
Assert.IsFalse(config.Confirmations.DeleteColumn); Assert.IsFalse(config.Confirmations.DeleteColumn);
Assert.IsFalse(config.Confirmations.DeleteTag); Assert.IsFalse(config.Confirmations.DeleteTag);
@@ -92,8 +92,7 @@ public class AppConfigStoreTests
} }
[TestMethod] [TestMethod]
public void LoadMissingSectionsFillsDefaults() public void LoadMissingSectionsFillsDefaults() {
{
using var directory = new TempDirectory(); using var directory = new TempDirectory();
string path = Path.Combine(directory.FullPath, "app.json"); string path = Path.Combine(directory.FullPath, "app.json");
File.WriteAllText(path, $$"""{ "version": {{AppConfig.CurrentFormatVersion}} }"""); File.WriteAllText(path, $$"""{ "version": {{AppConfig.CurrentFormatVersion}} }""");
@@ -101,24 +100,25 @@ public class AppConfigStoreTests
AppConfig config = store.Load(); AppConfig config = store.Load();
Assert.IsNotNull(config.Sort); Assert.IsNotNull(config.Display);
Assert.IsNotNull(config.ColumnWidth); Assert.IsNotNull(config.Display.ColumnWidth);
Assert.IsNotNull(config.Confirmations); Assert.IsNotNull(config.Confirmations);
Assert.AreEqual(ColumnWidthPreset.Standard, config.ColumnWidth.Preset); Assert.AreEqual(ColumnWidthPreset.Standard, config.Display.ColumnWidth.Preset);
} }
[TestMethod] [TestMethod]
public void SaveWritesKebabCaseKeysAndEnumValues() public void SaveWritesKebabCaseKeysAndEnumValues() {
{
using var directory = new TempDirectory(); using var directory = new TempDirectory();
string path = Path.Combine(directory.FullPath, "app.json"); string path = Path.Combine(directory.FullPath, "app.json");
var store = new AppConfigStore(path); var store = new AppConfigStore(path);
var config = new AppConfig var config = new AppConfig {
{
Theme = ThemeOption.FollowSystem, Theme = ThemeOption.FollowSystem,
Sort = new SortSettings { Card = CardSortOption.UpdatedAt }, Display = new DisplaySettings {
ColumnWidth = new ColumnWidthSettings { Preset = ColumnWidthPreset.Custom, CustomPixels = 500 }, CardSort = SortOption.UpdatedDescending,
ColumnSort = SortOption.CreatedAscending,
ColumnWidth = new ColumnWidthSettings { Preset = ColumnWidthPreset.Custom, CustomPixels = 500 },
},
Confirmations = new ConfirmationSettings { DeleteColumn = false }, Confirmations = new ConfirmationSettings { DeleteColumn = false },
}; };
store.Save(config); store.Save(config);
@@ -126,27 +126,31 @@ public class AppConfigStoreTests
string json = File.ReadAllText(path); string json = File.ReadAllText(path);
StringAssert.Contains(json, "\"delete-column\""); StringAssert.Contains(json, "\"delete-column\"");
StringAssert.Contains(json, "\"discard-edit\""); StringAssert.Contains(json, "\"discard-edit\"");
StringAssert.Contains(json, "\"card-sort\"");
StringAssert.Contains(json, "\"column-sort\"");
StringAssert.Contains(json, "\"custom-pixels\""); StringAssert.Contains(json, "\"custom-pixels\"");
StringAssert.Contains(json, "\"follow-system\""); StringAssert.Contains(json, "\"follow-system\"");
StringAssert.Contains(json, "\"updated-at\""); StringAssert.Contains(json, "\"updated-desc\"");
StringAssert.Contains(json, "\"created-asc\"");
// No member-name CamelCase must leak into the file. // No member-name CamelCase must leak into the file.
Assert.IsFalse(json.Contains("deleteColumn", StringComparison.Ordinal)); Assert.IsFalse(json.Contains("deleteColumn", StringComparison.Ordinal));
Assert.IsFalse(json.Contains("CustomPixels", StringComparison.Ordinal)); Assert.IsFalse(json.Contains("CustomPixels", StringComparison.Ordinal));
} }
[TestMethod] [TestMethod]
public void SaveThenLoadRoundTrips() public void SaveThenLoadRoundTrips() {
{
using var directory = new TempDirectory(); using var directory = new TempDirectory();
string path = Path.Combine(directory.FullPath, "app.json"); string path = Path.Combine(directory.FullPath, "app.json");
var store = new AppConfigStore(path); var store = new AppConfigStore(path);
var config = new AppConfig var config = new AppConfig {
{
Language = "zh-Hans", Language = "zh-Hans",
Theme = ThemeOption.Light, Theme = ThemeOption.Light,
Sort = new SortSettings { Card = CardSortOption.CreatedAt }, Display = new DisplaySettings {
ColumnWidth = new ColumnWidthSettings { Preset = ColumnWidthPreset.Wide }, CardSort = SortOption.CreatedDescending,
ColumnSort = SortOption.TitleAscending,
ColumnWidth = new ColumnWidthSettings { Preset = ColumnWidthPreset.Wide },
},
Confirmations = new ConfirmationSettings { DiscardEdit = false }, Confirmations = new ConfirmationSettings { DiscardEdit = false },
}; };
store.Save(config); store.Save(config);
@@ -154,8 +158,9 @@ public class AppConfigStoreTests
AppConfig reloaded = store.Load(); AppConfig reloaded = store.Load();
Assert.AreEqual(config.Language, reloaded.Language); Assert.AreEqual(config.Language, reloaded.Language);
Assert.AreEqual(config.Theme, reloaded.Theme); Assert.AreEqual(config.Theme, reloaded.Theme);
Assert.AreEqual(config.Sort.Card, reloaded.Sort.Card); Assert.AreEqual(config.Display.CardSort, reloaded.Display.CardSort);
Assert.AreEqual(config.ColumnWidth.Preset, reloaded.ColumnWidth.Preset); Assert.AreEqual(config.Display.ColumnSort, reloaded.Display.ColumnSort);
Assert.AreEqual(config.Display.ColumnWidth.Preset, reloaded.Display.ColumnWidth.Preset);
Assert.AreEqual(config.Confirmations.DiscardEdit, reloaded.Confirmations.DiscardEdit); Assert.AreEqual(config.Confirmations.DiscardEdit, reloaded.Confirmations.DiscardEdit);
} }
} }
+9 -16
View File
@@ -1,4 +1,5 @@
using Microsoft.Data.Sqlite; using Microsoft.Data.Sqlite;
using YKanBan.Storage; using YKanBan.Storage;
using YKanBan.Storage.Workspace; using YKanBan.Storage.Workspace;
using YKanBan.Tests.TestUtilities; using YKanBan.Tests.TestUtilities;
@@ -10,11 +11,9 @@ namespace YKanBan.Tests.Storage;
/// user_version-driven migration runner. /// user_version-driven migration runner.
/// </summary> /// </summary>
[TestClass] [TestClass]
public class SqliteDatabaseTests public class SqliteDatabaseTests {
{
[TestMethod] [TestMethod]
public void OpenAppliesMandatoryPragmas() public void OpenAppliesMandatoryPragmas() {
{
using var directory = new TempDirectory(); using var directory = new TempDirectory();
string databasePath = Path.Combine(directory.FullPath, "pragmas.db"); string databasePath = Path.Combine(directory.FullPath, "pragmas.db");
@@ -25,8 +24,7 @@ public class SqliteDatabaseTests
} }
[TestMethod] [TestMethod]
public void OpenSetsUserVersionToLatestMigration() public void OpenSetsUserVersionToLatestMigration() {
{
using var directory = new TempDirectory(); using var directory = new TempDirectory();
string databasePath = Path.Combine(directory.FullPath, "version.db"); string databasePath = Path.Combine(directory.FullPath, "version.db");
@@ -35,13 +33,11 @@ public class SqliteDatabaseTests
} }
[TestMethod] [TestMethod]
public void ReopenKeepsWalJournalMode() public void ReopenKeepsWalJournalMode() {
{
using var directory = new TempDirectory(); using var directory = new TempDirectory();
string databasePath = Path.Combine(directory.FullPath, "wal.db"); string databasePath = Path.Combine(directory.FullPath, "wal.db");
using (SqliteConnection connection = SqliteDatabase.Open(databasePath, WorkspaceSchema.Migrations)) using (SqliteConnection connection = SqliteDatabase.Open(databasePath, WorkspaceSchema.Migrations)) {
{
} }
// WAL mode is stored in the database header, so a fresh connection keeps it. // WAL mode is stored in the database header, so a fresh connection keeps it.
@@ -50,14 +46,12 @@ public class SqliteDatabaseTests
} }
[TestMethod] [TestMethod]
public void OpenRejectsNewerStoredSchemaVersion() public void OpenRejectsNewerStoredSchemaVersion() {
{
using var directory = new TempDirectory(); using var directory = new TempDirectory();
string databasePath = Path.Combine(directory.FullPath, "newer.db"); string databasePath = Path.Combine(directory.FullPath, "newer.db");
long newerVersion = WorkspaceSchema.CurrentVersion + 1; long newerVersion = WorkspaceSchema.CurrentVersion + 1;
using (SqliteConnection connection = SqliteDatabase.Open(databasePath, WorkspaceSchema.Migrations)) using (SqliteConnection connection = SqliteDatabase.Open(databasePath, WorkspaceSchema.Migrations)) {
{
SqliteTestHelper.Exec(connection, $"PRAGMA user_version={newerVersion};"); SqliteTestHelper.Exec(connection, $"PRAGMA user_version={newerVersion};");
} }
@@ -68,8 +62,7 @@ public class SqliteDatabaseTests
} }
[TestMethod] [TestMethod]
public void OpenRejectsNonContiguousMigrationList() public void OpenRejectsNonContiguousMigrationList() {
{
using var directory = new TempDirectory(); using var directory = new TempDirectory();
string databasePath = Path.Combine(directory.FullPath, "gap.db"); string databasePath = Path.Combine(directory.FullPath, "gap.db");
@@ -1,4 +1,5 @@
using Microsoft.Data.Sqlite; using Microsoft.Data.Sqlite;
using YKanBan.Storage; using YKanBan.Storage;
using YKanBan.Storage.Workspace; using YKanBan.Storage.Workspace;
using YKanBan.Tests.TestUtilities; using YKanBan.Tests.TestUtilities;
@@ -11,11 +12,9 @@ namespace YKanBan.Tests.Storage.Workspace;
/// content. /// content.
/// </summary> /// </summary>
[TestClass] [TestClass]
public class WorkspaceInitializerTests public class WorkspaceInitializerTests {
{
[TestMethod] [TestMethod]
public void IsWorkspaceReflectsInitializationState() public void IsWorkspaceReflectsInitializationState() {
{
using var directory = new TempDirectory(); using var directory = new TempDirectory();
Assert.IsFalse(WorkspaceInitializer.IsWorkspace(directory.FullPath)); Assert.IsFalse(WorkspaceInitializer.IsWorkspace(directory.FullPath));
@@ -24,8 +23,7 @@ public class WorkspaceInitializerTests
} }
[TestMethod] [TestMethod]
public void InitializeCreatesStructureAndMigratedEmptyDatabase() public void InitializeCreatesStructureAndMigratedEmptyDatabase() {
{
using var directory = new TempDirectory(); using var directory = new TempDirectory();
WorkspaceInitializer.Initialize(directory.FullPath); WorkspaceInitializer.Initialize(directory.FullPath);
@@ -43,8 +41,7 @@ public class WorkspaceInitializerTests
} }
[TestMethod] [TestMethod]
public void InitializeMissingFolderThrows() public void InitializeMissingFolderThrows() {
{
using var directory = new TempDirectory(); using var directory = new TempDirectory();
string missing = Path.Combine(directory.FullPath, "not-created"); string missing = Path.Combine(directory.FullPath, "not-created");
@@ -54,8 +51,7 @@ public class WorkspaceInitializerTests
} }
[TestMethod] [TestMethod]
public void InitializeTwiceThrows() public void InitializeTwiceThrows() {
{
using var directory = new TempDirectory(); using var directory = new TempDirectory();
WorkspaceInitializer.Initialize(directory.FullPath); WorkspaceInitializer.Initialize(directory.FullPath);
@@ -5,14 +5,12 @@ using YKanBan.Tests.TestUtilities;
namespace YKanBan.Tests.Storage.Workspace; namespace YKanBan.Tests.Storage.Workspace;
/// <summary> /// <summary>
/// Tests for exclusive lock acquisition, diagnostics and release. /// Tests for exclusive lock acquisition and release.
/// </summary> /// </summary>
[TestClass] [TestClass]
public class WorkspaceLockTests public class WorkspaceLockTests {
{
[TestMethod] [TestMethod]
public void AcquireThenDisposeThenAcquireAgainSucceeds() public void AcquireThenDisposeThenAcquireAgainSucceeds() {
{
using var directory = new TempDirectory(); using var directory = new TempDirectory();
WorkspaceInitializer.Initialize(directory.FullPath); WorkspaceInitializer.Initialize(directory.FullPath);
@@ -22,8 +20,7 @@ public class WorkspaceLockTests
} }
[TestMethod] [TestMethod]
public void SecondAcquireWhileHeldThrows() public void SecondAcquireWhileHeldThrows() {
{
using var directory = new TempDirectory(); using var directory = new TempDirectory();
WorkspaceInitializer.Initialize(directory.FullPath); WorkspaceInitializer.Initialize(directory.FullPath);
@@ -34,26 +31,21 @@ public class WorkspaceLockTests
} }
[TestMethod] [TestMethod]
public void AcquireWithoutYkanbanThrowsNotInitialized() public void AcquireWithoutYkanbanThrowsNotInitialized() {
{
using var directory = new TempDirectory(); using var directory = new TempDirectory();
Assert.ThrowsExactly<WorkspaceNotInitializedException>( Assert.ThrowsExactly<WorkspaceNotInitializedException>(
() => WorkspaceLock.Acquire(directory.FullPath)); () => WorkspaceLock.Acquire(directory.FullPath));
} }
[TestMethod] [TestMethod]
public void LockFileContainsHolderDiagnosticsAfterRelease() public void LockFileIsEmptyAfterRelease() {
{
using var directory = new TempDirectory(); using var directory = new TempDirectory();
WorkspaceInitializer.Initialize(directory.FullPath); WorkspaceInitializer.Initialize(directory.FullPath);
using (WorkspaceLock.Acquire(directory.FullPath)) using (WorkspaceLock.Acquire(directory.FullPath)) {
{
} }
// The file survives release and carries PID / machine name / time for humans. // The lock file survives release but carries no content; only the OS handle matters.
string content = File.ReadAllText(WorkspacePaths.LockFile(directory.FullPath)); Assert.AreEqual(0L, new FileInfo(WorkspacePaths.LockFile(directory.FullPath)).Length);
StringAssert.Contains(content, "pid=");
StringAssert.Contains(content, $"machine={Environment.MachineName}");
} }
} }
@@ -1,98 +1,139 @@
using System.Globalization; using System.Globalization;
using Microsoft.Data.Sqlite; using Microsoft.Data.Sqlite;
using YKanBan.Storage.Workspace; using YKanBan.Storage.Workspace;
using YKanBan.Tests.TestUtilities; using YKanBan.Tests.TestUtilities;
namespace YKanBan.Tests.Storage.Workspace; namespace YKanBan.Tests.Storage.Workspace;
/// <summary> /// <summary>
/// Verifies that the preset column titles follow the UI language active when /// Verifies that the preset columns and tags follow the UI language active when
/// they are added and then live as ordinary data. These tests mutate the /// they are added and then live as ordinary data. These tests mutate the global
/// global <see cref="Resources.Culture"/>, so they are marked do-not-parallelize. /// <see cref="Resources.Culture"/>, so they are marked do-not-parallelize.
/// </summary> /// </summary>
[TestClass] [TestClass]
[DoNotParallelize] [DoNotParallelize]
public class WorkspacePresetTests public class WorkspacePresetTests {
{
[TestMethod] [TestMethod]
public void AddPresetColumnsStoresEnglishTitlesUnderEnglishCulture() public void AddPresetColumnsStoresEnglishTextUnderEnglishCulture() {
{
CultureInfo? original = Resources.Culture; CultureInfo? original = Resources.Culture;
try try {
{
Resources.Culture = new CultureInfo("en"); Resources.Culture = new CultureInfo("en");
string[] expected =
[
Resources.PresetColumn_Todo,
Resources.PresetColumn_InProgress,
Resources.PresetColumn_Done,
];
using var directory = new TempDirectory(); using var directory = new TempDirectory();
WorkspaceInitializer.Initialize(directory.FullPath); WorkspaceInitializer.Initialize(directory.FullPath);
WorkspacePreset.AddPresetColumns(directory.FullPath); WorkspacePreset.AddPresetColumns(directory.FullPath);
using SqliteConnection connection = SqliteTestHelper.OpenWorkspace(directory.FullPath); using SqliteConnection connection = SqliteTestHelper.OpenWorkspace(directory.FullPath);
CollectionAssert.AreEqual(expected, SqliteTestHelper.GetColumnTitles(connection)); CollectionAssert.AreEqual(
} new[]
finally {
{ Resources.PresetColumn_Todo,
Resources.PresetColumn_InProgress,
Resources.PresetColumn_Done,
},
SqliteTestHelper.GetColumnTitles(connection));
CollectionAssert.AreEqual(
new[]
{
Resources.PresetColumn_Todo_Description,
Resources.PresetColumn_InProgress_Description,
Resources.PresetColumn_Done_Description,
},
SqliteTestHelper.GetColumnDescriptions(connection));
} finally {
Resources.Culture = original; Resources.Culture = original;
} }
} }
[TestMethod] [TestMethod]
public void AddPresetColumnsStoresChineseTitlesUnderChineseCulture() public void AddPresetColumnsStoresChineseTextUnderChineseCulture() {
{
CultureInfo? original = Resources.Culture; CultureInfo? original = Resources.Culture;
try try {
{
Resources.Culture = new CultureInfo("zh-Hans"); Resources.Culture = new CultureInfo("zh-Hans");
string[] expected =
[
Resources.PresetColumn_Todo,
Resources.PresetColumn_InProgress,
Resources.PresetColumn_Done,
];
using var directory = new TempDirectory(); using var directory = new TempDirectory();
WorkspaceInitializer.Initialize(directory.FullPath); WorkspaceInitializer.Initialize(directory.FullPath);
WorkspacePreset.AddPresetColumns(directory.FullPath); WorkspacePreset.AddPresetColumns(directory.FullPath);
using SqliteConnection connection = SqliteTestHelper.OpenWorkspace(directory.FullPath); using SqliteConnection connection = SqliteTestHelper.OpenWorkspace(directory.FullPath);
CollectionAssert.AreEqual(expected, SqliteTestHelper.GetColumnTitles(connection)); CollectionAssert.AreEqual(
} new[]
finally {
{ Resources.PresetColumn_Todo,
Resources.PresetColumn_InProgress,
Resources.PresetColumn_Done,
},
SqliteTestHelper.GetColumnTitles(connection));
// Chinese resources must resolve to different text than English.
Assert.AreEqual("待办", Resources.PresetColumn_Todo);
Assert.AreEqual("已完成的任务。", Resources.PresetColumn_Done_Description);
} finally {
Resources.Culture = original; Resources.Culture = original;
} }
} }
[TestMethod] [TestMethod]
public void PresetTitlesAreDataAndIgnoreLaterCultureChanges() public void AddPresetTagsStoresEightTagsUnderEnglishCulture() {
{
CultureInfo? original = Resources.Culture; CultureInfo? original = Resources.Culture;
try try {
{ Resources.Culture = new CultureInfo("en");
using var directory = new TempDirectory();
WorkspaceInitializer.Initialize(directory.FullPath);
WorkspacePreset.AddPresetTags(directory.FullPath);
using SqliteConnection connection = SqliteTestHelper.OpenWorkspace(directory.FullPath);
List<(string Name, string Color, string Description)> tags = SqliteTestHelper.GetTags(connection);
Assert.AreEqual(8, tags.Count);
Assert.AreEqual(("bug", "#d73a4a", "Something isn't working"), tags[0]);
Assert.AreEqual(("documentation", "#0075ca", "Improvements or additions to documentation"), tags[1]);
Assert.AreEqual(("wontfix", "#ffffff", "This will not be worked on"), tags[7]);
} finally {
Resources.Culture = original;
}
}
[TestMethod]
public void AddPresetTagsStoresChineseNamesUnderChineseCulture() {
CultureInfo? original = Resources.Culture;
try {
Resources.Culture = new CultureInfo("zh-Hans");
using var directory = new TempDirectory();
WorkspaceInitializer.Initialize(directory.FullPath);
WorkspacePreset.AddPresetTags(directory.FullPath);
using SqliteConnection connection = SqliteTestHelper.OpenWorkspace(directory.FullPath);
List<(string Name, string Color, string Description)> tags = SqliteTestHelper.GetTags(connection);
Assert.AreEqual(8, tags.Count);
Assert.AreEqual("缺陷", tags[0].Name);
Assert.AreEqual("功能没有正常工作", tags[0].Description);
} finally {
Resources.Culture = original;
}
}
[TestMethod]
public void PresetContentIsDataAndIgnoresLaterCultureChanges() {
CultureInfo? original = Resources.Culture;
try {
Resources.Culture = new CultureInfo("en"); Resources.Culture = new CultureInfo("en");
string[] expected =
[
Resources.PresetColumn_Todo,
Resources.PresetColumn_InProgress,
Resources.PresetColumn_Done,
];
using var directory = new TempDirectory(); using var directory = new TempDirectory();
WorkspaceInitializer.Initialize(directory.FullPath); WorkspaceInitializer.Initialize(directory.FullPath);
WorkspacePreset.AddPresetColumns(directory.FullPath); WorkspacePreset.AddPresetColumns(directory.FullPath);
WorkspacePreset.AddPresetTags(directory.FullPath);
// Switching the language after adding the presets must not rewrite stored data. // Switching the language after adding the presets must not rewrite stored data.
Resources.Culture = new CultureInfo("zh-Hans"); Resources.Culture = new CultureInfo("zh-Hans");
using SqliteConnection connection = SqliteTestHelper.OpenWorkspace(directory.FullPath); using SqliteConnection connection = SqliteTestHelper.OpenWorkspace(directory.FullPath);
CollectionAssert.AreEqual(expected, SqliteTestHelper.GetColumnTitles(connection)); Assert.AreEqual("To Do", SqliteTestHelper.GetColumnTitles(connection)[0]);
} Assert.AreEqual("bug", SqliteTestHelper.GetTags(connection)[0].Name);
finally } finally {
{
Resources.Culture = original; Resources.Culture = original;
} }
} }
@@ -1,5 +1,7 @@
using Microsoft.Data.Sqlite; using Microsoft.Data.Sqlite;
using YKanBan.Models; using YKanBan.Models;
using YKanBan.Search;
using YKanBan.Storage.Workspace; using YKanBan.Storage.Workspace;
using YKanBan.Tests.TestUtilities; using YKanBan.Tests.TestUtilities;
@@ -10,16 +12,14 @@ namespace YKanBan.Tests.Storage.Workspace;
/// transaction atomicity and the timestamp refresh rules. /// transaction atomicity and the timestamp refresh rules.
/// </summary> /// </summary>
[TestClass] [TestClass]
public class WorkspaceRepositoryTests public class WorkspaceRepositoryTests {
{
/// <summary> /// <summary>
/// Owns a workspace with fixed-timestamp fixture data (one column, one /// Owns a workspace with fixed-timestamp fixture data (one column, one
/// card, two tags linked to the card) plus the repository under test. /// card, two tags linked to the card) plus the repository under test.
/// Fixture timestamps are small literal values so that any real write, /// Fixture timestamps are small literal values so that any real write,
/// which stamps the current Unix time, is observable. /// which stamps the current Unix time, is observable.
/// </summary> /// </summary>
private sealed class RepositoryFixture : IDisposable private sealed class RepositoryFixture : IDisposable {
{
public TempDirectory Directory { get; } = new(); public TempDirectory Directory { get; } = new();
public WorkspaceRepository Repository { get; } public WorkspaceRepository Repository { get; }
@@ -32,12 +32,10 @@ public class WorkspaceRepositoryTests
public long UiTagId { get; } = 2; public long UiTagId { get; } = 2;
public RepositoryFixture() public RepositoryFixture() {
{
WorkspaceInitializer.Initialize(Directory.FullPath); WorkspaceInitializer.Initialize(Directory.FullPath);
using (SqliteConnection connection = SqliteTestHelper.OpenWorkspace(Directory.FullPath)) using (SqliteConnection connection = SqliteTestHelper.OpenWorkspace(Directory.FullPath)) {
{
SqliteTestHelper.Exec(connection, "INSERT INTO columns (title, description, created_at, updated_at) VALUES ('Col', '', 100, 100);"); SqliteTestHelper.Exec(connection, "INSERT INTO columns (title, description, created_at, updated_at) VALUES ('Col', '', 100, 100);");
SqliteTestHelper.Exec(connection, "INSERT INTO cards (column_id, title, content, created_at, updated_at) VALUES (1, 'T', 'C', 100, 100);"); SqliteTestHelper.Exec(connection, "INSERT INTO cards (column_id, title, content, created_at, updated_at) VALUES (1, 'T', 'C', 100, 100);");
SqliteTestHelper.Exec(connection, "INSERT INTO tags (name, color, description) VALUES ('bug', '#ff0000', '');"); SqliteTestHelper.Exec(connection, "INSERT INTO tags (name, color, description) VALUES ('bug', '#ff0000', '');");
@@ -49,16 +47,14 @@ public class WorkspaceRepositoryTests
Repository = new WorkspaceRepository(Directory.FullPath); Repository = new WorkspaceRepository(Directory.FullPath);
} }
public void Dispose() public void Dispose() {
{
Repository.Dispose(); Repository.Dispose();
Directory.Dispose(); Directory.Dispose();
} }
} }
[TestMethod] [TestMethod]
public void GetColumnsReturnsTheSeededColumn() public void GetColumnsReturnsTheSeededColumn() {
{
using var fixture = new RepositoryFixture(); using var fixture = new RepositoryFixture();
ColumnModel column = fixture.Repository.GetColumn(fixture.ColumnId)!; ColumnModel column = fixture.Repository.GetColumn(fixture.ColumnId)!;
Assert.AreEqual("Col", column.Title); Assert.AreEqual("Col", column.Title);
@@ -66,8 +62,7 @@ public class WorkspaceRepositoryTests
} }
[TestMethod] [TestMethod]
public void AddColumnSetsEqualTimestamps() public void AddColumnSetsEqualTimestamps() {
{
using var fixture = new RepositoryFixture(); using var fixture = new RepositoryFixture();
ColumnModel column = fixture.Repository.AddColumn("New", "desc"); ColumnModel column = fixture.Repository.AddColumn("New", "desc");
Assert.IsTrue(column.CreatedAt > 0L); Assert.IsTrue(column.CreatedAt > 0L);
@@ -75,8 +70,7 @@ public class WorkspaceRepositoryTests
} }
[TestMethod] [TestMethod]
public void UpdateColumnWithoutChangeWritesNothing() public void UpdateColumnWithoutChangeWritesNothing() {
{
using var fixture = new RepositoryFixture(); using var fixture = new RepositoryFixture();
ColumnModel result = fixture.Repository.UpdateColumn(fixture.ColumnId, "Col", ""); ColumnModel result = fixture.Repository.UpdateColumn(fixture.ColumnId, "Col", "");
@@ -86,8 +80,7 @@ public class WorkspaceRepositoryTests
} }
[TestMethod] [TestMethod]
public void UpdateColumnChangeRefreshesTimestamp() public void UpdateColumnChangeRefreshesTimestamp() {
{
using var fixture = new RepositoryFixture(); using var fixture = new RepositoryFixture();
ColumnModel updated = fixture.Repository.UpdateColumn(fixture.ColumnId, "Col2", "desc"); ColumnModel updated = fixture.Repository.UpdateColumn(fixture.ColumnId, "Col2", "desc");
@@ -97,8 +90,7 @@ public class WorkspaceRepositoryTests
} }
[TestMethod] [TestMethod]
public void DeleteColumnCascadesToCardsAndTagLinks() public void DeleteColumnCascadesToCardsAndTagLinks() {
{
using var fixture = new RepositoryFixture(); using var fixture = new RepositoryFixture();
Assert.IsTrue(fixture.Repository.DeleteColumn(fixture.ColumnId)); Assert.IsTrue(fixture.Repository.DeleteColumn(fixture.ColumnId));
@@ -111,8 +103,7 @@ public class WorkspaceRepositoryTests
} }
[TestMethod] [TestMethod]
public void DeleteCardRemovesTagLinksButKeepsTags() public void DeleteCardRemovesTagLinksButKeepsTags() {
{
using var fixture = new RepositoryFixture(); using var fixture = new RepositoryFixture();
Assert.IsTrue(fixture.Repository.DeleteCard(fixture.CardId)); Assert.IsTrue(fixture.Repository.DeleteCard(fixture.CardId));
@@ -124,8 +115,7 @@ public class WorkspaceRepositoryTests
} }
[TestMethod] [TestMethod]
public void DeleteTagDetachesFromCardsButKeepsCards() public void DeleteTagDetachesFromCardsButKeepsCards() {
{
using var fixture = new RepositoryFixture(); using var fixture = new RepositoryFixture();
Assert.IsTrue(fixture.Repository.DeleteTag(fixture.BugTagId)); Assert.IsTrue(fixture.Repository.DeleteTag(fixture.BugTagId));
@@ -137,8 +127,7 @@ public class WorkspaceRepositoryTests
} }
[TestMethod] [TestMethod]
public void UpdateCardWithoutEffectiveChangeWritesNothing() public void UpdateCardWithoutEffectiveChangeWritesNothing() {
{
using var fixture = new RepositoryFixture(); using var fixture = new RepositoryFixture();
CardModel result = fixture.Repository.UpdateCard( CardModel result = fixture.Repository.UpdateCard(
@@ -148,8 +137,7 @@ public class WorkspaceRepositoryTests
} }
[TestMethod] [TestMethod]
public void UpdateCardTitleChangeRefreshesTimestamp() public void UpdateCardTitleChangeRefreshesTimestamp() {
{
using var fixture = new RepositoryFixture(); using var fixture = new RepositoryFixture();
CardModel updated = fixture.Repository.UpdateCard( CardModel updated = fixture.Repository.UpdateCard(
@@ -160,8 +148,7 @@ public class WorkspaceRepositoryTests
} }
[TestMethod] [TestMethod]
public void UpdateCardTagSetOnlyChangeStillRefreshesTimestamp() public void UpdateCardTagSetOnlyChangeStillRefreshesTimestamp() {
{
using var fixture = new RepositoryFixture(); using var fixture = new RepositoryFixture();
CardModel updated = fixture.Repository.UpdateCard(fixture.CardId, "T", "C", [fixture.BugTagId]); CardModel updated = fixture.Repository.UpdateCard(fixture.CardId, "T", "C", [fixture.BugTagId]);
@@ -171,8 +158,7 @@ public class WorkspaceRepositoryTests
} }
[TestMethod] [TestMethod]
public void UpdateCardWithUnknownTagRollsBackAtomically() public void UpdateCardWithUnknownTagRollsBackAtomically() {
{
using var fixture = new RepositoryFixture(); using var fixture = new RepositoryFixture();
// Tag 999 does not exist: the FK fires mid-transaction and the whole edit must roll back. // Tag 999 does not exist: the FK fires mid-transaction and the whole edit must roll back.
@@ -187,8 +173,7 @@ public class WorkspaceRepositoryTests
} }
[TestMethod] [TestMethod]
public void MoveCardUpdatesColumnWithoutRefreshingTimestamp() public void MoveCardUpdatesColumnWithoutRefreshingTimestamp() {
{
using var fixture = new RepositoryFixture(); using var fixture = new RepositoryFixture();
long target = fixture.Repository.AddColumn("Target", "").Id; long target = fixture.Repository.AddColumn("Target", "").Id;
@@ -201,8 +186,7 @@ public class WorkspaceRepositoryTests
} }
[TestMethod] [TestMethod]
public void MoveCardToCurrentColumnIsNoOp() public void MoveCardToCurrentColumnIsNoOp() {
{
using var fixture = new RepositoryFixture(); using var fixture = new RepositoryFixture();
Assert.IsFalse(fixture.Repository.MoveCard(fixture.CardId, fixture.ColumnId)); Assert.IsFalse(fixture.Repository.MoveCard(fixture.CardId, fixture.ColumnId));
@@ -211,8 +195,7 @@ public class WorkspaceRepositoryTests
} }
[TestMethod] [TestMethod]
public void AddCardCreatesWithEqualTimestampsAndLinkedTags() public void AddCardCreatesWithEqualTimestampsAndLinkedTags() {
{
using var fixture = new RepositoryFixture(); using var fixture = new RepositoryFixture();
CardModel card = fixture.Repository.AddCard(fixture.ColumnId, "N", "body", [fixture.UiTagId]); CardModel card = fixture.Repository.AddCard(fixture.ColumnId, "N", "body", [fixture.UiTagId]);
@@ -224,8 +207,7 @@ public class WorkspaceRepositoryTests
} }
[TestMethod] [TestMethod]
public void UpdateTagWithoutChangeWritesNothing() public void UpdateTagWithoutChangeWritesNothing() {
{
using var fixture = new RepositoryFixture(); using var fixture = new RepositoryFixture();
TagModel result = fixture.Repository.UpdateTag( TagModel result = fixture.Repository.UpdateTag(
@@ -236,8 +218,7 @@ public class WorkspaceRepositoryTests
} }
[TestMethod] [TestMethod]
public void UpdateTagChangeWrites() public void UpdateTagChangeWrites() {
{
using var fixture = new RepositoryFixture(); using var fixture = new RepositoryFixture();
TagModel updated = fixture.Repository.UpdateTag( TagModel updated = fixture.Repository.UpdateTag(
@@ -250,16 +231,24 @@ public class WorkspaceRepositoryTests
} }
[TestMethod] [TestMethod]
public void AddTagWithDuplicateNameIsRejected() public void AddTagWithDuplicateNameIsRejected() {
{
using var fixture = new RepositoryFixture(); using var fixture = new RepositoryFixture();
Assert.ThrowsExactly<SqliteException>(() => Assert.ThrowsExactly<SqliteException>(() =>
fixture.Repository.AddTag("bug", RgbColor.Parse("#123456"), "")); fixture.Repository.AddTag("bug", RgbColor.Parse("#123456"), ""));
} }
[TestMethod] [TestMethod]
public void GetTagsWithUsageCountsAssignments() public void GetCardIdsMatchingRunsTheCompiledSearch() {
{ using var fixture = new RepositoryFixture();
CompiledSearch compiled = SearchSqlCompiler.Compile(new SearchNode.FreeText("T"));
IReadOnlyCollection<long> ids = fixture.Repository.GetCardIdsMatching(compiled);
CollectionAssert.AreEquivalent(new[] { fixture.CardId }, ids.ToList());
}
[TestMethod]
public void GetTagsWithUsageCountsAssignments() {
using var fixture = new RepositoryFixture(); using var fixture = new RepositoryFixture();
IReadOnlyList<(TagModel Tag, long UsageCount)> before = fixture.Repository.GetTagsWithUsage(); IReadOnlyList<(TagModel Tag, long UsageCount)> before = fixture.Repository.GetTagsWithUsage();
@@ -1,4 +1,5 @@
using Microsoft.Data.Sqlite; using Microsoft.Data.Sqlite;
using YKanBan.Storage; using YKanBan.Storage;
using YKanBan.Storage.Workspace; using YKanBan.Storage.Workspace;
using YKanBan.Tests.TestUtilities; using YKanBan.Tests.TestUtilities;
@@ -10,19 +11,16 @@ namespace YKanBan.Tests.Storage.Workspace;
/// and that the cascading delete chains work as specified. /// and that the cascading delete chains work as specified.
/// </summary> /// </summary>
[TestClass] [TestClass]
public class WorkspaceSchemaTests public class WorkspaceSchemaTests {
{
/// <summary> /// <summary>
/// Owns a temp directory plus a fresh workspace-schema database for a single test. /// Owns a temp directory plus a fresh workspace-schema database for a single test.
/// </summary> /// </summary>
private sealed class FreshDatabase : IDisposable private sealed class FreshDatabase : IDisposable {
{
public TempDirectory Directory { get; } = new(); public TempDirectory Directory { get; } = new();
public SqliteConnection Connection { get; } public SqliteConnection Connection { get; }
public FreshDatabase() public FreshDatabase() {
{
Connection = SqliteDatabase.Open( Connection = SqliteDatabase.Open(
Path.Combine(Directory.FullPath, "ws.db"), WorkspaceSchema.Migrations); Path.Combine(Directory.FullPath, "ws.db"), WorkspaceSchema.Migrations);
} }
@@ -30,24 +28,21 @@ public class WorkspaceSchemaTests
/// <summary> /// <summary>
/// Closes the connection before removing the temporary directory. /// Closes the connection before removing the temporary directory.
/// </summary> /// </summary>
public void Dispose() public void Dispose() {
{
Connection.Dispose(); Connection.Dispose();
Directory.Dispose(); Directory.Dispose();
} }
} }
[TestMethod] [TestMethod]
public void EmptyColumnTitleIsRejected() public void EmptyColumnTitleIsRejected() {
{
using var db = new FreshDatabase(); using var db = new FreshDatabase();
Assert.ThrowsExactly<SqliteException>(() => Assert.ThrowsExactly<SqliteException>(() =>
SqliteTestHelper.Exec(db.Connection, "INSERT INTO columns (title, created_at, updated_at) VALUES ('', 1, 1);")); SqliteTestHelper.Exec(db.Connection, "INSERT INTO columns (title, created_at, updated_at) VALUES ('', 1, 1);"));
} }
[TestMethod] [TestMethod]
public void WhitespaceColumnTitleIsAccepted() public void WhitespaceColumnTitleIsAccepted() {
{
using var db = new FreshDatabase(); using var db = new FreshDatabase();
// No trimming: a single space is a non-empty title as far as the DDL is concerned. // No trimming: a single space is a non-empty title as far as the DDL is concerned.
int affected = SqliteTestHelper.Exec( int affected = SqliteTestHelper.Exec(
@@ -56,8 +51,7 @@ public class WorkspaceSchemaTests
} }
[TestMethod] [TestMethod]
public void DuplicateColumnTitleIsRejected() public void DuplicateColumnTitleIsRejected() {
{
using var db = new FreshDatabase(); using var db = new FreshDatabase();
SqliteTestHelper.Exec(db.Connection, "INSERT INTO columns (title, created_at, updated_at) VALUES ('Foo', 1, 1);"); SqliteTestHelper.Exec(db.Connection, "INSERT INTO columns (title, created_at, updated_at) VALUES ('Foo', 1, 1);");
Assert.ThrowsExactly<SqliteException>(() => Assert.ThrowsExactly<SqliteException>(() =>
@@ -65,8 +59,7 @@ public class WorkspaceSchemaTests
} }
[TestMethod] [TestMethod]
public void ColumnTitlesCompareCaseSensitively() public void ColumnTitlesCompareCaseSensitively() {
{
using var db = new FreshDatabase(); using var db = new FreshDatabase();
// BINARY collation: 'Foo' and 'foo' are distinct titles. // BINARY collation: 'Foo' and 'foo' are distinct titles.
SqliteTestHelper.Exec(db.Connection, "INSERT INTO columns (title, created_at, updated_at) VALUES ('Foo', 1, 1);"); SqliteTestHelper.Exec(db.Connection, "INSERT INTO columns (title, created_at, updated_at) VALUES ('Foo', 1, 1);");
@@ -75,28 +68,24 @@ public class WorkspaceSchemaTests
} }
[TestMethod] [TestMethod]
public void EmptyTagNameIsRejected() public void EmptyTagNameIsRejected() {
{
using var db = new FreshDatabase(); using var db = new FreshDatabase();
Assert.ThrowsExactly<SqliteException>(() => Assert.ThrowsExactly<SqliteException>(() =>
SqliteTestHelper.Exec(db.Connection, "INSERT INTO tags (name, color) VALUES ('', '#112233');")); SqliteTestHelper.Exec(db.Connection, "INSERT INTO tags (name, color) VALUES ('', '#112233');"));
} }
[TestMethod] [TestMethod]
public void TagNamesAcceptSpacesEmojiAndReservedWords() public void TagNamesAcceptSpacesEmojiAndReservedWords() {
{
using var db = new FreshDatabase(); using var db = new FreshDatabase();
// Tag names are fully open: no charset or length rules, no trimming. // Tag names are fully open: no charset or length rules, no trimming.
foreach (string name in new[] { " ", "a b", "🏷️", "AND", "tag:with:colons" }) foreach (string name in new[] { " ", "a b", "🏷️", "AND", "tag:with:colons" }) {
{
SqliteTestHelper.Exec(db.Connection, "INSERT INTO tags (name, color) VALUES ($n, '#112233');", ("$n", name)); SqliteTestHelper.Exec(db.Connection, "INSERT INTO tags (name, color) VALUES ($n, '#112233');", ("$n", name));
} }
Assert.AreEqual(5L, SqliteTestHelper.ScalarLong(db.Connection, "SELECT COUNT(*) FROM tags;")); Assert.AreEqual(5L, SqliteTestHelper.ScalarLong(db.Connection, "SELECT COUNT(*) FROM tags;"));
} }
[TestMethod] [TestMethod]
public void DuplicateTagNameIsRejected() public void DuplicateTagNameIsRejected() {
{
using var db = new FreshDatabase(); using var db = new FreshDatabase();
SqliteTestHelper.Exec(db.Connection, "INSERT INTO tags (name, color) VALUES ('bug', '#112233');"); SqliteTestHelper.Exec(db.Connection, "INSERT INTO tags (name, color) VALUES ('bug', '#112233');");
Assert.ThrowsExactly<SqliteException>(() => Assert.ThrowsExactly<SqliteException>(() =>
@@ -107,8 +96,7 @@ public class WorkspaceSchemaTests
[DataRow("#000000")] [DataRow("#000000")]
[DataRow("#FFFFFF")] [DataRow("#FFFFFF")]
[DataRow("#a1B2c3")] [DataRow("#a1B2c3")]
public void ValidTagColorsAreAccepted(string color) public void ValidTagColorsAreAccepted(string color) {
{
using var db = new FreshDatabase(); using var db = new FreshDatabase();
int affected = SqliteTestHelper.Exec( int affected = SqliteTestHelper.Exec(
db.Connection, "INSERT INTO tags (name, color) VALUES ('x', $c);", ("$c", color)); db.Connection, "INSERT INTO tags (name, color) VALUES ('x', $c);", ("$c", color));
@@ -124,16 +112,14 @@ public class WorkspaceSchemaTests
[DataRow(" #112233")] [DataRow(" #112233")]
[DataRow("#112233 ")] [DataRow("#112233 ")]
[DataRow("")] [DataRow("")]
public void InvalidTagColorsAreRejected(string color) public void InvalidTagColorsAreRejected(string color) {
{
using var db = new FreshDatabase(); using var db = new FreshDatabase();
Assert.ThrowsExactly<SqliteException>(() => Assert.ThrowsExactly<SqliteException>(() =>
SqliteTestHelper.Exec(db.Connection, "INSERT INTO tags (name, color) VALUES ('x', $c);", ("$c", color))); SqliteTestHelper.Exec(db.Connection, "INSERT INTO tags (name, color) VALUES ('x', $c);", ("$c", color)));
} }
[TestMethod] [TestMethod]
public void CardRequiresExistingColumn() public void CardRequiresExistingColumn() {
{
using var db = new FreshDatabase(); using var db = new FreshDatabase();
// foreign_keys=ON makes the FK enforceable; this is the DDL contract behind the cascades. // foreign_keys=ON makes the FK enforceable; this is the DDL contract behind the cascades.
Assert.ThrowsExactly<SqliteException>(() => Assert.ThrowsExactly<SqliteException>(() =>
@@ -141,8 +127,7 @@ public class WorkspaceSchemaTests
} }
[TestMethod] [TestMethod]
public void CardDefaultsToEmptyTitleAndContent() public void CardDefaultsToEmptyTitleAndContent() {
{
using var db = new FreshDatabase(); using var db = new FreshDatabase();
SqliteTestHelper.Exec(db.Connection, "INSERT INTO columns (title, created_at, updated_at) VALUES ('c', 1, 1);"); SqliteTestHelper.Exec(db.Connection, "INSERT INTO columns (title, created_at, updated_at) VALUES ('c', 1, 1);");
SqliteTestHelper.Exec(db.Connection, "INSERT INTO cards (column_id, created_at, updated_at) VALUES (1, 1, 1);"); SqliteTestHelper.Exec(db.Connection, "INSERT INTO cards (column_id, created_at, updated_at) VALUES (1, 1, 1);");
@@ -153,8 +138,7 @@ public class WorkspaceSchemaTests
} }
[TestMethod] [TestMethod]
public void CardTagDuplicateAssignmentIsRejected() public void CardTagDuplicateAssignmentIsRejected() {
{
using var db = new FreshDatabase(); using var db = new FreshDatabase();
SqliteTestHelper.Exec(db.Connection, "INSERT INTO columns (title, created_at, updated_at) VALUES ('c', 1, 1);"); SqliteTestHelper.Exec(db.Connection, "INSERT INTO columns (title, created_at, updated_at) VALUES ('c', 1, 1);");
SqliteTestHelper.Exec(db.Connection, "INSERT INTO cards (column_id, created_at, updated_at) VALUES (1, 1, 1);"); SqliteTestHelper.Exec(db.Connection, "INSERT INTO cards (column_id, created_at, updated_at) VALUES (1, 1, 1);");
@@ -167,8 +151,7 @@ public class WorkspaceSchemaTests
} }
[TestMethod] [TestMethod]
public void DeletingColumnCascadesToCardsAndCardTags() public void DeletingColumnCascadesToCardsAndCardTags() {
{
using var db = new FreshDatabase(); using var db = new FreshDatabase();
InsertBoardRow(db.Connection); InsertBoardRow(db.Connection);
@@ -182,8 +165,7 @@ public class WorkspaceSchemaTests
} }
[TestMethod] [TestMethod]
public void DeletingCardCascadesToCardTagsOnly() public void DeletingCardCascadesToCardTagsOnly() {
{
using var db = new FreshDatabase(); using var db = new FreshDatabase();
InsertBoardRow(db.Connection); InsertBoardRow(db.Connection);
@@ -196,8 +178,7 @@ public class WorkspaceSchemaTests
} }
[TestMethod] [TestMethod]
public void DeletingTagRemovesAssignmentsButKeepsCards() public void DeletingTagRemovesAssignmentsButKeepsCards() {
{
using var db = new FreshDatabase(); using var db = new FreshDatabase();
InsertBoardRow(db.Connection); InsertBoardRow(db.Connection);
@@ -214,8 +195,7 @@ public class WorkspaceSchemaTests
/// Inserts one column, one card, one tag and their assignment, ready for a cascade test. /// Inserts one column, one card, one tag and their assignment, ready for a cascade test.
/// </summary> /// </summary>
/// <param name="connection">An open workspace-schema connection.</param> /// <param name="connection">An open workspace-schema connection.</param>
private static void InsertBoardRow(SqliteConnection connection) private static void InsertBoardRow(SqliteConnection connection) {
{
SqliteTestHelper.Exec(connection, "INSERT INTO columns (title, created_at, updated_at) VALUES ('c', 1, 1);"); SqliteTestHelper.Exec(connection, "INSERT INTO columns (title, created_at, updated_at) VALUES ('c', 1, 1);");
SqliteTestHelper.Exec(connection, "INSERT INTO cards (column_id, created_at, updated_at) VALUES (1, 1, 1);"); SqliteTestHelper.Exec(connection, "INSERT INTO cards (column_id, created_at, updated_at) VALUES (1, 1, 1);");
SqliteTestHelper.Exec(connection, "INSERT INTO tags (name, color) VALUES ('bug', '#112233');"); SqliteTestHelper.Exec(connection, "INSERT INTO tags (name, color) VALUES ('bug', '#112233');");
@@ -10,11 +10,9 @@ namespace YKanBan.Tests.Storage.Workspace;
/// the whole session and the repository is usable through it. /// the whole session and the repository is usable through it.
/// </summary> /// </summary>
[TestClass] [TestClass]
public class WorkspaceSessionTests public class WorkspaceSessionTests {
{
[TestMethod] [TestMethod]
public void OpenHoldsLockUntilDisposed() public void OpenHoldsLockUntilDisposed() {
{
using var directory = new TempDirectory(); using var directory = new TempDirectory();
WorkspaceInitializer.Initialize(directory.FullPath); WorkspaceInitializer.Initialize(directory.FullPath);
@@ -25,8 +23,7 @@ public class WorkspaceSessionTests
} }
[TestMethod] [TestMethod]
public void DisposeReleasesLockForReopen() public void DisposeReleasesLockForReopen() {
{
using var directory = new TempDirectory(); using var directory = new TempDirectory();
WorkspaceInitializer.Initialize(directory.FullPath); WorkspaceInitializer.Initialize(directory.FullPath);
@@ -37,8 +34,7 @@ public class WorkspaceSessionTests
} }
[TestMethod] [TestMethod]
public void OpenUninitializedFolderThrowsNotInitialized() public void OpenUninitializedFolderThrowsNotInitialized() {
{
using var directory = new TempDirectory(); using var directory = new TempDirectory();
Assert.ThrowsExactly<WorkspaceNotInitializedException>( Assert.ThrowsExactly<WorkspaceNotInitializedException>(
@@ -46,8 +42,7 @@ public class WorkspaceSessionTests
} }
[TestMethod] [TestMethod]
public void RepositoryIsUsableThroughSession() public void RepositoryIsUsableThroughSession() {
{
using var directory = new TempDirectory(); using var directory = new TempDirectory();
WorkspaceInitializer.Initialize(directory.FullPath); WorkspaceInitializer.Initialize(directory.FullPath);
+44 -18
View File
@@ -1,4 +1,5 @@
using Microsoft.Data.Sqlite; using Microsoft.Data.Sqlite;
using YKanBan.Storage; using YKanBan.Storage;
using YKanBan.Storage.Workspace; using YKanBan.Storage.Workspace;
@@ -8,8 +9,7 @@ namespace YKanBan.Tests.TestUtilities;
/// Shared helpers for the storage tests: small SQL conveniences plus opening a /// Shared helpers for the storage tests: small SQL conveniences plus opening a
/// workspace database with the real migration list. /// workspace database with the real migration list.
/// </summary> /// </summary>
public static class SqliteTestHelper public static class SqliteTestHelper {
{
/// <summary> /// <summary>
/// Executes a non-query SQL statement and returns the affected row count. /// Executes a non-query SQL statement and returns the affected row count.
/// </summary> /// </summary>
@@ -17,12 +17,10 @@ public static class SqliteTestHelper
/// <param name="sql">The statement to execute.</param> /// <param name="sql">The statement to execute.</param>
/// <param name="parameters">Name/value pairs bound as SQL parameters.</param> /// <param name="parameters">Name/value pairs bound as SQL parameters.</param>
/// <returns>The number of affected rows.</returns> /// <returns>The number of affected rows.</returns>
public static int Exec(SqliteConnection connection, string sql, params (string Name, object? Value)[] parameters) public static int Exec(SqliteConnection connection, string sql, params (string Name, object? Value)[] parameters) {
{
using var command = connection.CreateCommand(); using var command = connection.CreateCommand();
command.CommandText = sql; command.CommandText = sql;
foreach ((string name, object? value) in parameters) foreach ((string name, object? value) in parameters) {
{
command.Parameters.AddWithValue(name, value); command.Parameters.AddWithValue(name, value);
} }
return command.ExecuteNonQuery(); return command.ExecuteNonQuery();
@@ -34,8 +32,7 @@ public static class SqliteTestHelper
/// <param name="connection">An open database connection.</param> /// <param name="connection">An open database connection.</param>
/// <param name="sql">The query to execute.</param> /// <param name="sql">The query to execute.</param>
/// <returns>The scalar result cast to a string.</returns> /// <returns>The scalar result cast to a string.</returns>
public static string ScalarString(SqliteConnection connection, string sql) public static string ScalarString(SqliteConnection connection, string sql) {
{
using var command = connection.CreateCommand(); using var command = connection.CreateCommand();
command.CommandText = sql; command.CommandText = sql;
return (string)command.ExecuteScalar()!; return (string)command.ExecuteScalar()!;
@@ -47,8 +44,7 @@ public static class SqliteTestHelper
/// <param name="connection">An open database connection.</param> /// <param name="connection">An open database connection.</param>
/// <param name="sql">The query to execute.</param> /// <param name="sql">The query to execute.</param>
/// <returns>The scalar result cast to a long.</returns> /// <returns>The scalar result cast to a long.</returns>
public static long ScalarLong(SqliteConnection connection, string sql) public static long ScalarLong(SqliteConnection connection, string sql) {
{
using var command = connection.CreateCommand(); using var command = connection.CreateCommand();
command.CommandText = sql; command.CommandText = sql;
return (long)command.ExecuteScalar()!; return (long)command.ExecuteScalar()!;
@@ -60,8 +56,7 @@ public static class SqliteTestHelper
/// <param name="connection">An open database connection.</param> /// <param name="connection">An open database connection.</param>
/// <param name="tableName">The table name to look for.</param> /// <param name="tableName">The table name to look for.</param>
/// <returns><see langword="true"/> when the table exists.</returns> /// <returns><see langword="true"/> when the table exists.</returns>
public static bool TableExists(SqliteConnection connection, string tableName) public static bool TableExists(SqliteConnection connection, string tableName) {
{
using var command = connection.CreateCommand(); using var command = connection.CreateCommand();
command.CommandText = "SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name=$name;"; command.CommandText = "SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name=$name;";
command.Parameters.AddWithValue("$name", tableName); command.Parameters.AddWithValue("$name", tableName);
@@ -73,27 +68,58 @@ public static class SqliteTestHelper
/// </summary> /// </summary>
/// <param name="connection">An open database connection.</param> /// <param name="connection">An open database connection.</param>
/// <returns>The column titles in id order.</returns> /// <returns>The column titles in id order.</returns>
public static List<string> GetColumnTitles(SqliteConnection connection) public static List<string> GetColumnTitles(SqliteConnection connection) {
{
using var command = connection.CreateCommand(); using var command = connection.CreateCommand();
command.CommandText = "SELECT title FROM columns ORDER BY id ASC;"; command.CommandText = "SELECT title FROM columns ORDER BY id ASC;";
using var reader = command.ExecuteReader(); using var reader = command.ExecuteReader();
var titles = new List<string>(); var titles = new List<string>();
while (reader.Read()) while (reader.Read()) {
{
titles.Add(reader.GetString(0)); titles.Add(reader.GetString(0));
} }
return titles; return titles;
} }
/// <summary>
/// Returns the descriptions of all columns, ordered by id ascending.
/// </summary>
/// <param name="connection">An open database connection.</param>
/// <returns>The column descriptions in id order.</returns>
public static List<string> GetColumnDescriptions(SqliteConnection connection) {
using var command = connection.CreateCommand();
command.CommandText = "SELECT description FROM columns ORDER BY id ASC;";
using var reader = command.ExecuteReader();
var descriptions = new List<string>();
while (reader.Read()) {
descriptions.Add(reader.GetString(0));
}
return descriptions;
}
/// <summary>
/// Returns all tags as name/color/description tuples, ordered by id ascending.
/// </summary>
/// <param name="connection">An open database connection.</param>
/// <returns>The tags in id order.</returns>
public static List<(string Name, string Color, string Description)> GetTags(SqliteConnection connection) {
using var command = connection.CreateCommand();
command.CommandText = "SELECT name, color, description FROM tags ORDER BY id ASC;";
using var reader = command.ExecuteReader();
var tags = new List<(string, string, string)>();
while (reader.Read()) {
tags.Add((reader.GetString(0), reader.GetString(1), reader.GetString(2)));
}
return tags;
}
/// <summary> /// <summary>
/// Opens a workspace database with the real workspace migration list. /// Opens a workspace database with the real workspace migration list.
/// </summary> /// </summary>
/// <param name="folderPath">The workspace folder path.</param> /// <param name="folderPath">The workspace folder path.</param>
/// <returns>An open, migrated connection.</returns> /// <returns>An open, migrated connection.</returns>
public static SqliteConnection OpenWorkspace(string folderPath) public static SqliteConnection OpenWorkspace(string folderPath) {
{
return SqliteDatabase.Open(WorkspacePaths.Database(folderPath), WorkspaceSchema.Migrations); return SqliteDatabase.Open(WorkspacePaths.Database(folderPath), WorkspaceSchema.Migrations);
} }
} }
+12 -16
View File
@@ -5,15 +5,13 @@ namespace YKanBan.Tests.TestUtilities;
/// disposal. The removal is retried once because SQLite WAL sidecar files can /// disposal. The removal is retried once because SQLite WAL sidecar files can
/// linger for a moment after the connections close. /// linger for a moment after the connections close.
/// </summary> /// </summary>
public sealed class TempDirectory : IDisposable public sealed class TempDirectory : IDisposable {
{
/// <summary> /// <summary>
/// Gets the unique directory path managed by this instance. /// Gets the unique directory path managed by this instance.
/// </summary> /// </summary>
public string FullPath { get; } public string FullPath { get; }
public TempDirectory() public TempDirectory() {
{
FullPath = Path.Combine(Path.GetTempPath(), "ykanban-tests-" + Guid.NewGuid().ToString("N")); FullPath = Path.Combine(Path.GetTempPath(), "ykanban-tests-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(FullPath); Directory.CreateDirectory(FullPath);
} }
@@ -21,21 +19,19 @@ public sealed class TempDirectory : IDisposable
/// <summary> /// <summary>
/// Deletes the directory tree, retrying once after a short delay. /// Deletes the directory tree, retrying once after a short delay.
/// </summary> /// </summary>
public void Dispose() public void Dispose() {
{ try {
try // SAFETY: Recursive directory delete is safe: FullPath is the
{ // read-only, GUID-named directory this instance created under the
// OS temp folder, so it can never target user data or the temp root.
Directory.Delete(FullPath, recursive: true); Directory.Delete(FullPath, recursive: true);
} } catch (IOException) {
catch (IOException)
{
Thread.Sleep(100); Thread.Sleep(100);
try try {
{ // SAFETY: Retry of the same recursive delete, still confined to
// this instance's own temp directory.
Directory.Delete(FullPath, recursive: true); Directory.Delete(FullPath, recursive: true);
} } catch (IOException) {
catch (IOException)
{
// Leftovers in the OS temp folder are harmless; never fail a test over cleanup. // Leftovers in the OS temp folder are harmless; never fail a test over cleanup.
} }
} }
+11
View File
@@ -12,6 +12,7 @@
<Application.Styles> <Application.Styles>
<!-- Semi.Avalonia provides the light and dark palettes; icons need their own theme. --> <!-- Semi.Avalonia provides the light and dark palettes; icons need their own theme. -->
<semi:SemiTheme/> <semi:SemiTheme/>
<semi:ColorPickerSemiTheme/>
<StyleInclude Source="avares://IconPacks.Avalonia.Lucide/Lucide.axaml"/> <StyleInclude Source="avares://IconPacks.Avalonia.Lucide/Lucide.axaml"/>
</Application.Styles> </Application.Styles>
@@ -26,10 +27,20 @@
<ResourceDictionary x:Key="Light"> <ResourceDictionary x:Key="Light">
<SolidColorBrush x:Key="TopBarBackgroundBrush" Color="#F6F7F9"/> <SolidColorBrush x:Key="TopBarBackgroundBrush" Color="#F6F7F9"/>
<SolidColorBrush x:Key="TopBarBorderBrush" Color="#E2E4EA"/> <SolidColorBrush x:Key="TopBarBorderBrush" Color="#E2E4EA"/>
<SolidColorBrush x:Key="BoardColumnBackgroundBrush" Color="#F1F2F5"/>
<SolidColorBrush x:Key="BoardColumnBorderBrush" Color="#E2E4EA"/>
<SolidColorBrush x:Key="CardBackgroundBrush" Color="#FFFFFF"/>
<SolidColorBrush x:Key="CardBorderBrush" Color="#E2E4EA"/>
<SolidColorBrush x:Key="ErrorTextBrush" Color="#C0392B"/>
</ResourceDictionary> </ResourceDictionary>
<ResourceDictionary x:Key="Dark"> <ResourceDictionary x:Key="Dark">
<SolidColorBrush x:Key="TopBarBackgroundBrush" Color="#1C1E24"/> <SolidColorBrush x:Key="TopBarBackgroundBrush" Color="#1C1E24"/>
<SolidColorBrush x:Key="TopBarBorderBrush" Color="#2C2F37"/> <SolidColorBrush x:Key="TopBarBorderBrush" Color="#2C2F37"/>
<SolidColorBrush x:Key="BoardColumnBackgroundBrush" Color="#17181C"/>
<SolidColorBrush x:Key="BoardColumnBorderBrush" Color="#2C2F37"/>
<SolidColorBrush x:Key="CardBackgroundBrush" Color="#23252B"/>
<SolidColorBrush x:Key="CardBorderBrush" Color="#33363F"/>
<SolidColorBrush x:Key="ErrorTextBrush" Color="#FF6B6B"/>
</ResourceDictionary> </ResourceDictionary>
</ResourceDictionary.ThemeDictionaries> </ResourceDictionary.ThemeDictionaries>
</ResourceDictionary> </ResourceDictionary>
+16 -27
View File
@@ -1,20 +1,22 @@
using System.Globalization; using System.Globalization;
using Avalonia; using Avalonia;
using Avalonia.Controls.ApplicationLifetimes; using Avalonia.Controls.ApplicationLifetimes;
using Avalonia.Data.Core.Plugins; using Avalonia.Data.Core.Plugins;
using Avalonia.Markup.Xaml; using Avalonia.Markup.Xaml;
using Avalonia.Media; using Avalonia.Media;
using Avalonia.Styling; using Avalonia.Styling;
using YKanBan.Services; using YKanBan.Services;
using YKanBan.Storage.AppData; using YKanBan.Storage.AppData;
using YKanBan.ViewModels; using YKanBan.ViewModels;
using YKanBan.Views; using YKanBan.Views;
using Resx = YKanBan.Resources; using Resx = YKanBan.Resources;
namespace YKanBan; namespace YKanBan;
public partial class App : Application public partial class App : Application {
{
/// <summary> /// <summary>
/// Gets the process-wide composition root, created at startup. /// Gets the process-wide composition root, created at startup.
/// </summary> /// </summary>
@@ -26,15 +28,12 @@ public partial class App : Application
/// </summary> /// </summary>
public static string StartupLanguage { get; private set; } = AppConfig.DefaultLanguage; public static string StartupLanguage { get; private set; } = AppConfig.DefaultLanguage;
public override void Initialize() public override void Initialize() {
{
AvaloniaXamlLoader.Load(this); AvaloniaXamlLoader.Load(this);
} }
public override void OnFrameworkInitializationCompleted() public override void OnFrameworkInitializationCompleted() {
{ if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop) {
if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
{
DisableAvaloniaDataAnnotationValidation(); DisableAvaloniaDataAnnotationValidation();
// Startup order: apply the configured culture, its RTL flow direction // Startup order: apply the configured culture, its RTL flow direction
@@ -46,8 +45,7 @@ public partial class App : Application
ApplyTheme(Services.Config.Theme); ApplyTheme(Services.Config.Theme);
var viewModel = new MainWindowViewModel(Services, desktop.Args ?? []); var viewModel = new MainWindowViewModel(Services, desktop.Args ?? []);
desktop.MainWindow = new MainWindow desktop.MainWindow = new MainWindow {
{
DataContext = viewModel, DataContext = viewModel,
// RTL detection drives the whole window flow direction; the two // RTL detection drives the whole window flow direction; the two
@@ -67,14 +65,10 @@ public partial class App : Application
/// </summary> /// </summary>
/// <param name="language">The language code from app.json.</param> /// <param name="language">The language code from app.json.</param>
/// <returns>The resolved culture.</returns> /// <returns>The resolved culture.</returns>
public static CultureInfo ResolveCulture(string language) public static CultureInfo ResolveCulture(string language) {
{ try {
try
{
return new CultureInfo(language); return new CultureInfo(language);
} } catch (CultureNotFoundException) {
catch (CultureNotFoundException)
{
return new CultureInfo(AppConfig.DefaultLanguage); return new CultureInfo(AppConfig.DefaultLanguage);
} }
} }
@@ -84,28 +78,23 @@ public partial class App : Application
/// inherits the operating system preference. /// inherits the operating system preference.
/// </summary> /// </summary>
/// <param name="option">The theme selection.</param> /// <param name="option">The theme selection.</param>
public static void ApplyTheme(ThemeOption option) public static void ApplyTheme(ThemeOption option) {
{ if (Current is null) {
if (Current is null)
{
return; return;
} }
Current.RequestedThemeVariant = option switch Current.RequestedThemeVariant = option switch {
{
ThemeOption.Light => ThemeVariant.Light, ThemeOption.Light => ThemeVariant.Light,
ThemeOption.Dark => ThemeVariant.Dark, ThemeOption.Dark => ThemeVariant.Dark,
_ => ThemeVariant.Default, _ => ThemeVariant.Default,
}; };
} }
private static void DisableAvaloniaDataAnnotationValidation() private static void DisableAvaloniaDataAnnotationValidation() {
{
var dataValidationPluginsToRemove = var dataValidationPluginsToRemove =
BindingPlugins.DataValidators.OfType<DataAnnotationsValidationPlugin>().ToArray(); BindingPlugins.DataValidators.OfType<DataAnnotationsValidationPlugin>().ToArray();
foreach (var plugin in dataValidationPluginsToRemove) foreach (var plugin in dataValidationPluginsToRemove) {
{
BindingPlugins.DataValidators.Remove(plugin); BindingPlugins.DataValidators.Remove(plugin);
} }
} }
+281 -2
View File
@@ -25,6 +25,12 @@
<data name="Common_Cancel" xml:space="preserve"> <data name="Common_Cancel" xml:space="preserve">
<value>Cancel</value> <value>Cancel</value>
</data> </data>
<data name="Common_Delete" xml:space="preserve">
<value>Delete</value>
</data>
<data name="Common_Edit" xml:space="preserve">
<value>Edit</value>
</data>
<data name="Main_Export" xml:space="preserve"> <data name="Main_Export" xml:space="preserve">
<value>Export</value> <value>Export</value>
</data> </data>
@@ -40,6 +46,216 @@
<data name="Tab_Board" xml:space="preserve"> <data name="Tab_Board" xml:space="preserve">
<value>Board</value> <value>Board</value>
</data> </data>
<data name="Board_SearchPlaceholder" xml:space="preserve">
<value>Search…</value>
</data>
<data name="Board_Search" xml:space="preserve">
<value>Search</value>
</data>
<data name="Board_ClearSearch" xml:space="preserve">
<value>Clear</value>
</data>
<data name="Board_AddColumn" xml:space="preserve">
<value>Add Column</value>
</data>
<data name="Board_ColumnWidth" xml:space="preserve">
<value>Column Width</value>
</data>
<data name="Board_SortCard" xml:space="preserve">
<value>Card Sort</value>
</data>
<data name="Board_SortColumn" xml:space="preserve">
<value>Column Sort</value>
</data>
<data name="Board_Display" xml:space="preserve">
<value>Display</value>
</data>
<data name="Board_NoColumns" xml:space="preserve">
<value>No columns yet.</value>
</data>
<data name="Board_FilterActive" xml:space="preserve">
<value>Board is filtered</value>
</data>
<data name="Board_FilterInactive" xml:space="preserve">
<value>Board is not filtered</value>
</data>
<data name="Search_Error_Title" xml:space="preserve">
<value>Invalid search</value>
</data>
<data name="Search_Error_Message" xml:space="preserve">
<value>The query expression is invalid. Details: {0}</value>
</data>
<data name="Sort_IdAsc" xml:space="preserve">
<value>ID Ascending</value>
</data>
<data name="Sort_IdDesc" xml:space="preserve">
<value>ID Descending</value>
</data>
<data name="Sort_CreatedAsc" xml:space="preserve">
<value>Created Ascending</value>
</data>
<data name="Sort_CreatedDesc" xml:space="preserve">
<value>Created Descending</value>
</data>
<data name="Sort_UpdatedAsc" xml:space="preserve">
<value>Modified Ascending</value>
</data>
<data name="Sort_UpdatedDesc" xml:space="preserve">
<value>Modified Descending</value>
</data>
<data name="Sort_TitleAsc" xml:space="preserve">
<value>Title Ascending</value>
</data>
<data name="Sort_TitleDesc" xml:space="preserve">
<value>Title Descending</value>
</data>
<data name="Column_AddCard" xml:space="preserve">
<value>New Card</value>
</data>
<data name="Column_Edit" xml:space="preserve">
<value>Edit</value>
</data>
<data name="Column_Delete" xml:space="preserve">
<value>Delete</value>
</data>
<data name="Card_Delete" xml:space="preserve">
<value>Delete</value>
</data>
<data name="Card_Move" xml:space="preserve">
<value>Move to Column…</value>
</data>
<data name="ColumnDialog_AddTitle" xml:space="preserve">
<value>New Column</value>
</data>
<data name="ColumnDialog_EditTitle" xml:space="preserve">
<value>Edit Column</value>
</data>
<data name="ColumnDialog_Title" xml:space="preserve">
<value>Title</value>
</data>
<data name="ColumnDialog_Description" xml:space="preserve">
<value>Description</value>
</data>
<data name="ColumnDialog_InvalidTitle" xml:space="preserve">
<value>The title is empty or already used.</value>
</data>
<data name="CardDialog_AddTitle" xml:space="preserve">
<value>New Card</value>
</data>
<data name="CardDialog_EditTitle" xml:space="preserve">
<value>Edit Card</value>
</data>
<data name="CardDialog_Title" xml:space="preserve">
<value>Title</value>
</data>
<data name="CardDialog_Content" xml:space="preserve">
<value>Content</value>
</data>
<data name="CardDialog_Tags" xml:space="preserve">
<value>Tags</value>
</data>
<data name="CardDialog_AddTag" xml:space="preserve">
<value>Add Tag</value>
</data>
<data name="CardDialog_Id" xml:space="preserve">
<value>ID: {0}</value>
</data>
<data name="CardDialog_Created" xml:space="preserve">
<value>Created: {0}</value>
</data>
<data name="CardDialog_Modified" xml:space="preserve">
<value>Modified: {0}</value>
</data>
<data name="CardDialog_TimePattern" xml:space="preserve">
<value>yyyy-MM-dd HH:mm</value>
</data>
<data name="CardDialog_Error" xml:space="preserve">
<value>Could not save the card.</value>
</data>
<data name="TagDialog_Title" xml:space="preserve">
<value>Add Tag</value>
</data>
<data name="TagDialog_Target" xml:space="preserve">
<value>Tag</value>
</data>
<data name="TagDialog_NoTargets" xml:space="preserve">
<value>There are no more tags to add.</value>
</data>
<data name="Tags_AddTag" xml:space="preserve">
<value>Add Tag</value>
</data>
<data name="Tags_Empty" xml:space="preserve">
<value>No tags yet.</value>
</data>
<data name="Tags_Usage" xml:space="preserve">
<value>{0} cards</value>
</data>
<data name="TagEditor_AddTitle" xml:space="preserve">
<value>New Tag</value>
</data>
<data name="TagEditor_EditTitle" xml:space="preserve">
<value>Edit Tag</value>
</data>
<data name="TagEditor_Name" xml:space="preserve">
<value>Name</value>
</data>
<data name="TagEditor_Color" xml:space="preserve">
<value>Color</value>
</data>
<data name="TagEditor_Description" xml:space="preserve">
<value>Description</value>
</data>
<data name="TagEditor_InvalidName" xml:space="preserve">
<value>The name is empty or already used.</value>
</data>
<data name="DeleteTag_Confirm_Title" xml:space="preserve">
<value>Delete Tag</value>
</data>
<data name="DeleteTag_Confirm_Message" xml:space="preserve">
<value>Delete tag "{0}"? It will be removed from {1} card(s).</value>
</data>
<data name="MoveDialog_Title" xml:space="preserve">
<value>Move Card</value>
</data>
<data name="MoveDialog_Target" xml:space="preserve">
<value>Target Column</value>
</data>
<data name="MoveDialog_NoTargets" xml:space="preserve">
<value>There is nowhere to move this card.</value>
</data>
<data name="WidthPreset_Narrow" xml:space="preserve">
<value>Narrow</value>
</data>
<data name="WidthPreset_Standard" xml:space="preserve">
<value>Standard</value>
</data>
<data name="WidthPreset_Wide" xml:space="preserve">
<value>Wide</value>
</data>
<data name="WidthPreset_Custom" xml:space="preserve">
<value>Custom</value>
</data>
<data name="WidthDialog_Pixels" xml:space="preserve">
<value>Pixels (160–720)</value>
</data>
<data name="Confirm_DeleteColumn_Title" xml:space="preserve">
<value>Delete Column</value>
</data>
<data name="Confirm_DeleteColumn_Message" xml:space="preserve">
<value>Delete column "{0}" and its {1} card(s)?</value>
</data>
<data name="Confirm_DeleteCard_Title" xml:space="preserve">
<value>Delete Card</value>
</data>
<data name="Confirm_DeleteCard_Message" xml:space="preserve">
<value>Delete card #{0}?</value>
</data>
<data name="Confirm_Discard_Title" xml:space="preserve">
<value>Discard Changes</value>
</data>
<data name="Confirm_Discard_Message" xml:space="preserve">
<value>Discard the unsaved changes?</value>
</data>
<data name="Error_Argument_Title" xml:space="preserve"> <data name="Error_Argument_Title" xml:space="preserve">
<value>Invalid arguments</value> <value>Invalid arguments</value>
</data> </data>
@@ -62,7 +278,7 @@
<value>The folder does not contain a .ykanban workspace: {0}</value> <value>The folder does not contain a .ykanban workspace: {0}</value>
</data> </data>
<data name="Error_NotInitialized_Initialize" xml:space="preserve"> <data name="Error_NotInitialized_Initialize" xml:space="preserve">
<value>Initialize workspace</value> <value>Initialize Workspace</value>
</data> </data>
<data name="Error_LockConflict_Title" xml:space="preserve"> <data name="Error_LockConflict_Title" xml:space="preserve">
<value>Workspace locked</value> <value>Workspace locked</value>
@@ -95,7 +311,7 @@
<value>Dark</value> <value>Dark</value>
</data> </data>
<data name="Settings_ThemeFollowSystem" xml:space="preserve"> <data name="Settings_ThemeFollowSystem" xml:space="preserve">
<value>Follow system</value> <value>Follow System</value>
</data> </data>
<data name="Settings_Confirmations" xml:space="preserve"> <data name="Settings_Confirmations" xml:space="preserve">
<value>Confirmations</value> <value>Confirmations</value>
@@ -130,12 +346,69 @@
<data name="PresetColumn_Todo" xml:space="preserve"> <data name="PresetColumn_Todo" xml:space="preserve">
<value>To Do</value> <value>To Do</value>
</data> </data>
<data name="PresetColumn_Todo_Description" xml:space="preserve">
<value>Tasks that are planned but not started.</value>
</data>
<data name="PresetColumn_InProgress" xml:space="preserve"> <data name="PresetColumn_InProgress" xml:space="preserve">
<value>In Progress</value> <value>In Progress</value>
</data> </data>
<data name="PresetColumn_InProgress_Description" xml:space="preserve">
<value>Tasks that are currently being worked on.</value>
</data>
<data name="PresetColumn_Done" xml:space="preserve"> <data name="PresetColumn_Done" xml:space="preserve">
<value>Done</value> <value>Done</value>
</data> </data>
<data name="PresetColumn_Done_Description" xml:space="preserve">
<value>Tasks that have been completed.</value>
</data>
<data name="PresetTag_Bug_Name" xml:space="preserve">
<value>bug</value>
</data>
<data name="PresetTag_Bug_Description" xml:space="preserve">
<value>Something isn't working</value>
</data>
<data name="PresetTag_Documentation_Name" xml:space="preserve">
<value>documentation</value>
</data>
<data name="PresetTag_Documentation_Description" xml:space="preserve">
<value>Improvements or additions to documentation</value>
</data>
<data name="PresetTag_Duplicate_Name" xml:space="preserve">
<value>duplicate</value>
</data>
<data name="PresetTag_Duplicate_Description" xml:space="preserve">
<value>This issue or pull request already exists</value>
</data>
<data name="PresetTag_Enhancement_Name" xml:space="preserve">
<value>enhancement</value>
</data>
<data name="PresetTag_Enhancement_Description" xml:space="preserve">
<value>New feature or request</value>
</data>
<data name="PresetTag_HelpWanted_Name" xml:space="preserve">
<value>help-wanted</value>
</data>
<data name="PresetTag_HelpWanted_Description" xml:space="preserve">
<value>Extra attention is needed</value>
</data>
<data name="PresetTag_Invalid_Name" xml:space="preserve">
<value>invalid</value>
</data>
<data name="PresetTag_Invalid_Description" xml:space="preserve">
<value>This doesn't seem right</value>
</data>
<data name="PresetTag_Question_Name" xml:space="preserve">
<value>question</value>
</data>
<data name="PresetTag_Question_Description" xml:space="preserve">
<value>Further information is requested</value>
</data>
<data name="PresetTag_Wontfix_Name" xml:space="preserve">
<value>wontfix</value>
</data>
<data name="PresetTag_Wontfix_Description" xml:space="preserve">
<value>This will not be worked on</value>
</data>
<data name="Export_FileNamePattern" xml:space="preserve"> <data name="Export_FileNamePattern" xml:space="preserve">
<value>{0}-export-{1:yyyyMMdd-HHmmss}.md</value> <value>{0}-export-{1:yyyyMMdd-HHmmss}.md</value>
</data> </data>
@@ -166,4 +439,10 @@
<data name="Export_TagsTableHeader" xml:space="preserve"> <data name="Export_TagsTableHeader" xml:space="preserve">
<value>| Name | Color | Description | Usage |</value> <value>| Name | Color | Description | Usage |</value>
</data> </data>
<data name="Export_Done_Title" xml:space="preserve">
<value>Export Complete</value>
</data>
<data name="Export_Done_Message" xml:space="preserve">
<value>Exported to: {0}</value>
</data>
</root> </root>
@@ -25,6 +25,12 @@
<data name="Common_Cancel" xml:space="preserve"> <data name="Common_Cancel" xml:space="preserve">
<value>取消</value> <value>取消</value>
</data> </data>
<data name="Common_Delete" xml:space="preserve">
<value>删除</value>
</data>
<data name="Common_Edit" xml:space="preserve">
<value>编辑</value>
</data>
<data name="Main_Export" xml:space="preserve"> <data name="Main_Export" xml:space="preserve">
<value>导出</value> <value>导出</value>
</data> </data>
@@ -40,6 +46,216 @@
<data name="Tab_Board" xml:space="preserve"> <data name="Tab_Board" xml:space="preserve">
<value>看板</value> <value>看板</value>
</data> </data>
<data name="Board_SearchPlaceholder" xml:space="preserve">
<value>搜索…</value>
</data>
<data name="Board_Search" xml:space="preserve">
<value>搜索</value>
</data>
<data name="Board_ClearSearch" xml:space="preserve">
<value>清空</value>
</data>
<data name="Board_AddColumn" xml:space="preserve">
<value>新增列</value>
</data>
<data name="Board_ColumnWidth" xml:space="preserve">
<value>列宽</value>
</data>
<data name="Board_SortCard" xml:space="preserve">
<value>卡片排序</value>
</data>
<data name="Board_SortColumn" xml:space="preserve">
<value>列排序</value>
</data>
<data name="Board_Display" xml:space="preserve">
<value>显示</value>
</data>
<data name="Board_NoColumns" xml:space="preserve">
<value>还没有列。</value>
</data>
<data name="Board_FilterActive" xml:space="preserve">
<value>看板处于过滤状态</value>
</data>
<data name="Board_FilterInactive" xml:space="preserve">
<value>看板未处于过滤状态</value>
</data>
<data name="Search_Error_Title" xml:space="preserve">
<value>搜索表达式有误</value>
</data>
<data name="Search_Error_Message" xml:space="preserve">
<value>查询表达式有误,详情:{0}</value>
</data>
<data name="Sort_IdAsc" xml:space="preserve">
<value>ID 正序</value>
</data>
<data name="Sort_IdDesc" xml:space="preserve">
<value>ID 倒序</value>
</data>
<data name="Sort_CreatedAsc" xml:space="preserve">
<value>创建时间正序</value>
</data>
<data name="Sort_CreatedDesc" xml:space="preserve">
<value>创建时间倒序</value>
</data>
<data name="Sort_UpdatedAsc" xml:space="preserve">
<value>修改时间正序</value>
</data>
<data name="Sort_UpdatedDesc" xml:space="preserve">
<value>修改时间倒序</value>
</data>
<data name="Sort_TitleAsc" xml:space="preserve">
<value>标题正序</value>
</data>
<data name="Sort_TitleDesc" xml:space="preserve">
<value>标题倒序</value>
</data>
<data name="Column_AddCard" xml:space="preserve">
<value>新建卡片</value>
</data>
<data name="Column_Edit" xml:space="preserve">
<value>编辑</value>
</data>
<data name="Column_Delete" xml:space="preserve">
<value>删除</value>
</data>
<data name="Card_Delete" xml:space="preserve">
<value>删除</value>
</data>
<data name="Card_Move" xml:space="preserve">
<value>移动到列…</value>
</data>
<data name="ColumnDialog_AddTitle" xml:space="preserve">
<value>新增列</value>
</data>
<data name="ColumnDialog_EditTitle" xml:space="preserve">
<value>编辑列</value>
</data>
<data name="ColumnDialog_Title" xml:space="preserve">
<value>标题</value>
</data>
<data name="ColumnDialog_Description" xml:space="preserve">
<value>描述</value>
</data>
<data name="ColumnDialog_InvalidTitle" xml:space="preserve">
<value>标题为空或已被使用。</value>
</data>
<data name="CardDialog_AddTitle" xml:space="preserve">
<value>新增卡片</value>
</data>
<data name="CardDialog_EditTitle" xml:space="preserve">
<value>编辑卡片</value>
</data>
<data name="CardDialog_Title" xml:space="preserve">
<value>标题</value>
</data>
<data name="CardDialog_Content" xml:space="preserve">
<value>内容</value>
</data>
<data name="CardDialog_Tags" xml:space="preserve">
<value>标签</value>
</data>
<data name="CardDialog_AddTag" xml:space="preserve">
<value>添加标签</value>
</data>
<data name="CardDialog_Id" xml:space="preserve">
<value>编号:{0}</value>
</data>
<data name="CardDialog_Created" xml:space="preserve">
<value>创建:{0}</value>
</data>
<data name="CardDialog_Modified" xml:space="preserve">
<value>修改:{0}</value>
</data>
<data name="CardDialog_TimePattern" xml:space="preserve">
<value>yyyy年M月d日 HH:mm</value>
</data>
<data name="CardDialog_Error" xml:space="preserve">
<value>无法保存卡片。</value>
</data>
<data name="TagDialog_Title" xml:space="preserve">
<value>添加标签</value>
</data>
<data name="TagDialog_Target" xml:space="preserve">
<value>标签</value>
</data>
<data name="TagDialog_NoTargets" xml:space="preserve">
<value>没有可添加的标签。</value>
</data>
<data name="Tags_AddTag" xml:space="preserve">
<value>添加标签</value>
</data>
<data name="Tags_Empty" xml:space="preserve">
<value>还没有标签。</value>
</data>
<data name="Tags_Usage" xml:space="preserve">
<value>{0} 张卡片</value>
</data>
<data name="TagEditor_AddTitle" xml:space="preserve">
<value>新建标签</value>
</data>
<data name="TagEditor_EditTitle" xml:space="preserve">
<value>编辑标签</value>
</data>
<data name="TagEditor_Name" xml:space="preserve">
<value>名称</value>
</data>
<data name="TagEditor_Color" xml:space="preserve">
<value>颜色</value>
</data>
<data name="TagEditor_Description" xml:space="preserve">
<value>描述</value>
</data>
<data name="TagEditor_InvalidName" xml:space="preserve">
<value>名称为空或已被使用。</value>
</data>
<data name="DeleteTag_Confirm_Title" xml:space="preserve">
<value>删除标签</value>
</data>
<data name="DeleteTag_Confirm_Message" xml:space="preserve">
<value>删除标签“{0}”?将从 {1} 张卡片中移除。</value>
</data>
<data name="MoveDialog_Title" xml:space="preserve">
<value>移动卡片</value>
</data>
<data name="MoveDialog_Target" xml:space="preserve">
<value>目标列</value>
</data>
<data name="MoveDialog_NoTargets" xml:space="preserve">
<value>没有可移动到的目标列。</value>
</data>
<data name="WidthPreset_Narrow" xml:space="preserve">
<value>窄</value>
</data>
<data name="WidthPreset_Standard" xml:space="preserve">
<value>标准</value>
</data>
<data name="WidthPreset_Wide" xml:space="preserve">
<value>宽</value>
</data>
<data name="WidthPreset_Custom" xml:space="preserve">
<value>自定义</value>
</data>
<data name="WidthDialog_Pixels" xml:space="preserve">
<value>像素(160–720)</value>
</data>
<data name="Confirm_DeleteColumn_Title" xml:space="preserve">
<value>删除列</value>
</data>
<data name="Confirm_DeleteColumn_Message" xml:space="preserve">
<value>删除列“{0}”及其 {1} 张卡片?</value>
</data>
<data name="Confirm_DeleteCard_Title" xml:space="preserve">
<value>删除卡片</value>
</data>
<data name="Confirm_DeleteCard_Message" xml:space="preserve">
<value>删除卡片 #{0}?</value>
</data>
<data name="Confirm_Discard_Title" xml:space="preserve">
<value>放弃修改</value>
</data>
<data name="Confirm_Discard_Message" xml:space="preserve">
<value>放弃未保存的修改?</value>
</data>
<data name="Error_Argument_Title" xml:space="preserve"> <data name="Error_Argument_Title" xml:space="preserve">
<value>参数错误</value> <value>参数错误</value>
</data> </data>
@@ -130,12 +346,69 @@
<data name="PresetColumn_Todo" xml:space="preserve"> <data name="PresetColumn_Todo" xml:space="preserve">
<value>待办</value> <value>待办</value>
</data> </data>
<data name="PresetColumn_Todo_Description" xml:space="preserve">
<value>已计划但尚未开始的任务。</value>
</data>
<data name="PresetColumn_InProgress" xml:space="preserve"> <data name="PresetColumn_InProgress" xml:space="preserve">
<value>进行中</value> <value>进行中</value>
</data> </data>
<data name="PresetColumn_InProgress_Description" xml:space="preserve">
<value>正在处理中的任务。</value>
</data>
<data name="PresetColumn_Done" xml:space="preserve"> <data name="PresetColumn_Done" xml:space="preserve">
<value>已完成</value> <value>已完成</value>
</data> </data>
<data name="PresetColumn_Done_Description" xml:space="preserve">
<value>已完成的任务。</value>
</data>
<data name="PresetTag_Bug_Name" xml:space="preserve">
<value>缺陷</value>
</data>
<data name="PresetTag_Bug_Description" xml:space="preserve">
<value>功能没有正常工作</value>
</data>
<data name="PresetTag_Documentation_Name" xml:space="preserve">
<value>文档</value>
</data>
<data name="PresetTag_Documentation_Description" xml:space="preserve">
<value>文档的改进或补充</value>
</data>
<data name="PresetTag_Duplicate_Name" xml:space="preserve">
<value>重复</value>
</data>
<data name="PresetTag_Duplicate_Description" xml:space="preserve">
<value>该问题或请求已存在</value>
</data>
<data name="PresetTag_Enhancement_Name" xml:space="preserve">
<value>增强</value>
</data>
<data name="PresetTag_Enhancement_Description" xml:space="preserve">
<value>新功能或请求</value>
</data>
<data name="PresetTag_HelpWanted_Name" xml:space="preserve">
<value>需要帮助</value>
</data>
<data name="PresetTag_HelpWanted_Description" xml:space="preserve">
<value>需要额外关注</value>
</data>
<data name="PresetTag_Invalid_Name" xml:space="preserve">
<value>无效</value>
</data>
<data name="PresetTag_Invalid_Description" xml:space="preserve">
<value>似乎不正确</value>
</data>
<data name="PresetTag_Question_Name" xml:space="preserve">
<value>疑问</value>
</data>
<data name="PresetTag_Question_Description" xml:space="preserve">
<value>需要进一步信息</value>
</data>
<data name="PresetTag_Wontfix_Name" xml:space="preserve">
<value>不予处理</value>
</data>
<data name="PresetTag_Wontfix_Description" xml:space="preserve">
<value>不会被处理</value>
</data>
<data name="Export_FileNamePattern" xml:space="preserve"> <data name="Export_FileNamePattern" xml:space="preserve">
<value>{0}-导出-{1:yyyyMMdd-HHmmss}.md</value> <value>{0}-导出-{1:yyyyMMdd-HHmmss}.md</value>
</data> </data>
@@ -166,4 +439,10 @@
<data name="Export_TagsTableHeader" xml:space="preserve"> <data name="Export_TagsTableHeader" xml:space="preserve">
<value>| 名称 | 颜色 | 描述 | 使用数 |</value> <value>| 名称 | 颜色 | 描述 | 使用数 |</value>
</data> </data>
<data name="Export_Done_Title" xml:space="preserve">
<value>导出完成</value>
</data>
<data name="Export_Done_Message" xml:space="preserve">
<value>已导出到:{0}</value>
</data>
</root> </root>
+12 -22
View File
@@ -1,5 +1,6 @@
using System.Globalization; using System.Globalization;
using System.Text; using System.Text;
using YKanBan.Models; using YKanBan.Models;
namespace YKanBan.Export; namespace YKanBan.Export;
@@ -11,8 +12,7 @@ namespace YKanBan.Export;
/// timestamps use the shared minute-precision pattern. The output is meant for /// timestamps use the shared minute-precision pattern. The output is meant for
/// reading only — there is no re-import. /// reading only — there is no re-import.
/// </summary> /// </summary>
public static class MarkdownExporter public static class MarkdownExporter {
{
/// <summary> /// <summary>
/// Renders the whole board to Markdown. /// Renders the whole board to Markdown.
/// </summary> /// </summary>
@@ -27,8 +27,7 @@ public static class MarkdownExporter
IReadOnlyList<ColumnModel> columns, IReadOnlyList<ColumnModel> columns,
IReadOnlyList<CardModel> cards, IReadOnlyList<CardModel> cards,
IReadOnlyList<(TagModel Tag, long UsageCount)> tags, IReadOnlyList<(TagModel Tag, long UsageCount)> tags,
DateTimeOffset exportedAt) DateTimeOffset exportedAt) {
{
CultureInfo culture = Resources.Culture ?? CultureInfo.CurrentUICulture; CultureInfo culture = Resources.Culture ?? CultureInfo.CurrentUICulture;
var builder = new StringBuilder(); var builder = new StringBuilder();
@@ -40,18 +39,15 @@ public static class MarkdownExporter
builder.AppendLine(); builder.AppendLine();
// Board body: every column in id order, empty ones included. // Board body: every column in id order, empty ones included.
foreach (ColumnModel column in columns) foreach (ColumnModel column in columns) {
{
IReadOnlyList<CardModel> cardsInColumn = cards.Where(card => card.ColumnId == column.Id).ToArray(); IReadOnlyList<CardModel> cardsInColumn = cards.Where(card => card.ColumnId == column.Id).ToArray();
builder.AppendLine(string.Format(culture, Resources.Export_ColumnHeading, column.Title, cardsInColumn.Count)); builder.AppendLine(string.Format(culture, Resources.Export_ColumnHeading, column.Title, cardsInColumn.Count));
if (column.Description.Length > 0) if (column.Description.Length > 0) {
{
builder.AppendLine(SingleLine(column.Description)); builder.AppendLine(SingleLine(column.Description));
} }
builder.AppendLine(); builder.AppendLine();
foreach (CardModel card in cardsInColumn) foreach (CardModel card in cardsInColumn) {
{
AppendCard(builder, card, culture); AppendCard(builder, card, culture);
} }
} }
@@ -67,8 +63,7 @@ public static class MarkdownExporter
/// <param name="workspaceName">Workspace display name.</param> /// <param name="workspaceName">Workspace display name.</param>
/// <param name="exportedAt">Export moment.</param> /// <param name="exportedAt">Export moment.</param>
/// <returns>The file name.</returns> /// <returns>The file name.</returns>
public static string BuildFileName(string workspaceName, DateTimeOffset exportedAt) public static string BuildFileName(string workspaceName, DateTimeOffset exportedAt) {
{
CultureInfo culture = Resources.Culture ?? CultureInfo.CurrentUICulture; CultureInfo culture = Resources.Culture ?? CultureInfo.CurrentUICulture;
return string.Format(culture, Resources.Export_FileNamePattern, workspaceName, exportedAt); return string.Format(culture, Resources.Export_FileNamePattern, workspaceName, exportedAt);
} }
@@ -79,20 +74,17 @@ public static class MarkdownExporter
/// <param name="builder">The output builder.</param> /// <param name="builder">The output builder.</param>
/// <param name="card">The card to render.</param> /// <param name="card">The card to render.</param>
/// <param name="culture">The UI culture.</param> /// <param name="culture">The UI culture.</param>
private static void AppendCard(StringBuilder builder, CardModel card, CultureInfo culture) private static void AppendCard(StringBuilder builder, CardModel card, CultureInfo culture) {
{
// Heading: "#id title"; an untitled card shows only the id. // Heading: "#id title"; an untitled card shows only the id.
builder.AppendLine(card.Title.Length == 0 builder.AppendLine(card.Title.Length == 0
? $"### #{card.Id}" ? $"### #{card.Id}"
: $"### #{card.Id} {SingleLine(card.Title)}"); : $"### #{card.Id} {SingleLine(card.Title)}");
if (card.Content.Length > 0) if (card.Content.Length > 0) {
{
builder.AppendLine(card.Content); builder.AppendLine(card.Content);
} }
if (card.Tags.Count > 0) if (card.Tags.Count > 0) {
{
string names = string.Join(" ", card.Tags.Select(tag => $"`{tag.Name}`")); string names = string.Join(" ", card.Tags.Select(tag => $"`{tag.Name}`"));
builder.AppendLine(string.Format(culture, Resources.Export_TagsLine, names)); builder.AppendLine(string.Format(culture, Resources.Export_TagsLine, names));
} }
@@ -112,13 +104,11 @@ public static class MarkdownExporter
private static void AppendTagTable( private static void AppendTagTable(
StringBuilder builder, StringBuilder builder,
IReadOnlyList<(TagModel Tag, long UsageCount)> tags, IReadOnlyList<(TagModel Tag, long UsageCount)> tags,
CultureInfo culture) CultureInfo culture) {
{
builder.AppendLine(Resources.Export_TagsSummaryHeading); builder.AppendLine(Resources.Export_TagsSummaryHeading);
builder.AppendLine(Resources.Export_TagsTableHeader); builder.AppendLine(Resources.Export_TagsTableHeader);
builder.AppendLine("|---|---|---|---|"); builder.AppendLine("|---|---|---|---|");
foreach ((TagModel tag, long usage) in tags) foreach ((TagModel tag, long usage) in tags) {
{
// '|' and line breaks would break the table row; neutralize them. // '|' and line breaks would break the table row; neutralize them.
builder.AppendLine($"| {Cell(tag.Name)} | {tag.Color} | {Cell(tag.Description)} | {usage} |"); builder.AppendLine($"| {Cell(tag.Name)} | {tag.Color} | {Cell(tag.Description)} | {usage} |");
} }
+3 -6
View File
@@ -8,8 +8,7 @@ namespace YKanBan.Launching;
/// more than one argument, or a blank argument is rejected as an argument /// more than one argument, or a blank argument is rejected as an argument
/// error. The path itself is not checked for existence here. /// error. The path itself is not checked for existence here.
/// </summary> /// </summary>
public static class LaunchArguments public static class LaunchArguments {
{
/// <summary> /// <summary>
/// Tries to parse command-line arguments following the /// Tries to parse command-line arguments following the
/// <c>ykanban &lt;path&gt;</c> contract. /// <c>ykanban &lt;path&gt;</c> contract.
@@ -17,10 +16,8 @@ public static class LaunchArguments
/// <param name="arguments">The raw arguments, excluding the executable name.</param> /// <param name="arguments">The raw arguments, excluding the executable name.</param>
/// <param name="folderPath">The parsed workspace path on success, otherwise <see langword="null"/>.</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> /// <returns><see langword="true"/> when exactly one non-blank path was supplied.</returns>
public static bool TryParse(IReadOnlyList<string> arguments, [NotNullWhen(true)] out string? folderPath) public static bool TryParse(IReadOnlyList<string> arguments, [NotNullWhen(true)] out string? folderPath) {
{ if (arguments.Count == 1 && !string.IsNullOrWhiteSpace(arguments[0])) {
if (arguments.Count == 1 && !string.IsNullOrWhiteSpace(arguments[0]))
{
folderPath = arguments[0]; folderPath = arguments[0];
return true; return true;
} }
+7 -14
View File
@@ -10,8 +10,7 @@ namespace YKanBan.Models;
/// always produces the canonical lowercase form (for example "#ff0a00"). It is /// always produces the canonical lowercase form (for example "#ff0a00"). It is
/// not specific to tags and may be reused anywhere a color value is needed. /// not specific to tags and may be reused anywhere a color value is needed.
/// </summary> /// </summary>
public readonly record struct RgbColor(byte R, byte G, byte B) public readonly record struct RgbColor(byte R, byte G, byte B) {
{
/// <summary> /// <summary>
/// Parses a "#RRGGBB" text with case-insensitive hex digits. /// Parses a "#RRGGBB" text with case-insensitive hex digits.
/// </summary> /// </summary>
@@ -29,17 +28,14 @@ public readonly record struct RgbColor(byte R, byte G, byte B)
/// <param name="text">The text to parse.</param> /// <param name="text">The text to parse.</param>
/// <param name="color">The parsed color on success, otherwise the default value.</param> /// <param name="color">The parsed color on success, otherwise the default value.</param>
/// <returns><see langword="true"/> when the text is exactly #RRGGBB.</returns> /// <returns><see langword="true"/> when the text is exactly #RRGGBB.</returns>
public static bool TryParse(string? text, out RgbColor color) public static bool TryParse(string? text, out RgbColor color) {
{
color = default; color = default;
if (text is not { Length: 7 } || text[0] != '#') if (text is not { Length: 7 } || text[0] != '#') {
{
return false; return false;
} }
// Two hex digits per component: R, G, B. // Two hex digits per component: R, G, B.
if (TryHexPair(text, 1, out byte r) && TryHexPair(text, 3, out byte g) && TryHexPair(text, 5, out byte b)) if (TryHexPair(text, 1, out byte r) && TryHexPair(text, 3, out byte g) && TryHexPair(text, 5, out byte b)) {
{
color = new RgbColor(r, g, b); color = new RgbColor(r, g, b);
return true; return true;
} }
@@ -59,13 +55,11 @@ public readonly record struct RgbColor(byte R, byte G, byte B)
/// <param name="start">Index of the first of the two digits.</param> /// <param name="start">Index of the first of the two digits.</param>
/// <param name="value">The parsed byte value.</param> /// <param name="value">The parsed byte value.</param>
/// <returns><see langword="true"/> when both characters are hex digits.</returns> /// <returns><see langword="true"/> when both characters are hex digits.</returns>
private static bool TryHexPair(string text, int start, out byte value) private static bool TryHexPair(string text, int start, out byte value) {
{
value = 0; value = 0;
int high = HexDigit(text[start]); int high = HexDigit(text[start]);
int low = HexDigit(text[start + 1]); int low = HexDigit(text[start + 1]);
if (high < 0 || low < 0) if (high < 0 || low < 0) {
{
return false; return false;
} }
value = (byte)((high << 4) | low); value = (byte)((high << 4) | low);
@@ -77,8 +71,7 @@ public readonly record struct RgbColor(byte R, byte G, byte B)
/// </summary> /// </summary>
/// <param name="character">The character to convert.</param> /// <param name="character">The character to convert.</param>
/// <returns>The digit value, or -1 for any other character.</returns> /// <returns>The digit value, or -1 for any other character.</returns>
private static int HexDigit(char character) => character switch private static int HexDigit(char character) => character switch {
{
>= '0' and <= '9' => character - '0', >= '0' and <= '9' => character - '0',
>= 'a' and <= 'f' => character - 'a' + 10, >= 'a' and <= 'f' => character - 'a' + 10,
>= 'A' and <= 'F' => character - 'A' + 10, >= 'A' and <= 'F' => character - 'A' + 10,
+2 -4
View File
@@ -2,14 +2,12 @@
namespace YKanBan; namespace YKanBan;
sealed class Program sealed class Program {
{
// Initialization code. Don't use any Avalonia, third-party APIs or any // Initialization code. Don't use any Avalonia, third-party APIs or any
// SynchronizationContext-reliant code before AppMain is called: things aren't initialized // SynchronizationContext-reliant code before AppMain is called: things aren't initialized
// yet and stuff might break. // yet and stuff might break.
[STAThread] [STAThread]
public static void Main(string[] args) public static void Main(string[] args) {
{
BuildAvaloniaApp().StartWithClassicDesktopLifetime(args); BuildAvaloniaApp().StartWithClassicDesktopLifetime(args);
// The lifetime has ended: persist the configuration once, then release services. // The lifetime has ended: persist the configuration once, then release services.
+11 -13
View File
@@ -5,8 +5,7 @@ namespace YKanBan.Search;
/// <summary> /// <summary>
/// Lexical tokens of the search syntax. /// Lexical tokens of the search syntax.
/// </summary> /// </summary>
public abstract record SearchToken public abstract record SearchToken {
{
/// <summary> /// <summary>
/// A bare word; qualifier detection happens later from the text. /// A bare word; qualifier detection happens later from the text.
/// </summary> /// </summary>
@@ -39,14 +38,17 @@ public abstract record SearchToken
/// unterminated phrase is rejected. Any input not covered by the token rules /// unterminated phrase is rejected. Any input not covered by the token rules
/// is rejected rather than silently ignored. /// is rejected rather than silently ignored.
/// </summary> /// </summary>
public static class SearchLexer public static class SearchLexer {
{ /// <summary>
/// <summary>A valid phrase escape sequence: <c>\"</c> or <c>\\</c>.</summary> /// A valid phrase escape sequence: <c>\"</c> or <c>\\</c>.
/// </summary>
private static readonly Parser<char, char> PhraseEscape = private static readonly Parser<char, char> PhraseEscape =
Parser.Try(Parser.String("\\\"").Select(_ => '"')) Parser.Try(Parser.String("\\\"").Select(_ => '"'))
.Or(Parser.String("\\\\").Select(_ => '\\')); .Or(Parser.String("\\\\").Select(_ => '\\'));
/// <summary>One phrase character: an escape or any character except a quote or backslash.</summary> /// <summary>
/// One phrase character: an escape or any character except a quote or backslash.
/// </summary>
private static readonly Parser<char, char> PhraseCharacter = private static readonly Parser<char, char> PhraseCharacter =
PhraseEscape.Or(Parser<char>.Token(character => character != '"' && character != '\\')); PhraseEscape.Or(Parser<char>.Token(character => character != '"' && character != '\\'));
@@ -90,14 +92,10 @@ public static class SearchLexer
/// <param name="input">The raw search text.</param> /// <param name="input">The raw search text.</param>
/// <returns>The token stream.</returns> /// <returns>The token stream.</returns>
/// <exception cref="SearchSyntaxException">The text contains an invalid escape or an unterminated phrase.</exception> /// <exception cref="SearchSyntaxException">The text contains an invalid escape or an unterminated phrase.</exception>
public static IReadOnlyList<SearchToken> Tokenize(string input) public static IReadOnlyList<SearchToken> Tokenize(string input) {
{ try {
try
{
return Lexer.ParseOrThrow(input); return Lexer.ParseOrThrow(input);
} } catch (ParseException exception) {
catch (ParseException exception)
{
throw new SearchSyntaxException(exception.Message, exception); throw new SearchSyntaxException(exception.Message, exception);
} }
} }
+8 -6
View File
@@ -10,8 +10,7 @@ namespace YKanBan.Search;
/// Root of the search query AST. Search keywords are fixed English grammar /// Root of the search query AST. Search keywords are fixed English grammar
/// and are never localized. /// and are never localized.
/// </summary> /// </summary>
public abstract record SearchNode public abstract record SearchNode {
{
/// <summary> /// <summary>
/// Disjunction: matches when any term matches (OR). /// Disjunction: matches when any term matches (OR).
/// </summary> /// </summary>
@@ -59,11 +58,14 @@ public abstract record SearchNode
/// <summary> /// <summary>
/// The card fields a <see cref="SearchNode.FieldText"/> atom can scope to. /// The card fields a <see cref="SearchNode.FieldText"/> atom can scope to.
/// </summary> /// </summary>
public enum SearchField public enum SearchField {
{ /// <summary>
/// <summary>The card title.</summary> /// The card title.
/// </summary>
Title, Title,
/// <summary>The card content body.</summary> /// <summary>
/// The card content body.
/// </summary>
Content, Content,
} }
+34 -42
View File
@@ -1,4 +1,5 @@
using System.Globalization; using System.Globalization;
using Pidgin; using Pidgin;
namespace YKanBan.Search; namespace YKanBan.Search;
@@ -14,9 +15,10 @@ namespace YKanBan.Search;
/// input returns null and means "show everything". Search keywords and /// input returns null and means "show everything". Search keywords and
/// qualifier keys are fixed English grammar and are never localized. /// qualifier keys are fixed English grammar and are never localized.
/// </summary> /// </summary>
public static class SearchQueryParser public static class SearchQueryParser {
{ /// <summary>
/// <summary>The recognized qualifier keys; add new entries here to extend the grammar.</summary> /// The recognized qualifier keys; add new entries here to extend the grammar.
/// </summary>
private static readonly (string Key, QualifierKind Kind)[] QualifierTable = private static readonly (string Key, QualifierKind Kind)[] QualifierTable =
[ [
("tag", QualifierKind.Tag), ("tag", QualifierKind.Tag),
@@ -40,12 +42,16 @@ public static class SearchQueryParser
private static readonly Parser<SearchToken, SearchToken> CloseParen = private static readonly Parser<SearchToken, SearchToken> CloseParen =
Parser<SearchToken>.Token(token => token is SearchToken.CloseParen); Parser<SearchToken>.Token(token => token is SearchToken.CloseParen);
/// <summary>The text of a phrase token.</summary> /// <summary>
/// The text of a phrase token.
/// </summary>
private static readonly Parser<SearchToken, string> PhraseText = private static readonly Parser<SearchToken, string> PhraseText =
Parser<SearchToken>.Token(token => token is SearchToken.Phrase) Parser<SearchToken>.Token(token => token is SearchToken.Phrase)
.Select(token => ((SearchToken.Phrase)token).Text); .Select(token => ((SearchToken.Phrase)token).Text);
/// <summary>The text of a word token, operator keywords excluded (they never start an operand).</summary> /// <summary>
/// The text of a word token, operator keywords excluded (they never start an operand).
/// </summary>
private static readonly Parser<SearchToken, string> NonKeywordWord = private static readonly Parser<SearchToken, string> NonKeywordWord =
Parser<SearchToken>.Token(token => token is SearchToken.Word word && word.Text != "AND" && word.Text != "OR") Parser<SearchToken>.Token(token => token is SearchToken.Word word && word.Text != "AND" && word.Text != "OR")
.Select(token => ((SearchToken.Word)token).Text); .Select(token => ((SearchToken.Word)token).Text);
@@ -90,7 +96,9 @@ public static class SearchQueryParser
private static readonly Parser<SearchToken, SearchNode> Query = private static readonly Parser<SearchToken, SearchNode> Query =
OrExpr.Before(Parser<SearchToken>.End); OrExpr.Before(Parser<SearchToken>.End);
/// <summary>Defers the OrExpr field read to parse time (recursion cycle breaker).</summary> /// <summary>
/// Defers the OrExpr field read to parse time (recursion cycle breaker).
/// </summary>
/// <returns>The OR-expression parser.</returns> /// <returns>The OR-expression parser.</returns>
private static Parser<SearchToken, SearchNode> OrExprDeferred() => OrExpr; private static Parser<SearchToken, SearchNode> OrExprDeferred() => OrExpr;
@@ -102,20 +110,15 @@ public static class SearchQueryParser
/// <param name="text">The raw search text.</param> /// <param name="text">The raw search text.</param>
/// <returns>The parsed query, or <see langword="null"/> for blank input (meaning: show everything).</returns> /// <returns>The parsed query, or <see langword="null"/> for blank input (meaning: show everything).</returns>
/// <exception cref="SearchSyntaxException">The text violates the grammar.</exception> /// <exception cref="SearchSyntaxException">The text violates the grammar.</exception>
public static SearchNode? Parse(string text) public static SearchNode? Parse(string text) {
{ if (string.IsNullOrWhiteSpace(text)) {
if (string.IsNullOrWhiteSpace(text))
{
return null; return null;
} }
try try {
{
List<SearchToken> tokens = SearchLexer.Tokenize(text).ToList(); List<SearchToken> tokens = SearchLexer.Tokenize(text).ToList();
return Query.ParseOrThrow(tokens); return Query.ParseOrThrow(tokens);
} } catch (ParseException exception) {
catch (ParseException exception)
{
throw new SearchSyntaxException(exception.Message, exception); throw new SearchSyntaxException(exception.Message, exception);
} }
} }
@@ -128,21 +131,18 @@ public static class SearchQueryParser
/// </summary> /// </summary>
/// <param name="word">The word token text.</param> /// <param name="word">The word token text.</param>
/// <returns>The parser producing the operand node.</returns> /// <returns>The parser producing the operand node.</returns>
private static Parser<SearchToken, SearchNode> QualifierFrom(string word) private static Parser<SearchToken, SearchNode> QualifierFrom(string word) {
{
int colonIndex = word.IndexOf(':'); int colonIndex = word.IndexOf(':');
// Only a leading run of letters/digits/underscores before ':' can be a qualifier key. // 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 || !IsQualifierKeyCandidate(word.AsSpan(0, colonIndex))) {
{
return Parser<SearchToken>.Return<SearchNode>(new SearchNode.FreeText(word)); return Parser<SearchToken>.Return<SearchNode>(new SearchNode.FreeText(word));
} }
string key = word[..colonIndex]; string key = word[..colonIndex];
string value = word[(colonIndex + 1)..]; string value = word[(colonIndex + 1)..];
if (!TryLookupQualifier(key, out QualifierKind kind)) if (!TryLookupQualifier(key, out QualifierKind kind)) {
{
return Parser<SearchToken>.Fail<SearchNode>($"Unknown qualifier key '{key}'."); return Parser<SearchToken>.Fail<SearchNode>($"Unknown qualifier key '{key}'.");
} }
@@ -169,8 +169,7 @@ public static class SearchQueryParser
/// <param name="kind">The qualifier kind.</param> /// <param name="kind">The qualifier kind.</param>
/// <param name="value">The qualifier value.</param> /// <param name="value">The qualifier value.</param>
/// <returns>The atom node, or <see langword="null"/> for an invalid id value.</returns> /// <returns>The atom node, or <see langword="null"/> for an invalid id value.</returns>
private static SearchNode? AtomFrom(QualifierKind kind, string value) => kind switch private static SearchNode? AtomFrom(QualifierKind kind, string value) => kind switch {
{
QualifierKind.Tag => new SearchNode.TagName(value), QualifierKind.Tag => new SearchNode.TagName(value),
QualifierKind.Title => new SearchNode.FieldText(SearchField.Title, value), QualifierKind.Title => new SearchNode.FieldText(SearchField.Title, value),
QualifierKind.Content => new SearchNode.FieldText(SearchField.Content, value), QualifierKind.Content => new SearchNode.FieldText(SearchField.Content, value),
@@ -186,12 +185,9 @@ public static class SearchQueryParser
/// <param name="key">The key text before the colon.</param> /// <param name="key">The key text before the colon.</param>
/// <param name="kind">The matching qualifier kind.</param> /// <param name="kind">The matching qualifier kind.</param>
/// <returns><see langword="true"/> when the key is known.</returns> /// <returns><see langword="true"/> when the key is known.</returns>
private static bool TryLookupQualifier(string key, out QualifierKind kind) private static bool TryLookupQualifier(string key, out QualifierKind kind) {
{ foreach ((string candidate, QualifierKind candidateKind) in QualifierTable) {
foreach ((string candidate, QualifierKind candidateKind) in QualifierTable) if (string.Equals(candidate, key, StringComparison.Ordinal)) {
{
if (string.Equals(candidate, key, StringComparison.Ordinal))
{
kind = candidateKind; kind = candidateKind;
return true; return true;
} }
@@ -207,12 +203,9 @@ public static class SearchQueryParser
/// </summary> /// </summary>
/// <param name="text">The candidate key text.</param> /// <param name="text">The candidate key text.</param>
/// <returns><see langword="true"/> when every character is a word character.</returns> /// <returns><see langword="true"/> when every character is a word character.</returns>
private static bool IsQualifierKeyCandidate(ReadOnlySpan<char> text) private static bool IsQualifierKeyCandidate(ReadOnlySpan<char> text) {
{ foreach (char character in text) {
foreach (char character in text) if (!(char.IsLetterOrDigit(character) || character == '_')) {
{
if (!(char.IsLetterOrDigit(character) || character == '_'))
{
return false; return false;
} }
} }
@@ -226,8 +219,7 @@ public static class SearchQueryParser
/// <param name="first">The first operand.</param> /// <param name="first">The first operand.</param>
/// <param name="rest">The remaining operands.</param> /// <param name="rest">The remaining operands.</param>
/// <returns>The single operand, or an <see cref="SearchNode.And"/> node.</returns> /// <returns>The single operand, or an <see cref="SearchNode.And"/> node.</returns>
private static SearchNode FoldAnd(SearchNode first, IEnumerable<SearchNode> rest) private static SearchNode FoldAnd(SearchNode first, IEnumerable<SearchNode> rest) {
{
List<SearchNode> terms = [first, .. rest]; List<SearchNode> terms = [first, .. rest];
return terms.Count == 1 ? terms[0] : new SearchNode.And(terms); return terms.Count == 1 ? terms[0] : new SearchNode.And(terms);
} }
@@ -237,17 +229,17 @@ public static class SearchQueryParser
/// </summary> /// </summary>
/// <param name="terms">The operands.</param> /// <param name="terms">The operands.</param>
/// <returns>The single operand, or a <see cref="SearchNode.Or"/> node.</returns> /// <returns>The single operand, or a <see cref="SearchNode.Or"/> node.</returns>
private static SearchNode FoldOr(IEnumerable<SearchNode> terms) private static SearchNode FoldOr(IEnumerable<SearchNode> terms) {
{
List<SearchNode> list = terms.ToList(); List<SearchNode> list = terms.ToList();
return list.Count == 1 ? list[0] : new SearchNode.Or(list); return list.Count == 1 ? list[0] : new SearchNode.Or(list);
} }
#endregion #endregion
/// <summary>The recognized qualifier kinds.</summary> /// <summary>
private enum QualifierKind /// The recognized qualifier kinds.
{ /// </summary>
private enum QualifierKind {
Tag, Tag,
Title, Title,
Content, Content,
+29 -39
View File
@@ -15,15 +15,13 @@ public sealed record CompiledSearch(string Predicate, IReadOnlyList<(string Name
/// wildcards and the escape character in user text are escaped so they match /// wildcards and the escape character in user text are escaped so they match
/// literally. /// literally.
/// </summary> /// </summary>
public static class SearchSqlCompiler public static class SearchSqlCompiler {
{
/// <summary> /// <summary>
/// Compiles the query into a SQL predicate. /// Compiles the query into a SQL predicate.
/// </summary> /// </summary>
/// <param name="query">The parsed search AST.</param> /// <param name="query">The parsed search AST.</param>
/// <returns>The compiled predicate and its parameters.</returns> /// <returns>The compiled predicate and its parameters.</returns>
public static CompiledSearch Compile(SearchNode query) public static CompiledSearch Compile(SearchNode query) {
{
var parameters = new List<(string Name, object Value)>(); var parameters = new List<(string Name, object Value)>();
string predicate = Build(query, parameters); string predicate = Build(query, parameters);
return new CompiledSearch(predicate, parameters); return new CompiledSearch(predicate, parameters);
@@ -35,49 +33,42 @@ public static class SearchSqlCompiler
/// <param name="node">The AST node to compile.</param> /// <param name="node">The AST node to compile.</param>
/// <param name="parameters">The parameter accumulator.</param> /// <param name="parameters">The parameter accumulator.</param>
/// <returns>The SQL boolean expression for the node.</returns> /// <returns>The SQL boolean expression for the node.</returns>
private static string Build(SearchNode node, List<(string Name, object Value)> parameters) private static string Build(SearchNode node, List<(string Name, object Value)> parameters) {
{ switch (node) {
switch (node)
{
case SearchNode.And and: case SearchNode.And and:
return "(" + string.Join(" AND ", and.Terms.Select(term => Build(term, parameters))) + ")"; return "(" + string.Join(" AND ", and.Terms.Select(term => Build(term, parameters))) + ")";
case SearchNode.Or or: case SearchNode.Or or:
return "(" + string.Join(" OR ", or.Terms.Select(term => Build(term, parameters))) + ")"; return "(" + string.Join(" OR ", or.Terms.Select(term => Build(term, parameters))) + ")";
case SearchNode.FreeText freeText: case SearchNode.FreeText freeText: {
{ // A bare word matches a substring of the title OR the content.
// A bare word matches a substring of the title OR the content. string titleParam = AddParameter(parameters, "%" + EscapeLike(freeText.Text) + "%");
string titleParam = AddParameter(parameters, "%" + EscapeLike(freeText.Text) + "%"); string contentParam = AddParameter(parameters, "%" + EscapeLike(freeText.Text) + "%");
string contentParam = AddParameter(parameters, "%" + EscapeLike(freeText.Text) + "%"); return $"(c.title LIKE {titleParam} ESCAPE '\\' OR c.content LIKE {contentParam} ESCAPE '\\')";
return $"(c.title LIKE {titleParam} ESCAPE '\\' OR c.content LIKE {contentParam} ESCAPE '\\')"; }
}
case SearchNode.FieldText field: case SearchNode.FieldText field: {
{ string column = field.Field == SearchField.Title ? "c.title" : "c.content";
string column = field.Field == SearchField.Title ? "c.title" : "c.content"; string param = AddParameter(parameters, "%" + EscapeLike(field.Text) + "%");
string param = AddParameter(parameters, "%" + EscapeLike(field.Text) + "%"); return $"{column} LIKE {param} ESCAPE '\\'";
return $"{column} LIKE {param} ESCAPE '\\'"; }
}
case SearchNode.TagName tag: case SearchNode.TagName tag: {
{ string param = AddParameter(parameters, tag.Name);
string param = AddParameter(parameters, tag.Name); return "EXISTS (SELECT 1 FROM card_tags ct JOIN tags t ON t.id = ct.tag_id " +
return "EXISTS (SELECT 1 FROM card_tags ct JOIN tags t ON t.id = ct.tag_id " + $"WHERE ct.card_id = c.id AND t.name COLLATE NOCASE = {param})";
$"WHERE ct.card_id = c.id AND t.name COLLATE NOCASE = {param})"; }
}
case SearchNode.ColumnTitle column: case SearchNode.ColumnTitle column: {
{ string param = AddParameter(parameters, column.Title);
string param = AddParameter(parameters, column.Title); return $"c.column_id IN (SELECT id FROM columns WHERE title COLLATE NOCASE = {param})";
return $"c.column_id IN (SELECT id FROM columns WHERE title COLLATE NOCASE = {param})"; }
}
case SearchNode.CardId id: case SearchNode.CardId id: {
{ string param = AddParameter(parameters, id.Id);
string param = AddParameter(parameters, id.Id); return $"c.id = {param}";
return $"c.id = {param}"; }
}
default: default:
throw new InvalidOperationException($"Unsupported search node: {node.GetType().Name}"); throw new InvalidOperationException($"Unsupported search node: {node.GetType().Name}");
@@ -90,8 +81,7 @@ public static class SearchSqlCompiler
/// <param name="parameters">The parameter accumulator.</param> /// <param name="parameters">The parameter accumulator.</param>
/// <param name="value">The value to bind.</param> /// <param name="value">The value to bind.</param>
/// <returns>The placeholder text.</returns> /// <returns>The placeholder text.</returns>
private static string AddParameter(List<(string Name, object Value)> parameters, object value) private static string AddParameter(List<(string Name, object Value)> parameters, object value) {
{
string name = "$p" + parameters.Count.ToString(System.Globalization.CultureInfo.InvariantCulture); string name = "$p" + parameters.Count.ToString(System.Globalization.CultureInfo.InvariantCulture);
parameters.Add((name, value)); parameters.Add((name, value));
return name; return name;
+2 -4
View File
@@ -6,15 +6,13 @@ namespace YKanBan.Search;
/// search error instead of coupling to Pidgin types. The message is never /// search error instead of coupling to Pidgin types. The message is never
/// localized. /// localized.
/// </summary> /// </summary>
public sealed class SearchSyntaxException : Exception public sealed class SearchSyntaxException : Exception {
{
/// <summary> /// <summary>
/// Initializes the exception with a descriptive English message. /// Initializes the exception with a descriptive English message.
/// </summary> /// </summary>
/// <param name="message">The English diagnostic message.</param> /// <param name="message">The English diagnostic message.</param>
/// <param name="innerException">The underlying parse failure.</param> /// <param name="innerException">The underlying parse failure.</param>
public SearchSyntaxException(string message, Exception innerException) public SearchSyntaxException(string message, Exception innerException)
: base(message, innerException) : base(message, innerException) {
{
} }
} }
+3 -6
View File
@@ -8,13 +8,11 @@ namespace YKanBan.Services;
/// the single open workspace session. The configuration is persisted once at /// the single open workspace session. The configuration is persisted once at
/// shutdown; the session (lock plus connection) lives until disposal. /// shutdown; the session (lock plus connection) lives until disposal.
/// </summary> /// </summary>
public sealed class AppServices : IDisposable public sealed class AppServices : IDisposable {
{
/// <summary> /// <summary>
/// Loads the configuration and prepares the service graph. /// Loads the configuration and prepares the service graph.
/// </summary> /// </summary>
public AppServices() public AppServices() {
{
ConfigStore = new AppConfigStore(AppDataPaths.AppConfigJsonPath); ConfigStore = new AppConfigStore(AppDataPaths.AppConfigJsonPath);
Config = ConfigStore.Load(); Config = ConfigStore.Load();
} }
@@ -42,8 +40,7 @@ public sealed class AppServices : IDisposable
/// <returns>The open session.</returns> /// <returns>The open session.</returns>
/// <exception cref="YKanBan.Storage.WorkspaceNotInitializedException">The folder has no .ykanban structure.</exception> /// <exception cref="YKanBan.Storage.WorkspaceNotInitializedException">The folder has no .ykanban structure.</exception>
/// <exception cref="YKanBan.Storage.WorkspaceLockException">Another instance already holds the lock.</exception> /// <exception cref="YKanBan.Storage.WorkspaceLockException">Another instance already holds the lock.</exception>
public WorkspaceSession OpenWorkspace(string folderPath) public WorkspaceSession OpenWorkspace(string folderPath) {
{
Session = WorkspaceSession.Open(folderPath); Session = WorkspaceSession.Open(folderPath);
return Session; return Session;
} }
+101 -54
View File
@@ -1,49 +1,88 @@
using System.Runtime.Serialization; using System.Runtime.Serialization;
using Newtonsoft.Json; using Newtonsoft.Json;
namespace YKanBan.Storage.AppData; namespace YKanBan.Storage.AppData;
/// <summary> /// <summary>
/// Card ordering options. Every order falls back to id ascending as the final /// Display ordering options, used for both cards and columns. Except for the id
/// tie-breaker. /// order, every option falls back to id ascending as the final tie-breaker.
/// </summary> /// </summary>
public enum CardSortOption public enum SortOption {
{ /// <summary>
/// <summary>Primary key ascending (default).</summary> /// Primary key ascending.
[EnumMember(Value = "id")] /// </summary>
Id, [EnumMember(Value = "id-asc")]
IdAscending,
/// <summary>Creation time, oldest first.</summary> /// <summary>
[EnumMember(Value = "created-at")] /// Primary key descending.
CreatedAt, /// </summary>
[EnumMember(Value = "id-desc")]
IdDescending,
/// <summary>Last modification time, most recently modified first.</summary> /// <summary>
[EnumMember(Value = "updated-at")] /// Creation time ascending.
UpdatedAt, /// </summary>
[EnumMember(Value = "created-asc")]
CreatedAscending,
/// <summary>Title by code points (BINARY collation); empty titles sort first.</summary> /// <summary>
[EnumMember(Value = "title")] /// Creation time descending.
Title, /// </summary>
[EnumMember(Value = "created-desc")]
CreatedDescending,
/// <summary>
/// Last modification time ascending.
/// </summary>
[EnumMember(Value = "updated-asc")]
UpdatedAscending,
/// <summary>
/// Last modification time descending.
/// </summary>
[EnumMember(Value = "updated-desc")]
UpdatedDescending,
/// <summary>
/// Title by code points (BINARY collation) ascending.
/// </summary>
[EnumMember(Value = "title-asc")]
TitleAscending,
/// <summary>
/// Title by code points (BINARY collation) descending.
/// </summary>
[EnumMember(Value = "title-desc")]
TitleDescending,
} }
/// <summary> /// <summary>
/// Column width presets. <see cref="Custom"/> uses a user-defined pixel width. /// Column width presets. <see cref="Custom"/> uses a user-defined pixel width.
/// </summary> /// </summary>
public enum ColumnWidthPreset public enum ColumnWidthPreset {
{ /// <summary>
/// <summary>Narrow preset.</summary> /// Narrow preset.
/// </summary>
[EnumMember(Value = "narrow")] [EnumMember(Value = "narrow")]
Narrow, Narrow,
/// <summary>Standard preset (320 px, the default).</summary> /// <summary>
/// Standard preset (320 px, the default).
/// </summary>
[EnumMember(Value = "standard")] [EnumMember(Value = "standard")]
Standard, Standard,
/// <summary>Wide preset.</summary> /// <summary>
/// Wide preset.
/// </summary>
[EnumMember(Value = "wide")] [EnumMember(Value = "wide")]
Wide, Wide,
/// <summary>User-defined pixel width (160–720).</summary> /// <summary>
/// User-defined pixel width (160–720).
/// </summary>
[EnumMember(Value = "custom")] [EnumMember(Value = "custom")]
Custom, Custom,
} }
@@ -51,38 +90,30 @@ public enum ColumnWidthPreset
/// <summary> /// <summary>
/// UI theme selection. /// UI theme selection.
/// </summary> /// </summary>
public enum ThemeOption public enum ThemeOption {
{ /// <summary>
/// <summary>Always light.</summary> /// Always light.
/// </summary>
[EnumMember(Value = "light")] [EnumMember(Value = "light")]
Light, Light,
/// <summary>Always dark.</summary> /// <summary>
/// Always dark.
/// </summary>
[EnumMember(Value = "dark")] [EnumMember(Value = "dark")]
Dark, Dark,
/// <summary>Follow the operating system setting (default).</summary> /// <summary>
/// Follow the operating system setting (default).
/// </summary>
[EnumMember(Value = "follow-system")] [EnumMember(Value = "follow-system")]
FollowSystem, FollowSystem,
} }
/// <summary>
/// Card ordering settings. The chosen order is global, not per workspace.
/// </summary>
public sealed class SortSettings
{
/// <summary>
/// Gets or sets the order used by the board.
/// </summary>
[JsonProperty("card")]
public CardSortOption Card { get; set; } = CardSortOption.Id;
}
/// <summary> /// <summary>
/// Board column width settings, applied globally. /// Board column width settings, applied globally.
/// </summary> /// </summary>
public sealed class ColumnWidthSettings public sealed class ColumnWidthSettings {
{
/// <summary> /// <summary>
/// Gets or sets the active width preset. /// Gets or sets the active width preset.
/// </summary> /// </summary>
@@ -97,11 +128,34 @@ public sealed class ColumnWidthSettings
public int CustomPixels { get; set; } = 320; public int CustomPixels { get; set; } = 320;
} }
/// <summary>
/// Everything that controls how the board is displayed: the column width and
/// the card and column ordering.
/// </summary>
public sealed class DisplaySettings {
/// <summary>
/// Gets or sets the board column width settings.
/// </summary>
[JsonProperty("column-width")]
public ColumnWidthSettings ColumnWidth { get; set; } = new();
/// <summary>
/// Gets or sets the order of cards within their column.
/// </summary>
[JsonProperty("card-sort")]
public SortOption CardSort { get; set; } = SortOption.IdAscending;
/// <summary>
/// Gets or sets the left-to-right order of the columns.
/// </summary>
[JsonProperty("column-sort")]
public SortOption ColumnSort { get; set; } = SortOption.IdAscending;
}
/// <summary> /// <summary>
/// Confirmation-dialog toggles for the destructive actions. /// Confirmation-dialog toggles for the destructive actions.
/// </summary> /// </summary>
public sealed class ConfirmationSettings public sealed class ConfirmationSettings {
{
/// <summary> /// <summary>
/// Gets or sets whether deleting a card asks for confirmation. /// Gets or sets whether deleting a card asks for confirmation.
/// </summary> /// </summary>
@@ -133,8 +187,7 @@ public sealed class ConfirmationSettings
/// <see cref="JsonPropertyAttribute"/> and <see cref="EnumMemberAttribute"/>). /// <see cref="JsonPropertyAttribute"/> and <see cref="EnumMemberAttribute"/>).
/// The <c>version</c> field is the migration hook for future format changes. /// The <c>version</c> field is the migration hook for future format changes.
/// </summary> /// </summary>
public sealed class AppConfig public sealed class AppConfig {
{
/// <summary> /// <summary>
/// Current configuration format version. /// Current configuration format version.
/// </summary> /// </summary>
@@ -164,16 +217,10 @@ public sealed class AppConfig
public ThemeOption Theme { get; set; } = ThemeOption.FollowSystem; public ThemeOption Theme { get; set; } = ThemeOption.FollowSystem;
/// <summary> /// <summary>
/// Gets or sets the card ordering settings. /// Gets or sets the board display settings (width and ordering).
/// </summary> /// </summary>
[JsonProperty("sort")] [JsonProperty("display")]
public SortSettings Sort { get; set; } = new(); public DisplaySettings Display { get; set; } = new();
/// <summary>
/// Gets or sets the board column width settings.
/// </summary>
[JsonProperty("column-width")]
public ColumnWidthSettings ColumnWidth { get; set; } = new();
/// <summary> /// <summary>
/// Gets or sets the confirmation-dialog settings. /// Gets or sets the confirmation-dialog settings.
+10 -21
View File
@@ -9,10 +9,8 @@ namespace YKanBan.Storage.AppData;
/// used. Saving writes the file directly (no atomic replace) — losing the last /// used. Saving writes the file directly (no atomic replace) — losing the last
/// session's settings to a crash is an accepted trade-off. /// session's settings to a crash is an accepted trade-off.
/// </summary> /// </summary>
public sealed class AppConfigStore public sealed class AppConfigStore {
{ private static readonly JsonSerializerSettings SerializerSettings = new() {
private static readonly JsonSerializerSettings SerializerSettings = new()
{
Formatting = Formatting.Indented, Formatting = Formatting.Indented,
NullValueHandling = NullValueHandling.Ignore, NullValueHandling = NullValueHandling.Ignore,
@@ -37,32 +35,25 @@ public sealed class AppConfigStore
/// </summary> /// </summary>
/// <returns>The loaded configuration, or defaults when none could be read.</returns> /// <returns>The loaded configuration, or defaults when none could be read.</returns>
/// <exception cref="IOException">The file exists but cannot be read.</exception> /// <exception cref="IOException">The file exists but cannot be read.</exception>
public AppConfig Load() public AppConfig Load() {
{
// Missing file is a normal first-run state: run with defaults. // Missing file is a normal first-run state: run with defaults.
if (!File.Exists(FilePath)) if (!File.Exists(FilePath)) {
{
return new AppConfig(); return new AppConfig();
} }
string json = File.ReadAllText(FilePath); string json = File.ReadAllText(FilePath);
try try {
{
// A JSON null literal deserializes to null; treat it like defaults. // A JSON null literal deserializes to null; treat it like defaults.
AppConfig? config = JsonConvert.DeserializeObject<AppConfig>(json, SerializerSettings); AppConfig? config = JsonConvert.DeserializeObject<AppConfig>(json, SerializerSettings);
if (config is null) if (config is null) {
{
return new AppConfig(); return new AppConfig();
} }
// Older or hand-edited files may miss whole sections; each falls back to its defaults. // Older or hand-edited files may miss whole sections; each falls back to its defaults.
config.Sort ??= new SortSettings(); config.Display ??= new DisplaySettings();
config.ColumnWidth ??= new ColumnWidthSettings();
config.Confirmations ??= new ConfirmationSettings(); config.Confirmations ??= new ConfirmationSettings();
return config; return config;
} } catch (JsonException) {
catch (JsonException)
{
// Corrupt: keep a copy for inspection, then continue with defaults. // Corrupt: keep a copy for inspection, then continue with defaults.
File.Copy(FilePath, FilePath + ".bak", overwrite: true); File.Copy(FilePath, FilePath + ".bak", overwrite: true);
return new AppConfig(); return new AppConfig();
@@ -73,12 +64,10 @@ public sealed class AppConfigStore
/// Writes the configuration directly to disk (no atomic replace). /// Writes the configuration directly to disk (no atomic replace).
/// </summary> /// </summary>
/// <param name="config">The configuration to serialize.</param> /// <param name="config">The configuration to serialize.</param>
public void Save(AppConfig config) public void Save(AppConfig config) {
{
// Create the parent folder on demand; normally it already exists. // Create the parent folder on demand; normally it already exists.
string? directory = Path.GetDirectoryName(FilePath); string? directory = Path.GetDirectoryName(FilePath);
if (!string.IsNullOrEmpty(directory)) if (!string.IsNullOrEmpty(directory)) {
{
Directory.CreateDirectory(directory); Directory.CreateDirectory(directory);
} }
+1 -2
View File
@@ -5,8 +5,7 @@ namespace YKanBan.Storage.AppData;
/// (%APPDATA%/YKanBan on Windows and the equivalent directory on other /// (%APPDATA%/YKanBan on Windows and the equivalent directory on other
/// platforms). /// platforms).
/// </summary> /// </summary>
public static class AppDataPaths public static class AppDataPaths {
{
/// <summary> /// <summary>
/// Gets the per-user YKanBan application data folder. /// Gets the per-user YKanBan application data folder.
/// </summary> /// </summary>
+14 -29
View File
@@ -7,8 +7,7 @@ namespace YKanBan.Storage;
/// the mandated PRAGMA configuration (WAL journal, NORMAL synchronous mode, /// the mandated PRAGMA configuration (WAL journal, NORMAL synchronous mode,
/// foreign keys on) and applies incremental <c>user_version</c> migrations. /// foreign keys on) and applies incremental <c>user_version</c> migrations.
/// </summary> /// </summary>
public static class SqliteDatabase public static class SqliteDatabase {
{
/// <summary> /// <summary>
/// Opens (creating if needed) a database file, applies the mandatory /// Opens (creating if needed) a database file, applies the mandatory
/// PRAGMAs and runs any pending migrations. /// PRAGMAs and runs any pending migrations.
@@ -16,10 +15,8 @@ public static class SqliteDatabase
/// <param name="databasePath">Path of the SQLite database file.</param> /// <param name="databasePath">Path of the SQLite database file.</param>
/// <param name="migrations">Contiguous migration list ordered by version, starting at 1.</param> /// <param name="migrations">Contiguous migration list ordered by version, starting at 1.</param>
/// <returns>An open connection with all PRAGMAs applied and the schema migrated.</returns> /// <returns>An open connection with all PRAGMAs applied and the schema migrated.</returns>
public static SqliteConnection Open(string databasePath, IReadOnlyList<SchemaMigration> migrations) public static SqliteConnection Open(string databasePath, IReadOnlyList<SchemaMigration> migrations) {
{ var connection = new SqliteConnection(new SqliteConnectionStringBuilder {
var connection = new SqliteConnection(new SqliteConnectionStringBuilder
{
DataSource = databasePath, DataSource = databasePath,
Mode = SqliteOpenMode.ReadWriteCreate, Mode = SqliteOpenMode.ReadWriteCreate,
@@ -28,14 +25,11 @@ public static class SqliteDatabase
}.ToString()); }.ToString());
connection.Open(); connection.Open();
try try {
{
ApplyPragmas(connection); ApplyPragmas(connection);
ApplyMigrations(connection, migrations); ApplyMigrations(connection, migrations);
return connection; return connection;
} } catch {
catch
{
connection.Dispose(); connection.Dispose();
throw; throw;
} }
@@ -46,8 +40,7 @@ public static class SqliteDatabase
/// </summary> /// </summary>
/// <param name="connection">An open database connection.</param> /// <param name="connection">An open database connection.</param>
/// <returns>The stored schema version.</returns> /// <returns>The stored schema version.</returns>
public static long ReadUserVersion(SqliteConnection connection) public static long ReadUserVersion(SqliteConnection connection) {
{
using var command = connection.CreateCommand(); using var command = connection.CreateCommand();
command.CommandText = "PRAGMA user_version;"; command.CommandText = "PRAGMA user_version;";
return (long)command.ExecuteScalar()!; return (long)command.ExecuteScalar()!;
@@ -59,8 +52,7 @@ public static class SqliteDatabase
/// enabled on every connection or the DDL cascades never fire. /// enabled on every connection or the DDL cascades never fire.
/// </summary> /// </summary>
/// <param name="connection">An open database connection.</param> /// <param name="connection">An open database connection.</param>
internal static void ApplyPragmas(SqliteConnection connection) internal static void ApplyPragmas(SqliteConnection connection) {
{
// WAL plus NORMAL synchronous is the chosen durability/performance trade-off. // WAL plus NORMAL synchronous is the chosen durability/performance trade-off.
Execute(connection, "PRAGMA journal_mode=WAL;"); Execute(connection, "PRAGMA journal_mode=WAL;");
Execute(connection, "PRAGMA synchronous=NORMAL;"); Execute(connection, "PRAGMA synchronous=NORMAL;");
@@ -75,13 +67,10 @@ public static class SqliteDatabase
/// <param name="migrations">Contiguous migration list ordered by version, starting at 1.</param> /// <param name="migrations">Contiguous migration list ordered by version, starting at 1.</param>
/// <exception cref="ArgumentException">The migration list is not contiguous from version 1.</exception> /// <exception cref="ArgumentException">The migration list is not contiguous from version 1.</exception>
/// <exception cref="SchemaVersionException">The database was written by a newer build.</exception> /// <exception cref="SchemaVersionException">The database was written by a newer build.</exception>
internal static void ApplyMigrations(SqliteConnection connection, IReadOnlyList<SchemaMigration> migrations) internal static void ApplyMigrations(SqliteConnection connection, IReadOnlyList<SchemaMigration> migrations) {
{
// Contract check: the list must be ordered, contiguous and start at version 1. // Contract check: the list must be ordered, contiguous and start at version 1.
for (int index = 0; index < migrations.Count; index++) for (int index = 0; index < migrations.Count; index++) {
{ if (migrations[index].Version != index + 1) {
if (migrations[index].Version != index + 1)
{
throw new ArgumentException("Migrations must be contiguous and start at version 1.", nameof(migrations)); throw new ArgumentException("Migrations must be contiguous and start at version 1.", nameof(migrations));
} }
} }
@@ -90,16 +79,13 @@ public static class SqliteDatabase
int latest = migrations.Count; int latest = migrations.Count;
// A database written by a newer build cannot be managed by this one; refuse loudly. // A database written by a newer build cannot be managed by this one; refuse loudly.
if (current > latest) if (current > latest) {
{
throw new SchemaVersionException(current, latest); throw new SchemaVersionException(current, latest);
} }
// Apply each pending migration atomically so a crash never leaves a half-migrated database. // Apply each pending migration atomically so a crash never leaves a half-migrated database.
foreach (SchemaMigration migration in migrations) foreach (SchemaMigration migration in migrations) {
{ if (migration.Version <= current) {
if (migration.Version <= current)
{
continue; continue;
} }
@@ -116,8 +102,7 @@ public static class SqliteDatabase
/// <param name="connection">An open database connection.</param> /// <param name="connection">An open database connection.</param>
/// <param name="commandText">The SQL script to execute.</param> /// <param name="commandText">The SQL script to execute.</param>
/// <param name="transaction">The transaction to enlist in, when any.</param> /// <param name="transaction">The transaction to enlist in, when any.</param>
private static void Execute(SqliteConnection connection, string commandText, SqliteTransaction? transaction = null) private static void Execute(SqliteConnection connection, string commandText, SqliteTransaction? transaction = null) {
{
using var command = connection.CreateCommand(); using var command = connection.CreateCommand();
command.Transaction = transaction; command.Transaction = transaction;
command.CommandText = commandText; command.CommandText = commandText;
+11 -45
View File
@@ -5,24 +5,21 @@ namespace YKanBan.Storage;
/// Exception messages are always English and never localized; the UI maps the /// Exception messages are always English and never localized; the UI maps the
/// exception type to a localized resource key instead. /// exception type to a localized resource key instead.
/// </summary> /// </summary>
public abstract class YKanBanException : Exception public abstract class YKanBanException : Exception {
{
/// <summary> /// <summary>
/// Initializes the exception with an English diagnostic message. /// Initializes the exception with an English diagnostic message.
/// </summary> /// </summary>
/// <param name="message">The English diagnostic message.</param> /// <param name="message">The English diagnostic message.</param>
/// <param name="innerException">The underlying cause, when any.</param> /// <param name="innerException">The underlying cause, when any.</param>
protected YKanBanException(string message, Exception? innerException = null) protected YKanBanException(string message, Exception? innerException = null)
: base(message, innerException) : base(message, innerException) {
{
} }
} }
/// <summary> /// <summary>
/// Signals that the folder passed on the command line does not exist on disk. /// Signals that the folder passed on the command line does not exist on disk.
/// </summary> /// </summary>
public sealed class WorkspaceDirectoryMissingException : YKanBanException public sealed class WorkspaceDirectoryMissingException : YKanBanException {
{
/// <summary> /// <summary>
/// Gets the folder path that was expected to exist. /// Gets the folder path that was expected to exist.
/// </summary> /// </summary>
@@ -33,8 +30,7 @@ public sealed class WorkspaceDirectoryMissingException : YKanBanException
/// </summary> /// </summary>
/// <param name="folderPath">The missing folder path.</param> /// <param name="folderPath">The missing folder path.</param>
public WorkspaceDirectoryMissingException(string folderPath) public WorkspaceDirectoryMissingException(string folderPath)
: base($"The folder does not exist: {folderPath}") : base($"The folder does not exist: {folderPath}") {
{
FolderPath = folderPath; FolderPath = folderPath;
} }
} }
@@ -43,8 +39,7 @@ public sealed class WorkspaceDirectoryMissingException : YKanBanException
/// Signals that a folder exists but has no .ykanban structure, so it is not /// Signals that a folder exists but has no .ykanban structure, so it is not
/// (yet) a workspace. /// (yet) a workspace.
/// </summary> /// </summary>
public sealed class WorkspaceNotInitializedException : YKanBanException public sealed class WorkspaceNotInitializedException : YKanBanException {
{
/// <summary> /// <summary>
/// Gets the folder path that lacks the .ykanban structure. /// Gets the folder path that lacks the .ykanban structure.
/// </summary> /// </summary>
@@ -55,8 +50,7 @@ public sealed class WorkspaceNotInitializedException : YKanBanException
/// </summary> /// </summary>
/// <param name="folderPath">The uninitialized folder path.</param> /// <param name="folderPath">The uninitialized folder path.</param>
public WorkspaceNotInitializedException(string folderPath) public WorkspaceNotInitializedException(string folderPath)
: base($"The folder is not a YKanBan workspace (missing .ykanban): {folderPath}") : base($"The folder is not a YKanBan workspace (missing .ykanban): {folderPath}") {
{
FolderPath = folderPath; FolderPath = folderPath;
} }
} }
@@ -65,46 +59,20 @@ public sealed class WorkspaceNotInitializedException : YKanBanException
/// Signals that another instance already holds the workspace lock, so this /// Signals that another instance already holds the workspace lock, so this
/// process must not touch the workspace. /// process must not touch the workspace.
/// </summary> /// </summary>
public sealed class WorkspaceLockException : YKanBanException public sealed class WorkspaceLockException : YKanBanException {
{
/// <summary> /// <summary>
/// Gets the lock file that could not be acquired. /// Gets the lock file that could not be acquired.
/// </summary> /// </summary>
public string LockFilePath { get; } public string LockFilePath { get; }
/// <summary>
/// Gets the best-effort holder diagnostics read from the lock file, or
/// <see langword="null"/> when they could not be read.
/// </summary>
public string? HolderDiagnostics { get; }
/// <summary> /// <summary>
/// Initializes the exception for a failed lock acquisition. /// Initializes the exception for a failed lock acquisition.
/// </summary> /// </summary>
/// <param name="lockFilePath">The lock file that is already held.</param> /// <param name="lockFilePath">The lock file that is already held.</param>
/// <param name="holderDiagnostics">Diagnostics of the current holder, when readable.</param>
/// <param name="innerException">The underlying I/O error.</param> /// <param name="innerException">The underlying I/O error.</param>
public WorkspaceLockException(string lockFilePath, string? holderDiagnostics, Exception innerException) public WorkspaceLockException(string lockFilePath, Exception innerException)
: base(BuildMessage(lockFilePath, holderDiagnostics), innerException) : base($"The workspace is locked by another instance: {lockFilePath}", innerException) {
{
LockFilePath = lockFilePath; LockFilePath = lockFilePath;
HolderDiagnostics = holderDiagnostics;
}
/// <summary>
/// Composes the diagnostic message, appending holder details when they were readable.
/// </summary>
/// <param name="lockFilePath">The lock file that is already held.</param>
/// <param name="holderDiagnostics">Diagnostics of the current holder, when readable.</param>
/// <returns>The English diagnostic message.</returns>
private static string BuildMessage(string lockFilePath, string? holderDiagnostics)
{
string message = $"The workspace is locked by another instance: {lockFilePath}";
if (!string.IsNullOrEmpty(holderDiagnostics))
{
message += $" Lock holder: {holderDiagnostics}";
}
return message;
} }
} }
@@ -112,8 +80,7 @@ public sealed class WorkspaceLockException : YKanBanException
/// Signals that the database was written by a newer build than the one /// Signals that the database was written by a newer build than the one
/// currently running, so its schema cannot be safely managed. /// currently running, so its schema cannot be safely managed.
/// </summary> /// </summary>
public sealed class SchemaVersionException : YKanBanException public sealed class SchemaVersionException : YKanBanException {
{
/// <summary> /// <summary>
/// Gets the user_version value found in the database. /// Gets the user_version value found in the database.
/// </summary> /// </summary>
@@ -130,8 +97,7 @@ public sealed class SchemaVersionException : YKanBanException
/// <param name="storedVersion">The user_version read from the database.</param> /// <param name="storedVersion">The user_version read from the database.</param>
/// <param name="supportedVersion">The newest schema version this build supports.</param> /// <param name="supportedVersion">The newest schema version this build supports.</param>
public SchemaVersionException(long storedVersion, int supportedVersion) public SchemaVersionException(long storedVersion, int supportedVersion)
: base($"Database schema version {storedVersion} is newer than the latest supported version {supportedVersion}.") : base($"Database schema version {storedVersion} is newer than the latest supported version {supportedVersion}.") {
{
StoredVersion = storedVersion; StoredVersion = storedVersion;
SupportedVersion = supportedVersion; SupportedVersion = supportedVersion;
} }
+1 -2
View File
@@ -4,8 +4,7 @@ namespace YKanBan.Storage;
/// Supplies the current Unix timestamp. Every timestamp persisted by YKanBan /// Supplies the current Unix timestamp. Every timestamp persisted by YKanBan
/// is an INTEGER count of Unix seconds. /// is an INTEGER count of Unix seconds.
/// </summary> /// </summary>
public static class UnixTime public static class UnixTime {
{
/// <summary> /// <summary>
/// Gets the current UTC time expressed as Unix seconds. /// Gets the current UTC time expressed as Unix seconds.
/// </summary> /// </summary>
@@ -8,8 +8,7 @@ namespace YKanBan.Storage.Workspace;
/// separate concern handled by <see cref="WorkspacePreset"/>, so the /// separate concern handled by <see cref="WorkspacePreset"/>, so the
/// database can be created without any rows. /// database can be created without any rows.
/// </summary> /// </summary>
public static class WorkspaceInitializer public static class WorkspaceInitializer {
{
/// <summary> /// <summary>
/// Returns whether the folder contains a .ykanban structure. Only the /// Returns whether the folder contains a .ykanban structure. Only the
/// passed folder is checked; parent folders are never searched. /// passed folder is checked; parent folders are never searched.
@@ -25,16 +24,13 @@ public static class WorkspaceInitializer
/// <param name="folderPath">The existing folder to initialize.</param> /// <param name="folderPath">The existing folder to initialize.</param>
/// <exception cref="WorkspaceDirectoryMissingException">The folder does not exist on disk.</exception> /// <exception cref="WorkspaceDirectoryMissingException">The folder does not exist on disk.</exception>
/// <exception cref="InvalidOperationException">The workspace database already exists.</exception> /// <exception cref="InvalidOperationException">The workspace database already exists.</exception>
public static void Initialize(string folderPath) public static void Initialize(string folderPath) {
{ if (!Directory.Exists(folderPath)) {
if (!Directory.Exists(folderPath))
{
throw new WorkspaceDirectoryMissingException(folderPath); throw new WorkspaceDirectoryMissingException(folderPath);
} }
string databasePath = WorkspacePaths.Database(folderPath); string databasePath = WorkspacePaths.Database(folderPath);
if (File.Exists(databasePath)) if (File.Exists(databasePath)) {
{
throw new InvalidOperationException($"The workspace database already exists: {databasePath}"); throw new InvalidOperationException($"The workspace database already exists: {databasePath}");
} }
+14 -49
View File
@@ -1,14 +1,11 @@
using System.Text;
namespace YKanBan.Storage.Workspace; namespace YKanBan.Storage.Workspace;
/// <summary> /// <summary>
/// Exclusive, OS-enforced lock over a workspace's ykanban.lock. The handle is /// Exclusive, OS-enforced lock over a workspace's ykanban.lock. The handle is
/// held until disposal, so crashes and power loss release it automatically. /// held until disposal, so crashes and power loss release it automatically. The
/// The lock file also carries PID / machine name / time for human diagnostics. /// lock file is kept empty; only its exclusive OS handle carries meaning.
/// </summary> /// </summary>
public sealed class WorkspaceLock : IDisposable public sealed class WorkspaceLock : IDisposable {
{
private readonly FileStream _stream; private readonly FileStream _stream;
/// <summary> /// <summary>
@@ -16,8 +13,7 @@ public sealed class WorkspaceLock : IDisposable
/// </summary> /// </summary>
/// <param name="stream">The exclusively opened lock file stream.</param> /// <param name="stream">The exclusively opened lock file stream.</param>
/// <param name="lockFilePath">Path of the lock file being held.</param> /// <param name="lockFilePath">Path of the lock file being held.</param>
private WorkspaceLock(FileStream stream, string lockFilePath) private WorkspaceLock(FileStream stream, string lockFilePath) {
{
_stream = stream; _stream = stream;
LockFilePath = lockFilePath; LockFilePath = lockFilePath;
} }
@@ -28,61 +24,30 @@ public sealed class WorkspaceLock : IDisposable
public string LockFilePath { get; } public string LockFilePath { get; }
/// <summary> /// <summary>
/// Acquires the workspace lock, writing this process's diagnostics into it. /// Acquires the workspace lock, leaving the lock file empty.
/// </summary> /// </summary>
/// <param name="folderPath">The workspace folder to lock.</param> /// <param name="folderPath">The workspace folder to lock.</param>
/// <returns>The held lock; dispose it to release.</returns> /// <returns>The held lock; dispose it to release.</returns>
/// <exception cref="WorkspaceNotInitializedException">The folder has no .ykanban structure.</exception> /// <exception cref="WorkspaceNotInitializedException">The folder has no .ykanban structure.</exception>
/// <exception cref="WorkspaceLockException">Another instance already holds the lock.</exception> /// <exception cref="WorkspaceLockException">Another instance already holds the lock.</exception>
public static WorkspaceLock Acquire(string folderPath) public static WorkspaceLock Acquire(string folderPath) {
{
string lockFilePath = WorkspacePaths.LockFile(folderPath); string lockFilePath = WorkspacePaths.LockFile(folderPath);
FileStream stream; FileStream stream;
try try {
{ // FileShare.None gives the exclusive semantics; FileMode.Create empties any stale file.
// FileShare.None gives the exclusive semantics; FileMode.Create truncates stale content. // SAFETY: FileMode.Create truncates a pre-existing file, but the lock
// file is empty by design and the path always comes from
// WorkspacePaths.LockFile, so no user data is ever affected.
stream = new FileStream(lockFilePath, FileMode.Create, FileAccess.Write, FileShare.None); stream = new FileStream(lockFilePath, FileMode.Create, FileAccess.Write, FileShare.None);
} } catch (DirectoryNotFoundException) {
catch (DirectoryNotFoundException)
{
throw new WorkspaceNotInitializedException(folderPath); throw new WorkspaceNotInitializedException(folderPath);
} } catch (IOException ex) {
catch (IOException ex) throw new WorkspaceLockException(lockFilePath, ex);
{
throw new WorkspaceLockException(lockFilePath, ReadDiagnosticsBestEffort(lockFilePath), ex);
} }
// Write holder diagnostics so humans can identify the owning instance from the file alone.
string diagnostics = $"pid={Environment.ProcessId};machine={Environment.MachineName};time={DateTimeOffset.UtcNow:O}";
byte[] payload = Encoding.UTF8.GetBytes(diagnostics);
stream.Write(payload, 0, payload.Length);
stream.Flush();
return new WorkspaceLock(stream, lockFilePath); return new WorkspaceLock(stream, lockFilePath);
} }
/// <summary>
/// Attempts to read holder diagnostics from a lock file we failed to
/// acquire. The read is best-effort: a live FileShare.None holder makes the
/// file unreadable, in which case <see langword="null"/> is returned.
/// </summary>
/// <param name="lockFilePath">The lock file to read.</param>
/// <returns>The diagnostics text, or <see langword="null"/> when unreadable.</returns>
private static string? ReadDiagnosticsBestEffort(string lockFilePath)
{
try
{
return File.ReadAllText(lockFilePath);
}
catch (IOException)
{
return null;
}
catch (UnauthorizedAccessException)
{
return null;
}
}
/// <summary> /// <summary>
/// Releases the exclusive handle. The lock file itself is intentionally /// Releases the exclusive handle. The lock file itself is intentionally
/// left on disk; the OS releases the handle even on a crash. /// left on disk; the OS releases the handle even on a crash.
+1 -2
View File
@@ -4,8 +4,7 @@ namespace YKanBan.Storage.Workspace;
/// Well-known file and folder names inside a workspace's .ykanban structure, /// Well-known file and folder names inside a workspace's .ykanban structure,
/// plus helpers that combine them with a workspace folder path. /// plus helpers that combine them with a workspace folder path.
/// </summary> /// </summary>
public static class WorkspacePaths public static class WorkspacePaths {
{
/// <summary> /// <summary>
/// Name of the workspace root folder created inside a managed project. /// Name of the workspace root folder created inside a managed project.
/// </summary> /// </summary>
+54 -17
View File
@@ -3,48 +3,85 @@ using Microsoft.Data.Sqlite;
namespace YKanBan.Storage.Workspace; namespace YKanBan.Storage.Workspace;
/// <summary> /// <summary>
/// Adds the initial workspace content. The three preset column titles are read /// Adds the initial workspace content. The preset column titles/descriptions and
/// straight from the ResX resources in the UI language active when they are /// tag names/descriptions are read straight from the ResX resources in the UI
/// added; they then become ordinary data that no longer follows language /// language active when they are added; they then become ordinary data that no
/// switches. /// longer follows language switches.
/// </summary> /// </summary>
public static class WorkspacePreset public static class WorkspacePreset {
{
/// <summary> /// <summary>
/// Inserts the three preset columns (the current language's equivalents of /// Inserts the three preset columns (the current language's equivalents of
/// To Do / In Progress / Done) in a single transaction. /// To Do / In Progress / Done) with their descriptions in a single transaction.
/// </summary> /// </summary>
/// <param name="folderPath">The initialized workspace folder.</param> /// <param name="folderPath">The initialized workspace folder.</param>
/// <exception cref="SqliteException">The workspace database does not exist or a title collides with an existing column.</exception> /// <exception cref="SqliteException">The workspace database does not exist or a title collides with an existing column.</exception>
public static void AddPresetColumns(string folderPath) public static void AddPresetColumns(string folderPath) {
{
using SqliteConnection connection = SqliteDatabase.Open( using SqliteConnection connection = SqliteDatabase.Open(
WorkspacePaths.Database(folderPath), WorkspaceSchema.Migrations); WorkspacePaths.Database(folderPath), WorkspaceSchema.Migrations);
long now = UnixTime.Now; long now = UnixTime.Now;
// Preset titles are data at creation time: whatever the current language says gets stored. // Preset titles and descriptions are data at creation time: whatever the current language says gets stored.
string[] titles = (string Title, string Description)[] columns =
[ [
Resources.PresetColumn_Todo, (Resources.PresetColumn_Todo, Resources.PresetColumn_Todo_Description),
Resources.PresetColumn_InProgress, (Resources.PresetColumn_InProgress, Resources.PresetColumn_InProgress_Description),
Resources.PresetColumn_Done, (Resources.PresetColumn_Done, Resources.PresetColumn_Done_Description),
]; ];
// Insert all three atomically so a partially populated workspace can never exist. // Insert all three atomically so a partially populated workspace can never exist.
using var transaction = connection.BeginTransaction(); using var transaction = connection.BeginTransaction();
foreach (string title in titles) foreach ((string title, string description) in columns) {
{
using var command = connection.CreateCommand(); using var command = connection.CreateCommand();
command.Transaction = transaction; command.Transaction = transaction;
command.CommandText = """ command.CommandText = """
INSERT INTO columns (title, description, created_at, updated_at) INSERT INTO columns (title, description, created_at, updated_at)
VALUES ($title, '', $now, $now); VALUES ($title, $description, $now, $now);
"""; """;
command.Parameters.AddWithValue("$title", title); command.Parameters.AddWithValue("$title", title);
command.Parameters.AddWithValue("$description", description);
command.Parameters.AddWithValue("$now", now); command.Parameters.AddWithValue("$now", now);
command.ExecuteNonQuery(); command.ExecuteNonQuery();
} }
transaction.Commit(); transaction.Commit();
} }
/// <summary>
/// Inserts the preset tag set (names, colors and descriptions in the current
/// language) in a single transaction.
/// </summary>
/// <param name="folderPath">The initialized workspace folder.</param>
/// <exception cref="SqliteException">The workspace database does not exist or a tag name collides.</exception>
public static void AddPresetTags(string folderPath) {
using SqliteConnection connection = SqliteDatabase.Open(
WorkspacePaths.Database(folderPath), WorkspaceSchema.Migrations);
// Colors are stored in the canonical lowercase #rrggbb form.
(string Name, string Color, string Description)[] tags =
[
(Resources.PresetTag_Bug_Name, "#d73a4a", Resources.PresetTag_Bug_Description),
(Resources.PresetTag_Documentation_Name, "#0075ca", Resources.PresetTag_Documentation_Description),
(Resources.PresetTag_Duplicate_Name, "#cfd3d7", Resources.PresetTag_Duplicate_Description),
(Resources.PresetTag_Enhancement_Name, "#a2eeef", Resources.PresetTag_Enhancement_Description),
(Resources.PresetTag_HelpWanted_Name, "#008672", Resources.PresetTag_HelpWanted_Description),
(Resources.PresetTag_Invalid_Name, "#e4e669", Resources.PresetTag_Invalid_Description),
(Resources.PresetTag_Question_Name, "#d876e3", Resources.PresetTag_Question_Description),
(Resources.PresetTag_Wontfix_Name, "#ffffff", Resources.PresetTag_Wontfix_Description),
];
using var transaction = connection.BeginTransaction();
foreach ((string name, string color, string description) in tags) {
using var command = connection.CreateCommand();
command.Transaction = transaction;
command.CommandText = """
INSERT INTO tags (name, color, description)
VALUES ($name, $color, $description);
""";
command.Parameters.AddWithValue("$name", name);
command.Parameters.AddWithValue("$color", color);
command.Parameters.AddWithValue("$description", description);
command.ExecuteNonQuery();
}
transaction.Commit();
}
} }
@@ -1,5 +1,7 @@
using Microsoft.Data.Sqlite; using Microsoft.Data.Sqlite;
using YKanBan.Models; using YKanBan.Models;
using YKanBan.Search;
namespace YKanBan.Storage.Workspace; namespace YKanBan.Storage.Workspace;
@@ -13,16 +15,14 @@ namespace YKanBan.Storage.Workspace;
/// - columns.updated_at refreshes only when title or description changes; /// - columns.updated_at refreshes only when title or description changes;
/// - a confirmation with no effective change performs no write at all. /// - a confirmation with no effective change performs no write at all.
/// </summary> /// </summary>
public sealed class WorkspaceRepository : IDisposable public sealed class WorkspaceRepository : IDisposable {
{
private readonly SqliteConnection _connection; private readonly SqliteConnection _connection;
/// <summary> /// <summary>
/// Opens the repository over an initialized workspace database. /// Opens the repository over an initialized workspace database.
/// </summary> /// </summary>
/// <param name="folderPath">The workspace folder.</param> /// <param name="folderPath">The workspace folder.</param>
public WorkspaceRepository(string folderPath) public WorkspaceRepository(string folderPath) {
{
_connection = SqliteDatabase.Open(WorkspacePaths.Database(folderPath), WorkspaceSchema.Migrations); _connection = SqliteDatabase.Open(WorkspacePaths.Database(folderPath), WorkspaceSchema.Migrations);
} }
@@ -37,15 +37,13 @@ public sealed class WorkspaceRepository : IDisposable
/// Returns all columns ordered by id ascending. /// Returns all columns ordered by id ascending.
/// </summary> /// </summary>
/// <returns>All columns in id order.</returns> /// <returns>All columns in id order.</returns>
public IReadOnlyList<ColumnModel> GetColumns() public IReadOnlyList<ColumnModel> GetColumns() {
{
using var command = CreateCommand( using var command = CreateCommand(
"SELECT id, title, description, created_at, updated_at FROM columns ORDER BY id ASC;"); "SELECT id, title, description, created_at, updated_at FROM columns ORDER BY id ASC;");
using var reader = command.ExecuteReader(); using var reader = command.ExecuteReader();
var columns = new List<ColumnModel>(); var columns = new List<ColumnModel>();
while (reader.Read()) while (reader.Read()) {
{
columns.Add(ReadColumn(reader)); columns.Add(ReadColumn(reader));
} }
return columns; return columns;
@@ -56,8 +54,7 @@ public sealed class WorkspaceRepository : IDisposable
/// </summary> /// </summary>
/// <param name="columnId">The column id.</param> /// <param name="columnId">The column id.</param>
/// <returns>The column, or <see langword="null"/> when it does not exist.</returns> /// <returns>The column, or <see langword="null"/> when it does not exist.</returns>
public ColumnModel? GetColumn(long columnId) public ColumnModel? GetColumn(long columnId) {
{
using var command = CreateCommand( using var command = CreateCommand(
"SELECT id, title, description, created_at, updated_at FROM columns WHERE id = $id;"); "SELECT id, title, description, created_at, updated_at FROM columns WHERE id = $id;");
command.Parameters.AddWithValue("$id", columnId); command.Parameters.AddWithValue("$id", columnId);
@@ -72,8 +69,7 @@ public sealed class WorkspaceRepository : IDisposable
/// <param name="description">The optional description.</param> /// <param name="description">The optional description.</param>
/// <returns>The created column.</returns> /// <returns>The created column.</returns>
/// <exception cref="SqliteException">The title is empty or not unique.</exception> /// <exception cref="SqliteException">The title is empty or not unique.</exception>
public ColumnModel AddColumn(string title, string description) public ColumnModel AddColumn(string title, string description) {
{
long now = UnixTime.Now; long now = UnixTime.Now;
using var transaction = _connection.BeginTransaction(); using var transaction = _connection.BeginTransaction();
long id = ExecuteInsert(transaction, long id = ExecuteInsert(transaction,
@@ -94,14 +90,12 @@ public sealed class WorkspaceRepository : IDisposable
/// <returns>The updated column, or the unchanged one for a no-op.</returns> /// <returns>The updated column, or the unchanged one for a no-op.</returns>
/// <exception cref="InvalidOperationException">The column does not exist.</exception> /// <exception cref="InvalidOperationException">The column does not exist.</exception>
/// <exception cref="SqliteException">The new title is empty or not unique.</exception> /// <exception cref="SqliteException">The new title is empty or not unique.</exception>
public ColumnModel UpdateColumn(long columnId, string title, string description) public ColumnModel UpdateColumn(long columnId, string title, string description) {
{
ColumnModel existing = GetColumn(columnId) ColumnModel existing = GetColumn(columnId)
?? throw new InvalidOperationException($"Column {columnId} does not exist."); ?? throw new InvalidOperationException($"Column {columnId} does not exist.");
// Unchanged title and description: no write, no timestamp refresh. // Unchanged title and description: no write, no timestamp refresh.
if (existing.Title == title && existing.Description == description) if (existing.Title == title && existing.Description == description) {
{
return existing; return existing;
} }
@@ -132,8 +126,7 @@ public sealed class WorkspaceRepository : IDisposable
/// Returns all cards with their assigned tags loaded, ordered by id ascending. /// Returns all cards with their assigned tags loaded, ordered by id ascending.
/// </summary> /// </summary>
/// <returns>All cards in id order.</returns> /// <returns>All cards in id order.</returns>
public IReadOnlyList<CardModel> GetCards() public IReadOnlyList<CardModel> GetCards() {
{
using var command = CreateCommand(""" using var command = CreateCommand("""
SELECT c.id, c.column_id, c.title, c.content, c.created_at, c.updated_at, SELECT c.id, c.column_id, c.title, c.content, c.created_at, c.updated_at,
t.id, t.name, t.color, t.description t.id, t.name, t.color, t.description
@@ -147,11 +140,9 @@ public sealed class WorkspaceRepository : IDisposable
// Single grouped pass: one output card per distinct card id, with its tags accumulated alongside. // Single grouped pass: one output card per distinct card id, with its tags accumulated alongside.
var cards = new List<CardModel>(); var cards = new List<CardModel>();
var tagsByCard = new Dictionary<long, List<TagModel>>(); var tagsByCard = new Dictionary<long, List<TagModel>>();
while (reader.Read()) while (reader.Read()) {
{
long cardId = reader.GetInt64(0); long cardId = reader.GetInt64(0);
if (!tagsByCard.TryGetValue(cardId, out List<TagModel>? tags)) if (!tagsByCard.TryGetValue(cardId, out List<TagModel>? tags)) {
{
tags = new List<TagModel>(); tags = new List<TagModel>();
tagsByCard[cardId] = tags; tagsByCard[cardId] = tags;
cards.Add(new CardModel( cards.Add(new CardModel(
@@ -164,21 +155,38 @@ public sealed class WorkspaceRepository : IDisposable
tags)); tags));
} }
if (!reader.IsDBNull(6)) if (!reader.IsDBNull(6)) {
{
tags.Add(ReadTag(reader, 6)); tags.Add(ReadTag(reader, 6));
} }
} }
return cards; return cards;
} }
/// <summary>
/// Returns the ids of the cards matching a compiled search predicate.
/// </summary>
/// <param name="search">The compiled search predicate and its parameters.</param>
/// <returns>The matching card ids.</returns>
public IReadOnlyCollection<long> GetCardIdsMatching(CompiledSearch search) {
using var command = CreateCommand($"SELECT c.id FROM cards c WHERE {search.Predicate};");
foreach ((string name, object value) in search.Parameters) {
command.Parameters.AddWithValue(name, value);
}
using var reader = command.ExecuteReader();
var ids = new HashSet<long>();
while (reader.Read()) {
ids.Add(reader.GetInt64(0));
}
return ids;
}
/// <summary> /// <summary>
/// Returns the card with the given id, with its tags loaded. /// Returns the card with the given id, with its tags loaded.
/// </summary> /// </summary>
/// <param name="cardId">The card id.</param> /// <param name="cardId">The card id.</param>
/// <returns>The card, or <see langword="null"/> when it does not exist.</returns> /// <returns>The card, or <see langword="null"/> when it does not exist.</returns>
public CardModel? GetCard(long cardId) public CardModel? GetCard(long cardId) {
{
using var command = CreateCommand(""" using var command = CreateCommand("""
SELECT c.id, c.column_id, c.title, c.content, c.created_at, c.updated_at, SELECT c.id, c.column_id, c.title, c.content, c.created_at, c.updated_at,
t.id, t.name, t.color, t.description t.id, t.name, t.color, t.description
@@ -194,8 +202,7 @@ public sealed class WorkspaceRepository : IDisposable
// The LEFT JOIN may repeat the card row once per tag; build it on the first row only. // The LEFT JOIN may repeat the card row once per tag; build it on the first row only.
CardModel? card = null; CardModel? card = null;
var tags = new List<TagModel>(); var tags = new List<TagModel>();
while (reader.Read()) while (reader.Read()) {
{
card ??= new CardModel( card ??= new CardModel(
reader.GetInt64(0), reader.GetInt64(0),
reader.GetInt64(1), reader.GetInt64(1),
@@ -205,8 +212,7 @@ public sealed class WorkspaceRepository : IDisposable
reader.GetInt64(5), reader.GetInt64(5),
tags); tags);
if (!reader.IsDBNull(6)) if (!reader.IsDBNull(6)) {
{
tags.Add(ReadTag(reader, 6)); tags.Add(ReadTag(reader, 6));
} }
} }
@@ -222,15 +228,13 @@ public sealed class WorkspaceRepository : IDisposable
/// <param name="tagIds">The tags to assign initially.</param> /// <param name="tagIds">The tags to assign initially.</param>
/// <returns>The created card with tags loaded.</returns> /// <returns>The created card with tags loaded.</returns>
/// <exception cref="SqliteException">The column or a tag id does not exist.</exception> /// <exception cref="SqliteException">The column or a tag id does not exist.</exception>
public CardModel AddCard(long columnId, string title, string content, IReadOnlyCollection<long> tagIds) public CardModel AddCard(long columnId, string title, string content, IReadOnlyCollection<long> tagIds) {
{
long now = UnixTime.Now; long now = UnixTime.Now;
using var transaction = _connection.BeginTransaction(); using var transaction = _connection.BeginTransaction();
long id = ExecuteInsert(transaction, long id = ExecuteInsert(transaction,
"INSERT INTO cards (column_id, title, content, created_at, updated_at) VALUES ($columnId, $title, $content, $now, $now);", "INSERT INTO cards (column_id, title, content, created_at, updated_at) VALUES ($columnId, $title, $content, $now, $now);",
("$columnId", columnId), ("$title", title), ("$content", content), ("$now", now)); ("$columnId", columnId), ("$title", title), ("$content", content), ("$now", now));
foreach (long tagId in tagIds.Distinct()) foreach (long tagId in tagIds.Distinct()) {
{
ExecuteNonQuery(transaction, ExecuteNonQuery(transaction,
"INSERT INTO card_tags (card_id, tag_id) VALUES ($cardId, $tagId);", "INSERT INTO card_tags (card_id, tag_id) VALUES ($cardId, $tagId);",
("$cardId", id), ("$tagId", tagId)); ("$cardId", id), ("$tagId", tagId));
@@ -253,15 +257,13 @@ public sealed class WorkspaceRepository : IDisposable
/// <returns>The updated card with tags loaded, or the unchanged one for a no-op.</returns> /// <returns>The updated card with tags loaded, or the unchanged one for a no-op.</returns>
/// <exception cref="InvalidOperationException">The card does not exist.</exception> /// <exception cref="InvalidOperationException">The card does not exist.</exception>
/// <exception cref="SqliteException">A tag id does not exist; nothing is written.</exception> /// <exception cref="SqliteException">A tag id does not exist; nothing is written.</exception>
public CardModel UpdateCard(long cardId, string title, string content, IReadOnlyCollection<long> tagIds) public CardModel UpdateCard(long cardId, string title, string content, IReadOnlyCollection<long> tagIds) {
{
CardModel existing = GetCard(cardId) CardModel existing = GetCard(cardId)
?? throw new InvalidOperationException($"Card {cardId} does not exist."); ?? throw new InvalidOperationException($"Card {cardId} does not exist.");
// No effective change in title, content or tag set: no write, no timestamp refresh. // No effective change in title, content or tag set: no write, no timestamp refresh.
bool tagsChanged = !tagIds.Distinct().ToHashSet().SetEquals(existing.Tags.Select(tag => tag.Id)); bool tagsChanged = !tagIds.Distinct().ToHashSet().SetEquals(existing.Tags.Select(tag => tag.Id));
if (existing.Title == title && existing.Content == content && !tagsChanged) if (existing.Title == title && existing.Content == content && !tagsChanged) {
{
return existing; return existing;
} }
@@ -274,8 +276,7 @@ public sealed class WorkspaceRepository : IDisposable
// Tag assignment is rewritten wholesale; card_tags carries nothing beyond the pair. // Tag assignment is rewritten wholesale; card_tags carries nothing beyond the pair.
ExecuteNonQuery(transaction, "DELETE FROM card_tags WHERE card_id = $id;", ("$id", cardId)); ExecuteNonQuery(transaction, "DELETE FROM card_tags WHERE card_id = $id;", ("$id", cardId));
foreach (long tagId in tagIds.Distinct()) foreach (long tagId in tagIds.Distinct()) {
{
ExecuteNonQuery(transaction, ExecuteNonQuery(transaction,
"INSERT INTO card_tags (card_id, tag_id) VALUES ($cardId, $tagId);", "INSERT INTO card_tags (card_id, tag_id) VALUES ($cardId, $tagId);",
("$cardId", cardId), ("$tagId", tagId)); ("$cardId", cardId), ("$tagId", tagId));
@@ -293,8 +294,7 @@ public sealed class WorkspaceRepository : IDisposable
/// <param name="cardId">The card to move.</param> /// <param name="cardId">The card to move.</param>
/// <param name="targetColumnId">The destination column.</param> /// <param name="targetColumnId">The destination column.</param>
/// <returns><see langword="true"/> when the card actually moved.</returns> /// <returns><see langword="true"/> when the card actually moved.</returns>
public bool MoveCard(long cardId, long targetColumnId) public bool MoveCard(long cardId, long targetColumnId) {
{
using var command = CreateCommand( using var command = CreateCommand(
"UPDATE cards SET column_id = $columnId WHERE id = $id AND column_id <> $columnId;"); "UPDATE cards SET column_id = $columnId WHERE id = $id AND column_id <> $columnId;");
command.Parameters.AddWithValue("$columnId", targetColumnId); command.Parameters.AddWithValue("$columnId", targetColumnId);
@@ -317,15 +317,13 @@ public sealed class WorkspaceRepository : IDisposable
/// Returns all tags ordered by id ascending; unreferenced tags are included. /// Returns all tags ordered by id ascending; unreferenced tags are included.
/// </summary> /// </summary>
/// <returns>All tags in id order.</returns> /// <returns>All tags in id order.</returns>
public IReadOnlyList<TagModel> GetTags() public IReadOnlyList<TagModel> GetTags() {
{
using var command = CreateCommand( using var command = CreateCommand(
"SELECT id, name, color, description FROM tags ORDER BY id ASC;"); "SELECT id, name, color, description FROM tags ORDER BY id ASC;");
using var reader = command.ExecuteReader(); using var reader = command.ExecuteReader();
var tags = new List<TagModel>(); var tags = new List<TagModel>();
while (reader.Read()) while (reader.Read()) {
{
tags.Add(ReadTag(reader, 0)); tags.Add(ReadTag(reader, 0));
} }
return tags; return tags;
@@ -335,8 +333,7 @@ public sealed class WorkspaceRepository : IDisposable
/// Returns every tag together with the number of cards using it, ordered by tag id. /// Returns every tag together with the number of cards using it, ordered by tag id.
/// </summary> /// </summary>
/// <returns>The tag/usage pairs in tag id order.</returns> /// <returns>The tag/usage pairs in tag id order.</returns>
public IReadOnlyList<(TagModel Tag, long UsageCount)> GetTagsWithUsage() public IReadOnlyList<(TagModel Tag, long UsageCount)> GetTagsWithUsage() {
{
using var command = CreateCommand(""" using var command = CreateCommand("""
SELECT t.id, t.name, t.color, t.description, COUNT(ct.card_id) SELECT t.id, t.name, t.color, t.description, COUNT(ct.card_id)
FROM tags t FROM tags t
@@ -347,8 +344,7 @@ public sealed class WorkspaceRepository : IDisposable
using var reader = command.ExecuteReader(); using var reader = command.ExecuteReader();
var tags = new List<(TagModel Tag, long UsageCount)>(); var tags = new List<(TagModel Tag, long UsageCount)>();
while (reader.Read()) while (reader.Read()) {
{
tags.Add((ReadTag(reader, 0), reader.GetInt64(4))); tags.Add((ReadTag(reader, 0), reader.GetInt64(4)));
} }
return tags; return tags;
@@ -362,8 +358,7 @@ public sealed class WorkspaceRepository : IDisposable
/// <param name="description">The optional description.</param> /// <param name="description">The optional description.</param>
/// <returns>The created tag.</returns> /// <returns>The created tag.</returns>
/// <exception cref="SqliteException">The name is empty or not unique.</exception> /// <exception cref="SqliteException">The name is empty or not unique.</exception>
public TagModel AddTag(string name, RgbColor color, string description) public TagModel AddTag(string name, RgbColor color, string description) {
{
using var transaction = _connection.BeginTransaction(); using var transaction = _connection.BeginTransaction();
long id = ExecuteInsert(transaction, long id = ExecuteInsert(transaction,
"INSERT INTO tags (name, color, description) VALUES ($name, $color, $description);", "INSERT INTO tags (name, color, description) VALUES ($name, $color, $description);",
@@ -383,14 +378,12 @@ public sealed class WorkspaceRepository : IDisposable
/// <returns>The updated tag, or the unchanged one for a no-op.</returns> /// <returns>The updated tag, or the unchanged one for a no-op.</returns>
/// <exception cref="InvalidOperationException">The tag does not exist.</exception> /// <exception cref="InvalidOperationException">The tag does not exist.</exception>
/// <exception cref="SqliteException">The new name is empty or not unique.</exception> /// <exception cref="SqliteException">The new name is empty or not unique.</exception>
public TagModel UpdateTag(long tagId, string name, RgbColor color, string description) public TagModel UpdateTag(long tagId, string name, RgbColor color, string description) {
{
TagModel existing = GetTag(tagId) TagModel existing = GetTag(tagId)
?? throw new InvalidOperationException($"Tag {tagId} does not exist."); ?? throw new InvalidOperationException($"Tag {tagId} does not exist.");
// Unchanged name, color and description: no write. // Unchanged name, color and description: no write.
if (existing.Name == name && existing.Color == color && existing.Description == description) if (existing.Name == name && existing.Color == color && existing.Description == description) {
{
return existing; return existing;
} }
@@ -421,8 +414,7 @@ public sealed class WorkspaceRepository : IDisposable
/// </summary> /// </summary>
/// <param name="tagId">The tag id.</param> /// <param name="tagId">The tag id.</param>
/// <returns>The tag, or <see langword="null"/> when it does not exist.</returns> /// <returns>The tag, or <see langword="null"/> when it does not exist.</returns>
private TagModel? GetTag(long tagId) private TagModel? GetTag(long tagId) {
{
using var command = CreateCommand( using var command = CreateCommand(
"SELECT id, name, color, description FROM tags WHERE id = $id;"); "SELECT id, name, color, description FROM tags WHERE id = $id;");
command.Parameters.AddWithValue("$id", tagId); command.Parameters.AddWithValue("$id", tagId);
@@ -435,8 +427,7 @@ public sealed class WorkspaceRepository : IDisposable
/// </summary> /// </summary>
/// <param name="cardId">The card id.</param> /// <param name="cardId">The card id.</param>
/// <returns>The assigned tags in id order.</returns> /// <returns>The assigned tags in id order.</returns>
private IReadOnlyList<TagModel> LoadTags(long cardId) private IReadOnlyList<TagModel> LoadTags(long cardId) {
{
using var command = CreateCommand(""" using var command = CreateCommand("""
SELECT t.id, t.name, t.color, t.description SELECT t.id, t.name, t.color, t.description
FROM tags t FROM tags t
@@ -448,8 +439,7 @@ public sealed class WorkspaceRepository : IDisposable
using var reader = command.ExecuteReader(); using var reader = command.ExecuteReader();
var tags = new List<TagModel>(); var tags = new List<TagModel>();
while (reader.Read()) while (reader.Read()) {
{
tags.Add(ReadTag(reader, 0)); tags.Add(ReadTag(reader, 0));
} }
return tags; return tags;
@@ -479,8 +469,7 @@ public sealed class WorkspaceRepository : IDisposable
/// <param name="sql">The command text.</param> /// <param name="sql">The command text.</param>
/// <param name="transaction">The transaction to enlist in, when any.</param> /// <param name="transaction">The transaction to enlist in, when any.</param>
/// <returns>The prepared command.</returns> /// <returns>The prepared command.</returns>
private SqliteCommand CreateCommand(string sql, SqliteTransaction? transaction = null) private SqliteCommand CreateCommand(string sql, SqliteTransaction? transaction = null) {
{
SqliteCommand command = _connection.CreateCommand(); SqliteCommand command = _connection.CreateCommand();
command.Transaction = transaction; command.Transaction = transaction;
command.CommandText = sql; command.CommandText = sql;
@@ -493,11 +482,9 @@ public sealed class WorkspaceRepository : IDisposable
/// <param name="transaction">The transaction to enlist in.</param> /// <param name="transaction">The transaction to enlist in.</param>
/// <param name="sql">The statement to execute.</param> /// <param name="sql">The statement to execute.</param>
/// <param name="parameters">Name/value pairs bound as SQL parameters.</param> /// <param name="parameters">Name/value pairs bound as SQL parameters.</param>
private void ExecuteNonQuery(SqliteTransaction transaction, string sql, params (string Name, object? Value)[] parameters) private void ExecuteNonQuery(SqliteTransaction transaction, string sql, params (string Name, object? Value)[] parameters) {
{
using SqliteCommand command = CreateCommand(sql, transaction); using SqliteCommand command = CreateCommand(sql, transaction);
foreach ((string name, object? value) in parameters) foreach ((string name, object? value) in parameters) {
{
command.Parameters.AddWithValue(name, value); command.Parameters.AddWithValue(name, value);
} }
command.ExecuteNonQuery(); command.ExecuteNonQuery();
@@ -510,8 +497,7 @@ public sealed class WorkspaceRepository : IDisposable
/// <param name="sql">The INSERT statement.</param> /// <param name="sql">The INSERT statement.</param>
/// <param name="parameters">Name/value pairs bound as SQL parameters.</param> /// <param name="parameters">Name/value pairs bound as SQL parameters.</param>
/// <returns>The rowid assigned to the inserted row.</returns> /// <returns>The rowid assigned to the inserted row.</returns>
private long ExecuteInsert(SqliteTransaction transaction, string sql, params (string Name, object? Value)[] parameters) private long ExecuteInsert(SqliteTransaction transaction, string sql, params (string Name, object? Value)[] parameters) {
{
ExecuteNonQuery(transaction, sql, parameters); ExecuteNonQuery(transaction, sql, parameters);
using SqliteCommand rowId = CreateCommand("SELECT last_insert_rowid();", transaction); using SqliteCommand rowId = CreateCommand("SELECT last_insert_rowid();", transaction);
return (long)rowId.ExecuteScalar()!; return (long)rowId.ExecuteScalar()!;
@@ -523,8 +509,7 @@ public sealed class WorkspaceRepository : IDisposable
/// <param name="sql">The DELETE statement with an <c>$id</c> parameter.</param> /// <param name="sql">The DELETE statement with an <c>$id</c> parameter.</param>
/// <param name="id">The id to delete.</param> /// <param name="id">The id to delete.</param>
/// <returns><see langword="true"/> when a row was deleted.</returns> /// <returns><see langword="true"/> when a row was deleted.</returns>
private bool ExecuteDelete(string sql, long id) private bool ExecuteDelete(string sql, long id) {
{
using SqliteCommand command = CreateCommand(sql); using SqliteCommand command = CreateCommand(sql);
command.Parameters.AddWithValue("$id", id); command.Parameters.AddWithValue("$id", id);
return command.ExecuteNonQuery() > 0; return command.ExecuteNonQuery() > 0;
+1 -2
View File
@@ -7,8 +7,7 @@ namespace YKanBan.Storage.Workspace;
/// KEY) so every stored row is valid by construction, and cascading deletes /// KEY) so every stored row is valid by construction, and cascading deletes
/// are covered by the same DDL. /// are covered by the same DDL.
/// </summary> /// </summary>
public static class WorkspaceSchema public static class WorkspaceSchema {
{
/// <summary> /// <summary>
/// Newest workspace schema version this build understands. /// Newest workspace schema version this build understands.
/// </summary> /// </summary>
+6 -13
View File
@@ -7,8 +7,7 @@ namespace YKanBan.Storage.Workspace;
/// any database work happens. Disposing releases the repository and then the /// any database work happens. Disposing releases the repository and then the
/// lock. /// lock.
/// </summary> /// </summary>
public sealed class WorkspaceSession : IDisposable public sealed class WorkspaceSession : IDisposable {
{
private readonly WorkspaceLock _workspaceLock; private readonly WorkspaceLock _workspaceLock;
/// <summary> /// <summary>
@@ -17,8 +16,7 @@ public sealed class WorkspaceSession : IDisposable
/// <param name="folderPath">The canonical workspace folder path.</param> /// <param name="folderPath">The canonical workspace folder path.</param>
/// <param name="workspaceLock">The exclusive lock held while this session is open.</param> /// <param name="workspaceLock">The exclusive lock held while this session is open.</param>
/// <param name="repository">The data access object for this workspace.</param> /// <param name="repository">The data access object for this workspace.</param>
private WorkspaceSession(string folderPath, WorkspaceLock workspaceLock, WorkspaceRepository repository) private WorkspaceSession(string folderPath, WorkspaceLock workspaceLock, WorkspaceRepository repository) {
{
FolderPath = folderPath; FolderPath = folderPath;
_workspaceLock = workspaceLock; _workspaceLock = workspaceLock;
Repository = repository; Repository = repository;
@@ -41,16 +39,12 @@ public sealed class WorkspaceSession : IDisposable
/// <returns>The opened session; dispose it to release the lock and connection.</returns> /// <returns>The opened session; dispose it to release the lock and connection.</returns>
/// <exception cref="WorkspaceNotInitializedException">The folder has no .ykanban structure.</exception> /// <exception cref="WorkspaceNotInitializedException">The folder has no .ykanban structure.</exception>
/// <exception cref="WorkspaceLockException">Another instance already holds the lock.</exception> /// <exception cref="WorkspaceLockException">Another instance already holds the lock.</exception>
public static WorkspaceSession Open(string folderPath) public static WorkspaceSession Open(string folderPath) {
{
WorkspaceLock workspaceLock = WorkspaceLock.Acquire(folderPath); WorkspaceLock workspaceLock = WorkspaceLock.Acquire(folderPath);
try try {
{
var repository = new WorkspaceRepository(folderPath); var repository = new WorkspaceRepository(folderPath);
return new WorkspaceSession(folderPath, workspaceLock, repository); return new WorkspaceSession(folderPath, workspaceLock, repository);
} } catch {
catch
{
workspaceLock.Dispose(); workspaceLock.Dispose();
throw; throw;
} }
@@ -59,8 +53,7 @@ public sealed class WorkspaceSession : IDisposable
/// <summary> /// <summary>
/// Releases the repository connection, then the exclusive lock. /// Releases the repository connection, then the exclusive lock.
/// </summary> /// </summary>
public void Dispose() public void Dispose() {
{
Repository.Dispose(); Repository.Dispose();
_workspaceLock.Dispose(); _workspaceLock.Dispose();
} }
+6 -8
View File
@@ -1,31 +1,29 @@
using System; using System;
using Avalonia.Controls; using Avalonia.Controls;
using Avalonia.Controls.Templates; using Avalonia.Controls.Templates;
using YKanBan.ViewModels; using YKanBan.ViewModels;
namespace YKanBan; namespace YKanBan;
public class ViewLocator : IDataTemplate public class ViewLocator : IDataTemplate {
{
public Control? Build(object? param) public Control? Build(object? param) {
{
if (param is null) if (param is null)
return null; return null;
var name = param.GetType().FullName!.Replace("ViewModel", "View", StringComparison.Ordinal); var name = param.GetType().FullName!.Replace("ViewModel", "View", StringComparison.Ordinal);
var type = Type.GetType(name); var type = Type.GetType(name);
if (type != null) if (type != null) {
{
return (Control)Activator.CreateInstance(type)!; return (Control)Activator.CreateInstance(type)!;
} }
return new TextBlock { Text = "Not Found: " + name }; return new TextBlock { Text = "Not Found: " + name };
} }
public bool Match(object? data) public bool Match(object? data) {
{
return data is ViewModelBase; return data is ViewModelBase;
} }
} }
+343
View File
@@ -0,0 +1,343 @@
using System.Collections.ObjectModel;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using YKanBan.Models;
using YKanBan.Search;
using YKanBan.Services;
using YKanBan.Storage.AppData;
using YKanBan.Storage.Workspace;
namespace YKanBan.ViewModels.Board;
/// <summary>
/// The board tab: a toolbar (search box, add-column and the Display button)
/// over horizontally arranged columns of vertically stacked cards. All
/// persistence goes through the workspace repository; the board reloads from it
/// after each change.
/// </summary>
public sealed partial class BoardViewModel : ViewModelBase {
private readonly AppServices _services;
private readonly WorkspaceRepository _repository;
// The active search result filter, or null when the whole board is shown.
private IReadOnlyCollection<long>? _matchedCardIds;
/// <summary>
/// Initializes the board, loading its current content.
/// </summary>
/// <param name="services">The process composition root (configuration access).</param>
/// <param name="session">The open workspace session.</param>
public BoardViewModel(AppServices services, WorkspaceSession session) {
_services = services;
_repository = session.Repository;
Display = new DisplaySettingsViewModel(_services.Config, Reload);
Reload();
}
/// <summary>
/// Gets the workspace repository used for all board data access.
/// </summary>
public WorkspaceRepository Repository => _repository;
/// <summary>
/// Gets the live application configuration.
/// </summary>
public AppConfig Config => _services.Config;
/// <summary>
/// Gets the display options (column width, card sort, column sort).
/// </summary>
public DisplaySettingsViewModel Display { get; }
/// <summary>
/// Gets the columns shown by the board, in display order.
/// </summary>
public ObservableCollection<ColumnViewModel> Columns { get; } = [];
/// <summary>
/// Gets or sets the search box text. The board does not filter on change;
/// the search runs only when the search button is used.
/// </summary>
[ObservableProperty]
private string searchText = string.Empty;
/// <summary>
/// Gets the rendered column width in pixels, applied globally.
/// </summary>
[ObservableProperty]
private double columnWidth;
/// <summary>
/// Gets a value indicating whether a search filter is currently applied.
/// </summary>
public bool IsFiltering => _matchedCardIds is not null;
/// <summary>
/// Gets the localized filter status text shown as the status icon tooltip.
/// </summary>
public string FilterStatusText => IsFiltering ? Resources.Board_FilterActive : Resources.Board_FilterInactive;
/// <summary>
/// Gets the status icon opacity: full while filtering, dimmed otherwise.
/// </summary>
public double FilterIconOpacity => IsFiltering ? 1.0 : 0.4;
/// <summary>
/// Gets a value indicating whether the board has any columns.
/// </summary>
public bool HasColumns => Columns.Count > 0;
/// <summary>
/// Gets a value indicating whether the board is empty.
/// </summary>
public bool HasNoColumns => Columns.Count == 0;
#region Interactions
/// <summary>
/// Gets the interaction that opens the new-column editor.
/// </summary>
public Interaction<Unit> AddColumn { get; } = new();
/// <summary>
/// Gets the interaction that opens the column editor.
/// </summary>
public Interaction<ColumnViewModel> EditColumn { get; } = new();
/// <summary>
/// Gets the interaction that confirms and deletes a column.
/// </summary>
public Interaction<ColumnViewModel> DeleteColumn { get; } = new();
/// <summary>
/// Gets the interaction that opens the new-card editor.
/// </summary>
public Interaction<ColumnViewModel> AddCard { get; } = new();
/// <summary>
/// Gets the interaction that opens the card editor.
/// </summary>
public Interaction<CardViewModel> EditCard { get; } = new();
/// <summary>
/// Gets the interaction that confirms and deletes a card.
/// </summary>
public Interaction<CardViewModel> DeleteCard { get; } = new();
/// <summary>
/// Gets the interaction that opens the move-card dialog.
/// </summary>
public Interaction<CardViewModel> MoveCard { get; } = new();
/// <summary>
/// Gets the interaction that shows the search error dialog, carrying the English parser detail.
/// </summary>
public Interaction<string> ShowSearchError { get; } = new();
#endregion
#region Commands
/// <summary>
/// Opens the new-column editor.
/// </summary>
[RelayCommand]
private Task AddNewColumnAsync() => AddColumn.Handle(Unit.Value);
/// <summary>
/// Runs the current search. A blank query shows everything; an invalid
/// expression opens the error dialog and keeps the previous results and text.
/// </summary>
[RelayCommand]
private async Task SearchAsync() {
if (string.IsNullOrWhiteSpace(SearchText)) {
ApplyFilter(null);
return;
}
try {
SearchNode? query = SearchQueryParser.Parse(SearchText);
if (query is null) {
ApplyFilter(null);
return;
}
CompiledSearch compiled = SearchSqlCompiler.Compile(query);
ApplyFilter(_repository.GetCardIdsMatching(compiled));
} catch (SearchSyntaxException exception) {
// The error dialog carries the parser's non-localized English detail.
await ShowSearchError.Handle(exception.Message);
}
}
/// <summary>
/// Clears the search box and restores the unfiltered board.
/// </summary>
[RelayCommand]
private void ClearSearch() {
SearchText = string.Empty;
ApplyFilter(null);
}
/// <summary>
/// Applies a new result filter (null clears it) and rebuilds the board when it changed.
/// </summary>
/// <param name="matchedIds">The new filter, or <see langword="null"/> for no filter.</param>
private void ApplyFilter(IReadOnlyCollection<long>? matchedIds) {
if (_matchedCardIds is null && matchedIds is null) {
return;
}
_matchedCardIds = matchedIds;
OnPropertyChanged(nameof(IsFiltering));
OnPropertyChanged(nameof(FilterStatusText));
OnPropertyChanged(nameof(FilterIconOpacity));
Reload();
}
#endregion
#region Requests from columns and cards
/// <summary>
/// Requests the new-card editor for the given column.
/// </summary>
/// <param name="column">The target column.</param>
/// <returns>A task completing after the editor closes.</returns>
public Task RequestAddCardAsync(ColumnViewModel column) => AddCard.Handle(column);
/// <summary>
/// Requests the editor for the given card.
/// </summary>
/// <param name="card">The card to edit.</param>
/// <returns>A task completing after the editor closes.</returns>
public Task RequestEditCardAsync(CardViewModel card) => EditCard.Handle(card);
/// <summary>
/// Requests deletion of the given card.
/// </summary>
/// <param name="card">The card to delete.</param>
/// <returns>A task completing after confirmation.</returns>
public Task RequestDeleteCardAsync(CardViewModel card) => DeleteCard.Handle(card);
/// <summary>
/// Requests moving the given card to another column.
/// </summary>
/// <param name="card">The card to move.</param>
/// <returns>A task completing after the move.</returns>
public Task RequestMoveCardAsync(CardViewModel card) => MoveCard.Handle(card);
/// <summary>
/// Requests the editor for the given column.
/// </summary>
/// <param name="column">The column to edit.</param>
/// <returns>A task completing after the editor closes.</returns>
public Task RequestEditColumnAsync(ColumnViewModel column) => EditColumn.Handle(column);
/// <summary>
/// Requests deletion of the given column.
/// </summary>
/// <param name="column">The column to delete.</param>
/// <returns>A task completing after confirmation.</returns>
public Task RequestDeleteColumnAsync(ColumnViewModel column) => DeleteColumn.Handle(column);
#endregion
#region Loading and ordering
/// <summary>
/// Reloads all columns and cards from the repository and rebuilds the board.
/// </summary>
public void Reload() {
IReadOnlyList<ColumnModel> columns = _repository.GetColumns();
IReadOnlyList<CardModel> cards = _repository.GetCards();
// An active search hides non-matching cards while every column stays visible.
if (_matchedCardIds is not null) {
cards = cards.Where(card => _matchedCardIds.Contains(card.Id)).ToList();
}
// Group cards by column once so each column can be built independently.
Dictionary<long, List<CardModel>> cardsByColumn = cards
.GroupBy(card => card.ColumnId)
.ToDictionary(group => group.Key, group => group.ToList());
IEnumerable<ColumnModel> orderedColumns = SortColumns(columns, _services.Config.Display.ColumnSort);
Columns.Clear();
foreach (ColumnModel column in orderedColumns) {
// Cards are sorted within their column by the selected card order.
IEnumerable<CardModel> columnCards = cardsByColumn.TryGetValue(column.Id, out List<CardModel>? list)
? SortCards(list, _services.Config.Display.CardSort)
: [];
Columns.Add(new ColumnViewModel(this, column, columnCards.Select(card => new CardViewModel(this, card))));
}
ApplyColumnWidth();
OnPropertyChanged(nameof(HasColumns));
OnPropertyChanged(nameof(HasNoColumns));
}
/// <summary>
/// Recomputes the global column width and pushes it to every column.
/// </summary>
public void ApplyColumnWidth() {
ColumnWidth = ColumnWidthPixels(_services.Config.Display.ColumnWidth);
foreach (ColumnViewModel column in Columns) {
column.Width = ColumnWidth;
}
}
/// <summary>
/// Resolves a column width setting to its pixel value.
/// </summary>
/// <param name="settings">The configured column width.</param>
/// <returns>The width in pixels.</returns>
public static double ColumnWidthPixels(ColumnWidthSettings settings) => settings.Preset switch {
ColumnWidthPreset.Narrow => 240,
ColumnWidthPreset.Wide => 480,
ColumnWidthPreset.Custom => settings.CustomPixels,
_ => 320,
};
/// <summary>
/// Orders cards by the selected option, tie-breaking by id ascending.
/// </summary>
/// <param name="cards">The cards to order.</param>
/// <param name="option">The selected order.</param>
/// <returns>The ordered cards.</returns>
private static IEnumerable<CardModel> SortCards(IEnumerable<CardModel> cards, SortOption option) => option switch {
SortOption.IdAscending => cards.OrderBy(card => card.Id),
SortOption.IdDescending => cards.OrderByDescending(card => card.Id),
SortOption.CreatedAscending => cards.OrderBy(card => card.CreatedAt).ThenBy(card => card.Id),
SortOption.CreatedDescending => cards.OrderByDescending(card => card.CreatedAt).ThenBy(card => card.Id),
SortOption.UpdatedAscending => cards.OrderBy(card => card.UpdatedAt).ThenBy(card => card.Id),
SortOption.UpdatedDescending => cards.OrderByDescending(card => card.UpdatedAt).ThenBy(card => card.Id),
SortOption.TitleAscending => cards.OrderBy(card => card.Title, StringComparer.Ordinal).ThenBy(card => card.Id),
SortOption.TitleDescending => cards.OrderByDescending(card => card.Title, StringComparer.Ordinal).ThenBy(card => card.Id),
_ => cards.OrderBy(card => card.Id),
};
/// <summary>
/// Orders columns by the selected option, tie-breaking by id ascending.
/// </summary>
/// <param name="columns">The columns to order.</param>
/// <param name="option">The selected order.</param>
/// <returns>The ordered columns.</returns>
private static IEnumerable<ColumnModel> SortColumns(IEnumerable<ColumnModel> columns, SortOption option) => option switch {
SortOption.IdAscending => columns.OrderBy(column => column.Id),
SortOption.IdDescending => columns.OrderByDescending(column => column.Id),
SortOption.CreatedAscending => columns.OrderBy(column => column.CreatedAt).ThenBy(column => column.Id),
SortOption.CreatedDescending => columns.OrderByDescending(column => column.CreatedAt).ThenBy(column => column.Id),
SortOption.UpdatedAscending => columns.OrderBy(column => column.UpdatedAt).ThenBy(column => column.Id),
SortOption.UpdatedDescending => columns.OrderByDescending(column => column.UpdatedAt).ThenBy(column => column.Id),
SortOption.TitleAscending => columns.OrderBy(column => column.Title, StringComparer.Ordinal).ThenBy(column => column.Id),
SortOption.TitleDescending => columns.OrderByDescending(column => column.Title, StringComparer.Ordinal).ThenBy(column => column.Id),
_ => columns.OrderBy(column => column.Id),
};
#endregion
}
+104
View File
@@ -0,0 +1,104 @@
using CommunityToolkit.Mvvm.Input;
using YKanBan.Models;
namespace YKanBan.ViewModels.Board;
/// <summary>
/// One card on the board. Clicking the card body opens the editor; the corner
/// menu offers delete and move. The shown text is the "#id title" heading, a
/// truncated content preview and the colored tag badges; timestamps are not
/// shown on the board.
/// </summary>
public sealed partial class CardViewModel : ViewModelBase {
/// <summary>
/// Maximum number of content characters shown in the card preview.
/// </summary>
private const int PreviewLength = 200;
private readonly BoardViewModel _board;
/// <summary>
/// Initializes the card view from its model.
/// </summary>
/// <param name="board">The owning board view model.</param>
/// <param name="card">The card model to display.</param>
public CardViewModel(BoardViewModel board, CardModel card) {
_board = board;
Model = card;
TagBadges = card.Tags.Select(tag => new TagBadgeViewModel(tag)).ToList();
}
/// <summary>
/// Gets the underlying card model.
/// </summary>
public CardModel Model { get; }
/// <summary>
/// Gets the card id.
/// </summary>
public long Id => Model.Id;
/// <summary>
/// Gets the owning column id.
/// </summary>
public long ColumnId => Model.ColumnId;
/// <summary>
/// Gets the tag badges shown under the content.
/// </summary>
public IReadOnlyList<TagBadgeViewModel> TagBadges { get; }
/// <summary>
/// Gets the bold id marker, for example "#61".
/// </summary>
public string IdText => $"#{Model.Id}";
/// <summary>
/// Gets the card title, empty when the card has no title.
/// </summary>
public string TitleText => Model.Title;
/// <summary>
/// Gets a value indicating whether the card has a title to show.
/// </summary>
public bool HasTitle => Model.Title.Length > 0;
/// <summary>
/// Gets a value indicating whether the card has content to preview.
/// </summary>
public bool HasContent => Model.Content.Length > 0;
/// <summary>
/// Gets the content preview, collapsed to one line and truncated.
/// </summary>
public string PreviewContent {
get {
string singleLine = Model.Content.Replace("\r", " ").Replace("\n", " ");
return singleLine.Length <= PreviewLength ? singleLine : singleLine[..PreviewLength] + "…";
}
}
/// <summary>
/// Gets a value indicating whether the card has any tags.
/// </summary>
public bool HasTags => TagBadges.Count > 0;
/// <summary>
/// Opens the card editor.
/// </summary>
[RelayCommand]
private void Edit() => _ = _board.RequestEditCardAsync(this);
/// <summary>
/// Asks the board to delete this card.
/// </summary>
[RelayCommand]
private void Delete() => _ = _board.RequestDeleteCardAsync(this);
/// <summary>
/// Asks the board to move this card to another column.
/// </summary>
[RelayCommand]
private void Move() => _ = _board.RequestMoveCardAsync(this);
}
@@ -0,0 +1,89 @@
using System.Collections.ObjectModel;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using YKanBan.Models;
namespace YKanBan.ViewModels.Board;
/// <summary>
/// One board column: a header with its title, card count and actions, plus the
/// vertically stacked cards.
/// </summary>
public sealed partial class ColumnViewModel : ViewModelBase {
private readonly BoardViewModel _board;
/// <summary>
/// Initializes the column view from its model and cards.
/// </summary>
/// <param name="board">The owning board view model.</param>
/// <param name="column">The column model.</param>
/// <param name="cards">The already sorted cards belonging to this column.</param>
public ColumnViewModel(BoardViewModel board, ColumnModel column, IEnumerable<CardViewModel> cards) {
_board = board;
Model = column;
Cards = new ObservableCollection<CardViewModel>(cards);
width = board.ColumnWidth;
}
/// <summary>
/// Gets the underlying column model.
/// </summary>
public ColumnModel Model { get; }
/// <summary>
/// Gets the column id.
/// </summary>
public long Id => Model.Id;
/// <summary>
/// Gets the column title.
/// </summary>
public string Title => Model.Title;
/// <summary>
/// Gets the column description.
/// </summary>
public string Description => Model.Description;
/// <summary>
/// Gets the cards in this column, already in display order.
/// </summary>
public ObservableCollection<CardViewModel> Cards { get; }
/// <summary>
/// Gets the number of cards in this column.
/// </summary>
public int CardCount => Cards.Count;
/// <summary>
/// Gets the tooltip text: the column description when present, otherwise
/// <see langword="null"/> so no tooltip is shown.
/// </summary>
public string? ToolTipText => Model.Description.Length > 0 ? Model.Description : null;
/// <summary>
/// Gets or sets the rendered column width in pixels, applied globally.
/// </summary>
[ObservableProperty]
private double width;
/// <summary>
/// Opens the editor for a new card in this column.
/// </summary>
[RelayCommand]
private void AddCard() => _ = _board.RequestAddCardAsync(this);
/// <summary>
/// Opens the editor for this column.
/// </summary>
[RelayCommand]
private void Edit() => _ = _board.RequestEditColumnAsync(this);
/// <summary>
/// Asks the board to delete this column.
/// </summary>
[RelayCommand]
private void Delete() => _ = _board.RequestDeleteColumnAsync(this);
}
@@ -0,0 +1,164 @@
using CommunityToolkit.Mvvm.ComponentModel;
using YKanBan.Storage.AppData;
namespace YKanBan.ViewModels.Board;
/// <summary>
/// The board display options shown in the Display flyout: the global column
/// width and the separate card and column orderings. Every change writes to
/// the configuration and asks the board to refresh immediately.
/// </summary>
public sealed partial class DisplaySettingsViewModel : ViewModelBase {
/// <summary>
/// Smallest accepted manual width.
/// </summary>
public const int MinimumPixels = 160;
/// <summary>
/// Largest accepted manual width.
/// </summary>
public const int MaximumPixels = 720;
private readonly AppConfig _config;
private readonly Action _refresh;
/// <summary>
/// Initializes the display options from the configuration.
/// </summary>
/// <param name="config">The live application configuration.</param>
/// <param name="refresh">Invoked after every change to refresh the board.</param>
public DisplaySettingsViewModel(AppConfig config, Action refresh) {
_config = config;
_refresh = refresh;
Presets =
[
new OptionItem(ColumnWidthPreset.Narrow, Resources.WidthPreset_Narrow),
new OptionItem(ColumnWidthPreset.Standard, Resources.WidthPreset_Standard),
new OptionItem(ColumnWidthPreset.Wide, Resources.WidthPreset_Wide),
new OptionItem(ColumnWidthPreset.Custom, Resources.WidthPreset_Custom),
];
SortOptions = BuildSortOptions();
selectedPreset = Presets.FirstOrDefault(option => (ColumnWidthPreset)option.Value == config.Display.ColumnWidth.Preset)
?? Presets[1];
customPixels = config.Display.ColumnWidth.CustomPixels;
selectedCardSort = FindSort(SortOptions, config.Display.CardSort);
selectedColumnSort = FindSort(SortOptions, config.Display.ColumnSort);
}
/// <summary>
/// Gets the width preset choices.
/// </summary>
public IReadOnlyList<OptionItem> Presets { get; }
/// <summary>
/// Gets the ordering choices (shared by cards and columns).
/// </summary>
public IReadOnlyList<OptionItem> SortOptions { get; }
/// <summary>
/// Gets or sets the selected width preset.
/// </summary>
[ObservableProperty]
private OptionItem? selectedPreset;
/// <summary>
/// Gets or sets the manual pixel width used by the custom preset.
/// </summary>
[ObservableProperty]
private decimal? customPixels;
/// <summary>
/// Gets or sets the selected card order.
/// </summary>
[ObservableProperty]
private OptionItem? selectedCardSort;
/// <summary>
/// Gets or sets the selected column order.
/// </summary>
[ObservableProperty]
private OptionItem? selectedColumnSort;
/// <summary>
/// Gets a value indicating whether the custom preset is selected.
/// </summary>
public bool IsCustom => SelectedPreset is not null && (ColumnWidthPreset)SelectedPreset.Value == ColumnWidthPreset.Custom;
/// <summary>
/// Stores the width preset and refreshes the board.
/// </summary>
/// <param name="value">The new selection.</param>
partial void OnSelectedPresetChanged(OptionItem? value) {
OnPropertyChanged(nameof(IsCustom));
if (value is not null) {
_config.Display.ColumnWidth.Preset = (ColumnWidthPreset)value.Value;
_refresh();
}
}
/// <summary>
/// Stores the manual width and refreshes the board when the custom preset is active.
/// </summary>
/// <param name="value">The new pixel count.</param>
partial void OnCustomPixelsChanged(decimal? value) {
if (value is null) {
return;
}
int pixels = (int)value.Value;
_config.Display.ColumnWidth.CustomPixels = pixels;
if (IsCustom) {
_refresh();
}
}
/// <summary>
/// Stores the card order and refreshes the board.
/// </summary>
/// <param name="value">The new selection.</param>
partial void OnSelectedCardSortChanged(OptionItem? value) {
if (value is not null) {
_config.Display.CardSort = (SortOption)value.Value;
_refresh();
}
}
/// <summary>
/// Stores the column order and refreshes the board.
/// </summary>
/// <param name="value">The new selection.</param>
partial void OnSelectedColumnSortChanged(OptionItem? value) {
if (value is not null) {
_config.Display.ColumnSort = (SortOption)value.Value;
_refresh();
}
}
/// <summary>
/// Builds the localized eight-way ordering option list.
/// </summary>
/// <returns>The ordering options.</returns>
private static IReadOnlyList<OptionItem> BuildSortOptions() =>
[
new OptionItem(SortOption.IdAscending, Resources.Sort_IdAsc),
new OptionItem(SortOption.IdDescending, Resources.Sort_IdDesc),
new OptionItem(SortOption.CreatedAscending, Resources.Sort_CreatedAsc),
new OptionItem(SortOption.CreatedDescending, Resources.Sort_CreatedDesc),
new OptionItem(SortOption.UpdatedAscending, Resources.Sort_UpdatedAsc),
new OptionItem(SortOption.UpdatedDescending, Resources.Sort_UpdatedDesc),
new OptionItem(SortOption.TitleAscending, Resources.Sort_TitleAsc),
new OptionItem(SortOption.TitleDescending, Resources.Sort_TitleDesc),
];
/// <summary>
/// Finds the option matching a stored sort value.
/// </summary>
/// <param name="options">The option list.</param>
/// <param name="value">The stored value.</param>
/// <returns>The matching option, or the first option.</returns>
private static OptionItem FindSort(IReadOnlyList<OptionItem> options, SortOption value) =>
options.FirstOrDefault(option => (SortOption)option.Value == value) ?? options[0];
}
@@ -0,0 +1,60 @@
using Avalonia.Media;
using YKanBan.Models;
namespace YKanBan.ViewModels.Board;
/// <summary>
/// A read-only colored tag badge shown on a card: the tag name over a
/// background taken directly from the tag color (user data, never themed) and
/// an automatically contrasting text color.
/// </summary>
public sealed class TagBadgeViewModel {
/// <summary>
/// Initializes a badge from a tag.
/// </summary>
/// <param name="tag">The tag to render.</param>
public TagBadgeViewModel(TagModel tag) {
Tag = tag;
Name = tag.Name;
Color background = Color.FromRgb(tag.Color.R, tag.Color.G, tag.Color.B);
Background = new SolidColorBrush(background);
Foreground = new SolidColorBrush(ContrastingTextColor(background));
}
/// <summary>
/// Gets the underlying tag model.
/// </summary>
public TagModel Tag { get; }
/// <summary>
/// Gets the tag name.
/// </summary>
public string Name { get; }
/// <summary>
/// Gets the tooltip text: the tag description when present, otherwise
/// <see langword="null"/> so no tooltip is shown.
/// </summary>
public string? ToolTipText => Tag.Description.Length > 0 ? Tag.Description : null;
/// <summary>
/// Gets the badge background brush.
/// </summary>
public IBrush Background { get; }
/// <summary>
/// Gets the badge text brush.
/// </summary>
public IBrush Foreground { get; }
/// <summary>
/// Picks black or white text for readability against the given background.
/// </summary>
/// <param name="background">The badge background color.</param>
/// <returns>The contrasting text color.</returns>
private static Color ContrastingTextColor(Color background) {
double luminance = (0.299 * background.R + 0.587 * background.G + 0.114 * background.B) / 255.0;
return luminance > 0.6 ? Colors.Black : Colors.White;
}
}
@@ -5,13 +5,11 @@ namespace YKanBan.ViewModels.Dialogs;
/// <summary> /// <summary>
/// The about dialog: application name, version, repository link and license. /// The about dialog: application name, version, repository link and license.
/// </summary> /// </summary>
public sealed class AboutDialogViewModel : ViewModelBase public sealed class AboutDialogViewModel : ViewModelBase {
{
/// <summary> /// <summary>
/// Initializes the view model, reading the version from the assembly. /// Initializes the view model, reading the version from the assembly.
/// </summary> /// </summary>
public AboutDialogViewModel() public AboutDialogViewModel() {
{
string version = typeof(AboutDialogViewModel).Assembly.GetName().Version?.ToString(3) ?? "0.0.0"; string version = typeof(AboutDialogViewModel).Assembly.GetName().Version?.ToString(3) ?? "0.0.0";
Version = string.Format( Version = string.Format(
Resources.Culture ?? CultureInfo.CurrentCulture, Resources.About_Version, version); Resources.Culture ?? CultureInfo.CurrentCulture, Resources.About_Version, version);
@@ -0,0 +1,55 @@
using Avalonia.Media;
using CommunityToolkit.Mvvm.Input;
using YKanBan.Models;
using YKanBan.ViewModels.Board;
namespace YKanBan.ViewModels.Dialogs;
/// <summary>
/// One tag assigned to the card being edited, shown with a colored badge and a
/// remove action that only changes the in-memory assignment (the actual write
/// happens on confirm).
/// </summary>
public sealed partial class AssignedTagViewModel {
private readonly CardEditorViewModel _editor;
private readonly TagBadgeViewModel _badge;
/// <summary>
/// Initializes the assigned-tag row.
/// </summary>
/// <param name="editor">The owning card editor.</param>
/// <param name="tag">The assigned tag.</param>
public AssignedTagViewModel(CardEditorViewModel editor, TagModel tag) {
_editor = editor;
Tag = tag;
_badge = new TagBadgeViewModel(tag);
}
/// <summary>
/// Gets the assigned tag model.
/// </summary>
public TagModel Tag { get; }
/// <summary>
/// Gets the tag name.
/// </summary>
public string Name => _badge.Name;
/// <summary>
/// Gets the badge background brush.
/// </summary>
public IBrush Background => _badge.Background;
/// <summary>
/// Gets the badge text brush.
/// </summary>
public IBrush Foreground => _badge.Foreground;
/// <summary>
/// Removes this tag from the in-memory assignment.
/// </summary>
[RelayCommand]
private void Remove() => _editor.RemoveTag(Tag);
}
@@ -0,0 +1,181 @@
using System.Collections.ObjectModel;
using System.Globalization;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using Microsoft.Data.Sqlite;
using YKanBan.Models;
using YKanBan.Storage.Workspace;
namespace YKanBan.ViewModels.Dialogs;
/// <summary>
/// The add/edit card dialog: title, content and the assigned-tag area, plus
/// read-only id and timestamps for an existing card. The confirm writes the
/// card and its tag assignment as one unit; a confirm with no effective change
/// writes nothing; cancelling never writes.
/// </summary>
public sealed partial class CardEditorViewModel : ViewModelBase {
private readonly WorkspaceRepository _repository;
private readonly long _columnId;
private readonly CardModel? _existing;
/// <summary>
/// Initializes the dialog for a new or existing card.
/// </summary>
/// <param name="repository">The workspace repository.</param>
/// <param name="columnId">The owning column (used when adding).</param>
/// <param name="existing">The card to edit, or <see langword="null"/> to add one.</param>
public CardEditorViewModel(WorkspaceRepository repository, long columnId, CardModel? existing) {
_repository = repository;
_columnId = columnId;
_existing = existing;
title = existing?.Title ?? string.Empty;
content = existing?.Content ?? string.Empty;
AssignedTags = new ObservableCollection<AssignedTagViewModel>(
(existing?.Tags ?? []).Select(tag => new AssignedTagViewModel(this, tag)));
if (existing is not null) {
IdLine = string.Format(Culture, Resources.CardDialog_Id, $"#{existing.Id}");
CreatedLine = string.Format(Culture, Resources.CardDialog_Created, FormatTime(existing.CreatedAt));
ModifiedLine = string.Format(Culture, Resources.CardDialog_Modified, FormatTime(existing.UpdatedAt));
}
}
/// <summary>
/// Gets the interaction that opens the nested tag picker.
/// </summary>
public Interaction<Unit, TagModel?> ShowTagPicker { get; } = new();
/// <summary>
/// Gets the workspace repository (used by the tag picker).
/// </summary>
public WorkspaceRepository Repository => _repository;
/// <summary>
/// Gets a value indicating whether this dialog creates a new card.
/// </summary>
public bool IsNew => _existing is null;
/// <summary>
/// Gets the localized window title.
/// </summary>
public string WindowTitle => IsNew ? Resources.CardDialog_AddTitle : Resources.CardDialog_EditTitle;
/// <summary>
/// Gets the read-only id line, empty for a new card.
/// </summary>
public string IdLine { get; } = string.Empty;
/// <summary>
/// Gets the read-only created line, empty for a new card.
/// </summary>
public string CreatedLine { get; } = string.Empty;
/// <summary>
/// Gets the read-only modified line, empty for a new card.
/// </summary>
public string ModifiedLine { get; } = string.Empty;
/// <summary>
/// Gets the tags currently assigned to the card (in memory until confirmed).
/// </summary>
public ObservableCollection<AssignedTagViewModel> AssignedTags { get; }
/// <summary>
/// Gets or sets the card title.
/// </summary>
[ObservableProperty]
private string title;
/// <summary>
/// Gets or sets the card content.
/// </summary>
[ObservableProperty]
private string content;
/// <summary>
/// Gets or sets the inline error shown when the write fails.
/// </summary>
[ObservableProperty]
private string? errorMessage;
/// <summary>
/// Gets a value indicating whether there are unsaved effective changes.
/// </summary>
public bool HasChanges {
get {
if (_existing is null) {
return Title.Length > 0 || Content.Length > 0 || AssignedTags.Count > 0;
}
bool tagsChanged = !AssignedTags.Select(row => row.Tag.Id).ToHashSet()
.SetEquals(_existing.Tags.Select(tag => tag.Id));
return _existing.Title != Title || _existing.Content != Content || tagsChanged;
}
}
/// <summary>
/// Opens the nested tag picker and adds the chosen tag when it is new to the card.
/// </summary>
[RelayCommand]
private async Task AddTagAsync() {
TagModel? tag = await ShowTagPicker.Handle(Unit.Value);
if (tag is not null && AssignedTags.All(row => row.Tag.Id != tag.Id)) {
AssignedTags.Add(new AssignedTagViewModel(this, tag));
}
}
/// <summary>
/// Removes a tag from the in-memory assignment.
/// </summary>
/// <param name="tag">The tag to remove.</param>
public void RemoveTag(TagModel tag) {
AssignedTagViewModel? row = AssignedTags.FirstOrDefault(item => item.Tag.Id == tag.Id);
if (row is not null) {
AssignedTags.Remove(row);
}
}
/// <summary>
/// Writes the card and its tags when there is an effective change.
/// </summary>
/// <returns><see langword="true"/> when the dialog may close.</returns>
public bool TryAccept() {
ErrorMessage = null;
// A confirm with no effective change writes nothing and just closes.
if (!HasChanges) {
return true;
}
try {
IReadOnlyCollection<long> tagIds = AssignedTags.Select(row => row.Tag.Id).ToList();
if (_existing is null) {
_repository.AddCard(_columnId, Title, Content, tagIds);
} else {
_repository.UpdateCard(_existing.Id, Title, Content, tagIds);
}
return true;
} catch (SqliteException) {
ErrorMessage = Resources.CardDialog_Error;
return false;
}
}
/// <summary>
/// Gets the culture used for formatted read-only lines.
/// </summary>
private static CultureInfo Culture => Resources.Culture ?? CultureInfo.CurrentCulture;
/// <summary>
/// Formats a stored timestamp as a local time using the UI language pattern.
/// </summary>
/// <param name="unixSeconds">The stored timestamp.</param>
/// <returns>The formatted local time.</returns>
private static string FormatTime(long unixSeconds) =>
DateTimeOffset.FromUnixTimeSeconds(unixSeconds).ToLocalTime().ToString(Resources.CardDialog_TimePattern, Culture);
}
@@ -0,0 +1,78 @@
using CommunityToolkit.Mvvm.ComponentModel;
using Microsoft.Data.Sqlite;
using YKanBan.Models;
using YKanBan.Storage.Workspace;
namespace YKanBan.ViewModels.Dialogs;
/// <summary>
/// The add/edit column dialog: a required title and an optional description.
/// The write happens when the dialog is accepted; a duplicate or empty title
/// keeps the dialog open with an inline error.
/// </summary>
public sealed partial class ColumnEditorViewModel : ViewModelBase {
private readonly WorkspaceRepository _repository;
private readonly ColumnModel? _existing;
/// <summary>
/// Initializes the dialog for a new or existing column.
/// </summary>
/// <param name="repository">The workspace repository.</param>
/// <param name="existing">The column to edit, or <see langword="null"/> to add one.</param>
public ColumnEditorViewModel(WorkspaceRepository repository, ColumnModel? existing) {
_repository = repository;
_existing = existing;
title = existing?.Title ?? string.Empty;
description = existing?.Description ?? string.Empty;
}
/// <summary>
/// Gets a value indicating whether this dialog creates a new column.
/// </summary>
public bool IsNew => _existing is null;
/// <summary>
/// Gets the localized window title.
/// </summary>
public string WindowTitle => IsNew ? Resources.ColumnDialog_AddTitle : Resources.ColumnDialog_EditTitle;
/// <summary>
/// Gets or sets the column title.
/// </summary>
[ObservableProperty]
private string title;
/// <summary>
/// Gets or sets the column description.
/// </summary>
[ObservableProperty]
private string description;
/// <summary>
/// Gets or sets the inline error shown when the title is rejected.
/// </summary>
[ObservableProperty]
private string? errorMessage;
/// <summary>
/// Writes the column when accepted.
/// </summary>
/// <returns><see langword="true"/> when the dialog may close.</returns>
public bool TryAccept() {
ErrorMessage = null;
try {
if (_existing is null) {
_repository.AddColumn(Title, Description);
} else {
_repository.UpdateColumn(_existing.Id, Title, Description);
}
return true;
} catch (SqliteException) {
ErrorMessage = Resources.ColumnDialog_InvalidTitle;
return false;
}
}
}
@@ -0,0 +1,24 @@
using System.Globalization;
namespace YKanBan.ViewModels.Dialogs;
/// <summary>
/// The confirmation shown before deleting a card, naming the card id.
/// </summary>
public sealed class DeleteCardConfirmViewModel : ViewModelBase {
/// <summary>
/// Initializes the confirmation.
/// </summary>
/// <param name="cardId">The id of the card to delete.</param>
public DeleteCardConfirmViewModel(long cardId) {
Message = string.Format(
Resources.Culture ?? CultureInfo.CurrentCulture,
Resources.Confirm_DeleteCard_Message,
cardId);
}
/// <summary>
/// Gets the localized confirmation message.
/// </summary>
public string Message { get; }
}
@@ -0,0 +1,27 @@
using System.Globalization;
namespace YKanBan.ViewModels.Dialogs;
/// <summary>
/// The confirmation shown before deleting a column, naming the column and how
/// many cards it will cascade-delete.
/// </summary>
public sealed class DeleteColumnConfirmViewModel : ViewModelBase {
/// <summary>
/// Initializes the confirmation.
/// </summary>
/// <param name="columnTitle">The title of the column to delete.</param>
/// <param name="cardCount">The number of cards in the column.</param>
public DeleteColumnConfirmViewModel(string columnTitle, int cardCount) {
Message = string.Format(
Resources.Culture ?? CultureInfo.CurrentCulture,
Resources.Confirm_DeleteColumn_Message,
columnTitle,
cardCount);
}
/// <summary>
/// Gets the localized confirmation message.
/// </summary>
public string Message { get; }
}
@@ -0,0 +1,27 @@
using System.Globalization;
namespace YKanBan.ViewModels.Dialogs;
/// <summary>
/// The confirmation shown before deleting a tag, naming the tag and how many
/// cards it will be removed from.
/// </summary>
public sealed class DeleteTagConfirmViewModel : ViewModelBase {
/// <summary>
/// Initializes the confirmation.
/// </summary>
/// <param name="tagName">The name of the tag to delete.</param>
/// <param name="usageCount">The number of cards using the tag.</param>
public DeleteTagConfirmViewModel(string tagName, long usageCount) {
Message = string.Format(
Resources.Culture ?? CultureInfo.CurrentCulture,
Resources.DeleteTag_Confirm_Message,
tagName,
usageCount);
}
/// <summary>
/// Gets the localized confirmation message.
/// </summary>
public string Message { get; }
}
@@ -0,0 +1,11 @@
namespace YKanBan.ViewModels.Dialogs;
/// <summary>
/// The confirmation shown before closing an editor with unsaved changes.
/// </summary>
public sealed class DiscardEditConfirmViewModel : ViewModelBase {
/// <summary>
/// Gets the localized confirmation message.
/// </summary>
public string Message => Resources.Confirm_Discard_Message;
}
@@ -0,0 +1,23 @@
using System.Globalization;
namespace YKanBan.ViewModels.Dialogs;
/// <summary>
/// The confirmation dialog shown after a successful Markdown export, naming the
/// written file.
/// </summary>
public sealed class ExportDoneViewModel : ViewModelBase {
/// <summary>
/// Initializes the dialog with the exported file path.
/// </summary>
/// <param name="filePath">The path the export was written to.</param>
public ExportDoneViewModel(string filePath) {
Message = string.Format(
Resources.Culture ?? CultureInfo.CurrentCulture, Resources.Export_Done_Message, filePath);
}
/// <summary>
/// Gets the localized confirmation message.
/// </summary>
public string Message { get; }
}
@@ -0,0 +1,39 @@
using CommunityToolkit.Mvvm.ComponentModel;
using YKanBan.Models;
namespace YKanBan.ViewModels.Dialogs;
/// <summary>
/// The move-card dialog: choose one of the other columns as the destination.
/// </summary>
public sealed partial class MoveCardViewModel : ViewModelBase {
/// <summary>
/// Initializes the dialog with the candidate destination columns.
/// </summary>
/// <param name="columns">All columns; the card's current column is excluded.</param>
/// <param name="currentColumnId">The card's current column id.</param>
public MoveCardViewModel(IReadOnlyList<ColumnModel> columns, long currentColumnId) {
Targets = columns
.Where(column => column.Id != currentColumnId)
.Select(column => new OptionItem(column.Id, column.Title))
.ToList();
selectedTarget = Targets.FirstOrDefault();
}
/// <summary>
/// Gets the candidate destination columns.
/// </summary>
public IReadOnlyList<OptionItem> Targets { get; }
/// <summary>
/// Gets or sets the selected destination column.
/// </summary>
[ObservableProperty]
private OptionItem? selectedTarget;
/// <summary>
/// Gets a value indicating whether there is anywhere to move the card.
/// </summary>
public bool CanMove => Targets.Count > 0;
}
@@ -0,0 +1,25 @@
using System.Globalization;
namespace YKanBan.ViewModels.Dialogs;
/// <summary>
/// The pure-information dialog shown when the search expression is invalid. It
/// wraps the parser's non-localized English detail in the localized message.
/// </summary>
public sealed class SearchErrorViewModel : ViewModelBase {
/// <summary>
/// Initializes the dialog with the parser's English detail.
/// </summary>
/// <param name="detail">The non-localized parser error description.</param>
public SearchErrorViewModel(string detail) {
Message = string.Format(
Resources.Culture ?? CultureInfo.CurrentCulture,
Resources.Search_Error_Message,
detail);
}
/// <summary>
/// Gets the localized error message.
/// </summary>
public string Message { get; }
}
@@ -1,4 +1,5 @@
using CommunityToolkit.Mvvm.ComponentModel; using CommunityToolkit.Mvvm.ComponentModel;
using YKanBan.Storage.AppData; using YKanBan.Storage.AppData;
namespace YKanBan.ViewModels.Dialogs; namespace YKanBan.ViewModels.Dialogs;
@@ -8,8 +9,7 @@ namespace YKanBan.ViewModels.Dialogs;
/// confirmation-dialog toggles. Nothing is applied until the user accepts; /// confirmation-dialog toggles. Nothing is applied until the user accepts;
/// cancelling or closing the window discards the changes. /// cancelling or closing the window discards the changes.
/// </summary> /// </summary>
public sealed partial class SettingsDialogViewModel : ViewModelBase public sealed partial class SettingsDialogViewModel : ViewModelBase {
{
private readonly AppConfig _config; private readonly AppConfig _config;
private readonly string _startupLanguage; private readonly string _startupLanguage;
@@ -18,8 +18,7 @@ public sealed partial class SettingsDialogViewModel : ViewModelBase
/// </summary> /// </summary>
/// <param name="config">The live application configuration.</param> /// <param name="config">The live application configuration.</param>
/// <param name="startupLanguage">The language applied at startup, for the restart notice.</param> /// <param name="startupLanguage">The language applied at startup, for the restart notice.</param>
public SettingsDialogViewModel(AppConfig config, string startupLanguage) public SettingsDialogViewModel(AppConfig config, string startupLanguage) {
{
_config = config; _config = config;
_startupLanguage = startupLanguage; _startupLanguage = startupLanguage;
@@ -101,14 +100,11 @@ public sealed partial class SettingsDialogViewModel : ViewModelBase
/// <summary> /// <summary>
/// Commits the working values into the live configuration. /// Commits the working values into the live configuration.
/// </summary> /// </summary>
public void Accept() public void Accept() {
{ if (SelectedLanguage is not null) {
if (SelectedLanguage is not null)
{
_config.Language = (string)SelectedLanguage.Value; _config.Language = (string)SelectedLanguage.Value;
} }
if (SelectedTheme is not null) if (SelectedTheme is not null) {
{
_config.Theme = (ThemeOption)SelectedTheme.Value; _config.Theme = (ThemeOption)SelectedTheme.Value;
App.ApplyTheme(_config.Theme); App.ApplyTheme(_config.Theme);
} }
@@ -0,0 +1,91 @@
using Avalonia.Media;
using CommunityToolkit.Mvvm.ComponentModel;
using Microsoft.Data.Sqlite;
using YKanBan.Models;
using YKanBan.Storage.Workspace;
namespace YKanBan.ViewModels.Dialogs;
/// <summary>
/// The add/edit tag dialog: a name, a color chosen with a color picker and an
/// optional description. The write happens when the dialog is accepted; a
/// duplicate or empty name keeps the dialog open with an inline error.
/// </summary>
public sealed partial class TagEditorViewModel : ViewModelBase {
private readonly WorkspaceRepository _repository;
private readonly TagModel? _existing;
/// <summary>
/// Initializes the dialog for a new or existing tag.
/// </summary>
/// <param name="repository">The workspace repository.</param>
/// <param name="existing">The tag to edit, or <see langword="null"/> to add one.</param>
public TagEditorViewModel(WorkspaceRepository repository, TagModel? existing) {
_repository = repository;
_existing = existing;
name = existing?.Name ?? string.Empty;
description = existing?.Description ?? string.Empty;
color = existing is not null
? Color.FromRgb(existing.Color.R, existing.Color.G, existing.Color.B)
: Colors.Gray;
}
/// <summary>
/// Gets a value indicating whether this dialog creates a new tag.
/// </summary>
public bool IsNew => _existing is null;
/// <summary>
/// Gets the localized window title.
/// </summary>
public string WindowTitle => IsNew ? Resources.TagEditor_AddTitle : Resources.TagEditor_EditTitle;
/// <summary>
/// Gets or sets the tag name.
/// </summary>
[ObservableProperty]
private string name;
/// <summary>
/// Gets or sets the tag color.
/// </summary>
[ObservableProperty]
private Color color;
/// <summary>
/// Gets or sets the tag description.
/// </summary>
[ObservableProperty]
private string description;
/// <summary>
/// Gets or sets the inline error shown when the name is rejected.
/// </summary>
[ObservableProperty]
private string? errorMessage;
/// <summary>
/// Writes the tag when accepted.
/// </summary>
/// <returns><see langword="true"/> when the dialog may close.</returns>
public bool TryAccept() {
ErrorMessage = null;
var rgb = new RgbColor(Color.R, Color.G, Color.B);
try {
if (_existing is null) {
_repository.AddTag(Name, rgb, Description);
} else {
_repository.UpdateTag(_existing.Id, Name, rgb, Description);
}
return true;
} catch (SqliteException) {
ErrorMessage = Resources.TagEditor_InvalidName;
return false;
}
}
}
@@ -0,0 +1,42 @@
using CommunityToolkit.Mvvm.ComponentModel;
using YKanBan.Storage.Workspace;
using YKanBan.ViewModels.Board;
namespace YKanBan.ViewModels.Dialogs;
/// <summary>
/// The nested tag picker opened from the card editor: choose one tag that is
/// not already assigned to the card. When no candidate remains the picker
/// shows a message and cannot be confirmed.
/// </summary>
public sealed partial class TagPickerViewModel : ViewModelBase {
/// <summary>
/// Initializes the picker with the tags not yet assigned to the card.
/// </summary>
/// <param name="repository">The workspace repository.</param>
/// <param name="assignedTagIds">The tag ids already assigned to the card.</param>
public TagPickerViewModel(WorkspaceRepository repository, IReadOnlyCollection<long> assignedTagIds) {
Targets = repository.GetTags()
.Where(tag => !assignedTagIds.Contains(tag.Id))
.Select(tag => new TagBadgeViewModel(tag))
.ToList();
selectedTarget = Targets.FirstOrDefault();
}
/// <summary>
/// Gets the assignable tags.
/// </summary>
public IReadOnlyList<TagBadgeViewModel> Targets { get; }
/// <summary>
/// Gets or sets the selected tag.
/// </summary>
[ObservableProperty]
private TagBadgeViewModel? selectedTarget;
/// <summary>
/// Gets a value indicating whether there is a tag to add.
/// </summary>
public bool CanAdd => Targets.Count > 0;
}
@@ -4,6 +4,5 @@ namespace YKanBan.ViewModels.ErrorPages;
/// The full-window page shown when YKanBan is started without arguments or with /// The full-window page shown when YKanBan is started without arguments or with
/// invalid arguments. It has no operations. /// invalid arguments. It has no operations.
/// </summary> /// </summary>
public sealed class ArgumentErrorPageViewModel : ViewModelBase public sealed class ArgumentErrorPageViewModel : ViewModelBase {
{
} }
@@ -6,14 +6,12 @@ namespace YKanBan.ViewModels.ErrorPages;
/// The full-window page shown when the folder passed on the command line does /// The full-window page shown when the folder passed on the command line does
/// not exist. It has no operations. /// not exist. It has no operations.
/// </summary> /// </summary>
public sealed class DirectoryMissingPageViewModel : ViewModelBase public sealed class DirectoryMissingPageViewModel : ViewModelBase {
{
/// <summary> /// <summary>
/// Initializes the page for a missing folder. /// Initializes the page for a missing folder.
/// </summary> /// </summary>
/// <param name="folderPath">The folder path that does not exist.</param> /// <param name="folderPath">The folder path that does not exist.</param>
public DirectoryMissingPageViewModel(string folderPath) public DirectoryMissingPageViewModel(string folderPath) {
{
FolderPath = folderPath; FolderPath = folderPath;
Message = string.Format( Message = string.Format(
Resources.Culture ?? CultureInfo.CurrentCulture, Resources.Error_DirectoryMissing_Message, folderPath); Resources.Culture ?? CultureInfo.CurrentCulture, Resources.Error_DirectoryMissing_Message, folderPath);
@@ -6,14 +6,12 @@ namespace YKanBan.ViewModels.ErrorPages;
/// The full-window page shown when the workspace is already locked by another /// The full-window page shown when the workspace is already locked by another
/// instance. It has no operations. /// instance. It has no operations.
/// </summary> /// </summary>
public sealed class LockConflictPageViewModel : ViewModelBase public sealed class LockConflictPageViewModel : ViewModelBase {
{
/// <summary> /// <summary>
/// Initializes the page for a locked workspace. /// Initializes the page for a locked workspace.
/// </summary> /// </summary>
/// <param name="folderPath">The locked workspace folder.</param> /// <param name="folderPath">The locked workspace folder.</param>
public LockConflictPageViewModel(string folderPath) public LockConflictPageViewModel(string folderPath) {
{
FolderPath = folderPath; FolderPath = folderPath;
Message = string.Format( Message = string.Format(
Resources.Culture ?? CultureInfo.CurrentCulture, Resources.Error_LockConflict_Message, folderPath); Resources.Culture ?? CultureInfo.CurrentCulture, Resources.Error_LockConflict_Message, folderPath);
@@ -1,4 +1,5 @@
using System.Globalization; using System.Globalization;
using CommunityToolkit.Mvvm.Input; using CommunityToolkit.Mvvm.Input;
namespace YKanBan.ViewModels.ErrorPages; namespace YKanBan.ViewModels.ErrorPages;
@@ -8,8 +9,7 @@ namespace YKanBan.ViewModels.ErrorPages;
/// structure. It is the only error page with an operation: initializing the /// structure. It is the only error page with an operation: initializing the
/// workspace. /// workspace.
/// </summary> /// </summary>
public sealed partial class NotInitializedPageViewModel : ViewModelBase public sealed partial class NotInitializedPageViewModel : ViewModelBase {
{
private readonly Interaction<Unit> _initializeWorkspace; private readonly Interaction<Unit> _initializeWorkspace;
/// <summary> /// <summary>
@@ -17,8 +17,7 @@ public sealed partial class NotInitializedPageViewModel : ViewModelBase
/// </summary> /// </summary>
/// <param name="folderPath">The uninitialized folder path.</param> /// <param name="folderPath">The uninitialized folder path.</param>
/// <param name="initializeWorkspace">The interaction that performs initialization.</param> /// <param name="initializeWorkspace">The interaction that performs initialization.</param>
public NotInitializedPageViewModel(string folderPath, Interaction<Unit> initializeWorkspace) public NotInitializedPageViewModel(string folderPath, Interaction<Unit> initializeWorkspace) {
{
FolderPath = folderPath; FolderPath = folderPath;
_initializeWorkspace = initializeWorkspace; _initializeWorkspace = initializeWorkspace;
Message = string.Format( Message = string.Format(
+3 -6
View File
@@ -3,8 +3,7 @@ namespace YKanBan.ViewModels;
/// <summary> /// <summary>
/// Input placeholder for interactions that carry no meaningful payload. /// Input placeholder for interactions that carry no meaningful payload.
/// </summary> /// </summary>
public readonly record struct Unit public readonly record struct Unit {
{
/// <summary> /// <summary>
/// Gets the single unit value. /// Gets the single unit value.
/// </summary> /// </summary>
@@ -18,8 +17,7 @@ public readonly record struct Unit
/// The view model never holds a reference to a view. /// The view model never holds a reference to a view.
/// </summary> /// </summary>
/// <typeparam name="TInput">The request payload.</typeparam> /// <typeparam name="TInput">The request payload.</typeparam>
public sealed class Interaction<TInput> public sealed class Interaction<TInput> {
{
private Func<TInput, Task>? _handler; private Func<TInput, Task>? _handler;
/// <summary> /// <summary>
@@ -46,8 +44,7 @@ public sealed class Interaction<TInput>
/// </summary> /// </summary>
/// <typeparam name="TInput">The request payload.</typeparam> /// <typeparam name="TInput">The request payload.</typeparam>
/// <typeparam name="TOutput">The handler's answer.</typeparam> /// <typeparam name="TOutput">The handler's answer.</typeparam>
public sealed class Interaction<TInput, TOutput> public sealed class Interaction<TInput, TOutput> {
{
private Func<TInput, Task<TOutput>>? _handler; private Func<TInput, Task<TOutput>>? _handler;
/// <summary> /// <summary>
+17 -30
View File
@@ -1,5 +1,7 @@
using System.Diagnostics; using System.Diagnostics;
using CommunityToolkit.Mvvm.ComponentModel; using CommunityToolkit.Mvvm.ComponentModel;
using YKanBan.Launching; using YKanBan.Launching;
using YKanBan.Services; using YKanBan.Services;
using YKanBan.Storage; using YKanBan.Storage;
@@ -13,8 +15,7 @@ namespace YKanBan.ViewModels;
/// normal workspace view or one of the full-window error pages, and owns the /// normal workspace view or one of the full-window error pages, and owns the
/// interactions that the view fulfils by opening dialogs. /// interactions that the view fulfils by opening dialogs.
/// </summary> /// </summary>
public sealed partial class MainWindowViewModel : ViewModelBase public sealed partial class MainWindowViewModel : ViewModelBase {
{
private readonly AppServices _services; private readonly AppServices _services;
/// <summary> /// <summary>
@@ -22,8 +23,7 @@ public sealed partial class MainWindowViewModel : ViewModelBase
/// </summary> /// </summary>
/// <param name="services">The process composition root.</param> /// <param name="services">The process composition root.</param>
/// <param name="arguments">The command-line arguments (excluding the executable).</param> /// <param name="arguments">The command-line arguments (excluding the executable).</param>
public MainWindowViewModel(AppServices services, IReadOnlyList<string> arguments) public MainWindowViewModel(AppServices services, IReadOnlyList<string> arguments) {
{
_services = services; _services = services;
ShowSettings = new Interaction<Unit>(); ShowSettings = new Interaction<Unit>();
ShowAbout = new Interaction<Unit>(); ShowAbout = new Interaction<Unit>();
@@ -63,30 +63,22 @@ public sealed partial class MainWindowViewModel : ViewModelBase
/// Resolves the launch arguments into a content view model. /// Resolves the launch arguments into a content view model.
/// </summary> /// </summary>
/// <param name="arguments">The command-line arguments.</param> /// <param name="arguments">The command-line arguments.</param>
private void Resolve(IReadOnlyList<string> arguments) private void Resolve(IReadOnlyList<string> arguments) {
{ if (!LaunchArguments.TryParse(arguments, out string? folderPath)) {
if (!LaunchArguments.TryParse(arguments, out string? folderPath))
{
Content = new ArgumentErrorPageViewModel(); Content = new ArgumentErrorPageViewModel();
return; return;
} }
if (!Directory.Exists(folderPath)) if (!Directory.Exists(folderPath)) {
{
Content = new DirectoryMissingPageViewModel(folderPath); Content = new DirectoryMissingPageViewModel(folderPath);
return; return;
} }
try try {
{
OpenWorkspace(folderPath); OpenWorkspace(folderPath);
} } catch (WorkspaceNotInitializedException) {
catch (WorkspaceNotInitializedException)
{
Content = new NotInitializedPageViewModel(folderPath, InitializeWorkspace); Content = new NotInitializedPageViewModel(folderPath, InitializeWorkspace);
} } catch (WorkspaceLockException) {
catch (WorkspaceLockException)
{
Content = new LockConflictPageViewModel(folderPath); Content = new LockConflictPageViewModel(folderPath);
} }
} }
@@ -95,10 +87,9 @@ public sealed partial class MainWindowViewModel : ViewModelBase
/// Opens the workspace and switches the content to the normal view. /// Opens the workspace and switches the content to the normal view.
/// </summary> /// </summary>
/// <param name="folderPath">The workspace folder to open.</param> /// <param name="folderPath">The workspace folder to open.</param>
private void OpenWorkspace(string folderPath) private void OpenWorkspace(string folderPath) {
{
WorkspaceSession session = _services.OpenWorkspace(folderPath); WorkspaceSession session = _services.OpenWorkspace(folderPath);
Content = new WorkspaceViewModel(session, ShowSettings, ShowAbout); Content = new WorkspaceViewModel(_services, session, ShowSettings, ShowAbout);
Title = $"{new DirectoryInfo(folderPath).Name} - {Resources.App_Name}"; Title = $"{new DirectoryInfo(folderPath).Name} - {Resources.App_Name}";
} }
@@ -107,21 +98,17 @@ public sealed partial class MainWindowViewModel : ViewModelBase
/// columns and opens the resulting workspace. /// columns and opens the resulting workspace.
/// </summary> /// </summary>
/// <returns>A completed task once initialization has been attempted.</returns> /// <returns>A completed task once initialization has been attempted.</returns>
private Task InitializeCurrentWorkspaceAsync() private Task InitializeCurrentWorkspaceAsync() {
{ if (Content is not NotInitializedPageViewModel page) {
if (Content is not NotInitializedPageViewModel page)
{
return Task.CompletedTask; return Task.CompletedTask;
} }
try try {
{
WorkspaceInitializer.Initialize(page.FolderPath); WorkspaceInitializer.Initialize(page.FolderPath);
WorkspacePreset.AddPresetColumns(page.FolderPath); WorkspacePreset.AddPresetColumns(page.FolderPath);
WorkspacePreset.AddPresetTags(page.FolderPath);
OpenWorkspace(page.FolderPath); OpenWorkspace(page.FolderPath);
} } catch (Exception exception) when (exception is YKanBanException or IOException or UnauthorizedAccessException) {
catch (Exception exception) when (exception is YKanBanException or IOException or UnauthorizedAccessException)
{
// Initialization failed; the page remains so the user can retry. // Initialization failed; the page remains so the user can retry.
Debug.WriteLine(exception); Debug.WriteLine(exception);
} }
@@ -0,0 +1,78 @@
using System.Globalization;
using CommunityToolkit.Mvvm.Input;
using YKanBan.Models;
using YKanBan.ViewModels.Board;
namespace YKanBan.ViewModels.Tags;
/// <summary>
/// One row of the tag manager: a color swatch, the name, the description and the
/// usage count, plus edit and delete actions.
/// </summary>
public sealed partial class TagItemViewModel {
private readonly TagsViewModel _owner;
/// <summary>
/// Initializes the row.
/// </summary>
/// <param name="owner">The owning tag manager.</param>
/// <param name="tag">The tag model.</param>
/// <param name="usageCount">The number of cards using the tag.</param>
public TagItemViewModel(TagsViewModel owner, TagModel tag, long usageCount) {
_owner = owner;
Tag = tag;
Badge = new TagBadgeViewModel(tag);
UsageCount = usageCount;
UsageText = string.Format(
Resources.Culture ?? CultureInfo.CurrentCulture, Resources.Tags_Usage, usageCount);
}
/// <summary>
/// Gets the underlying tag model.
/// </summary>
public TagModel Tag { get; }
/// <summary>
/// Gets the colored badge for the swatch and name.
/// </summary>
public TagBadgeViewModel Badge { get; }
/// <summary>
/// Gets the tag name.
/// </summary>
public string Name => Tag.Name;
/// <summary>
/// Gets the tag description.
/// </summary>
public string Description => Tag.Description;
/// <summary>
/// Gets a value indicating whether the tag has a description.
/// </summary>
public bool HasDescription => Tag.Description.Length > 0;
/// <summary>
/// Gets the number of cards using the tag.
/// </summary>
public long UsageCount { get; }
/// <summary>
/// Gets the localized usage count.
/// </summary>
public string UsageText { get; }
/// <summary>
/// Asks the manager to edit this tag.
/// </summary>
[RelayCommand]
private void Edit() => _ = _owner.RequestEditAsync(this);
/// <summary>
/// Asks the manager to delete this tag.
/// </summary>
[RelayCommand]
private void Delete() => _ = _owner.RequestDeleteAsync(this);
}
+105
View File
@@ -0,0 +1,105 @@
using System.Collections.ObjectModel;
using CommunityToolkit.Mvvm.Input;
using YKanBan.Models;
using YKanBan.Storage.Workspace;
namespace YKanBan.ViewModels.Tags;
/// <summary>
/// The tags tab: a manager for the workspace's tags (create, rename, recolor,
/// re-describe and delete), showing each tag's color, name, description and
/// usage count. Tag changes also refresh the board.
/// </summary>
public sealed partial class TagsViewModel : ViewModelBase {
private readonly WorkspaceRepository _repository;
private readonly Action _boardChanged;
/// <summary>
/// Initializes the manager, loading the current tags.
/// </summary>
/// <param name="repository">The workspace repository.</param>
/// <param name="boardChanged">Invoked after a tag change so the board refreshes.</param>
public TagsViewModel(WorkspaceRepository repository, Action boardChanged) {
_repository = repository;
_boardChanged = boardChanged;
Reload();
}
/// <summary>
/// Gets the workspace repository used for tag access.
/// </summary>
public WorkspaceRepository Repository => _repository;
/// <summary>
/// Gets the tags in id order.
/// </summary>
public ObservableCollection<TagItemViewModel> Tags { get; } = [];
/// <summary>
/// Gets a value indicating whether the workspace has any tags.
/// </summary>
public bool HasTags => Tags.Count > 0;
/// <summary>
/// Gets a value indicating whether the workspace has no tags.
/// </summary>
public bool HasNoTags => Tags.Count == 0;
/// <summary>
/// Gets the interaction that opens the new-tag editor.
/// </summary>
public Interaction<Unit> AddTag { get; } = new();
/// <summary>
/// Gets the interaction that opens the tag editor.
/// </summary>
public Interaction<TagItemViewModel> EditTag { get; } = new();
/// <summary>
/// Gets the interaction that confirms and deletes a tag.
/// </summary>
public Interaction<TagItemViewModel> DeleteTag { get; } = new();
/// <summary>
/// Opens the new-tag editor.
/// </summary>
[RelayCommand]
private Task AddNewTagAsync() => AddTag.Handle(Unit.Value);
/// <summary>
/// Requests the editor for a tag.
/// </summary>
/// <param name="item">The tag to edit.</param>
/// <returns>A task completing after the editor closes.</returns>
public Task RequestEditAsync(TagItemViewModel item) => EditTag.Handle(item);
/// <summary>
/// Requests deletion of a tag.
/// </summary>
/// <param name="item">The tag to delete.</param>
/// <returns>A task completing after confirmation.</returns>
public Task RequestDeleteAsync(TagItemViewModel item) => DeleteTag.Handle(item);
/// <summary>
/// Reloads the tag list from the repository.
/// </summary>
public void Reload() {
Tags.Clear();
foreach ((TagModel tag, long usage) in _repository.GetTagsWithUsage()) {
Tags.Add(new TagItemViewModel(this, tag, usage));
}
OnPropertyChanged(nameof(HasTags));
OnPropertyChanged(nameof(HasNoTags));
}
/// <summary>
/// Reloads the tags and refreshes the board after a tag change.
/// </summary>
public void RefreshAfterChange() {
Reload();
_boardChanged();
}
}
+1 -2
View File
@@ -2,6 +2,5 @@
namespace YKanBan.ViewModels; namespace YKanBan.ViewModels;
public class ViewModelBase : ObservableObject public class ViewModelBase : ObservableObject {
{
} }
+30 -11
View File
@@ -1,34 +1,41 @@
using CommunityToolkit.Mvvm.Input; using CommunityToolkit.Mvvm.Input;
using YKanBan.Services;
using YKanBan.Storage.Workspace; using YKanBan.Storage.Workspace;
using YKanBan.ViewModels.Board;
using YKanBan.ViewModels.Tags;
namespace YKanBan.ViewModels; namespace YKanBan.ViewModels;
/// <summary> /// <summary>
/// The normal workspace view: the top display area (name, path and the export, /// 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 /// settings and about buttons) plus the board and tags tabs.
/// filled in by the board and tag features.
/// </summary> /// </summary>
public sealed partial class WorkspaceViewModel : ViewModelBase public sealed partial class WorkspaceViewModel : ViewModelBase {
{
private readonly Interaction<Unit> _showSettings; private readonly Interaction<Unit> _showSettings;
private readonly Interaction<Unit> _showAbout; private readonly Interaction<Unit> _showAbout;
/// <summary> /// <summary>
/// Initializes the view for an open workspace. /// Initializes the view for an open workspace.
/// </summary> /// </summary>
/// <param name="services">The process composition root.</param>
/// <param name="session">The open workspace session.</param> /// <param name="session">The open workspace session.</param>
/// <param name="showSettings">The interaction that opens the settings dialog.</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="showAbout">The interaction that opens the about dialog.</param>
public WorkspaceViewModel( public WorkspaceViewModel(
AppServices services,
WorkspaceSession session, WorkspaceSession session,
Interaction<Unit> showSettings, Interaction<Unit> showSettings,
Interaction<Unit> showAbout) Interaction<Unit> showAbout) {
{
Session = session; Session = session;
WorkspaceName = new DirectoryInfo(session.FolderPath).Name; WorkspaceName = new DirectoryInfo(session.FolderPath).Name;
WorkspacePath = session.FolderPath; WorkspacePath = session.FolderPath;
_showSettings = showSettings; _showSettings = showSettings;
_showAbout = showAbout; _showAbout = showAbout;
// Both tabs share the same repository; tag changes refresh the board.
Board = new BoardViewModel(services, session);
Tags = new TagsViewModel(session.Repository, Board.Reload);
} }
/// <summary> /// <summary>
@@ -46,6 +53,21 @@ public sealed partial class WorkspaceViewModel : ViewModelBase
/// </summary> /// </summary>
public string WorkspacePath { get; } public string WorkspacePath { get; }
/// <summary>
/// Gets the board tab view model.
/// </summary>
public BoardViewModel Board { get; }
/// <summary>
/// Gets the tags tab view model.
/// </summary>
public TagsViewModel Tags { get; }
/// <summary>
/// Gets the interaction that runs the export flow.
/// </summary>
public Interaction<Unit> Export { get; } = new();
/// <summary> /// <summary>
/// Opens the settings dialog through the registered interaction. /// Opens the settings dialog through the registered interaction.
/// </summary> /// </summary>
@@ -59,11 +81,8 @@ public sealed partial class WorkspaceViewModel : ViewModelBase
private async Task OpenAboutAsync() => await _showAbout.Handle(Unit.Value); private async Task OpenAboutAsync() => await _showAbout.Handle(Unit.Value);
/// <summary> /// <summary>
/// Raised by the export button; the export flow is wired up with the export /// Runs the export flow through the registered interaction.
/// feature.
/// </summary> /// </summary>
[RelayCommand] [RelayCommand]
private static void Export() private async Task RunExportAsync() => await Export.Handle(Unit.Value);
{
}
} }
+126
View File
@@ -0,0 +1,126 @@
<UserControl xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:vm="using:YKanBan.ViewModels.Board"
xmlns:vmBase="using:YKanBan.ViewModels"
xmlns:lang="using:YKanBan"
xmlns:icons="using:IconPacks.Avalonia.Lucide"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d" d:DesignWidth="1000" d:DesignHeight="600"
x:Class="YKanBan.Views.Board.BoardView"
x:DataType="vm:BoardViewModel">
<Grid RowDefinitions="Auto,*">
<!-- Toolbar: search, add column and the combined display options. -->
<Grid Grid.Row="0" Margin="8" ColumnDefinitions="Auto,*,Auto,Auto,Auto,Auto">
<!-- Wrapped in a transparent-border hit area so the tooltip triggers across the whole 16x16 box. -->
<Border Grid.Column="0" Background="Transparent" Padding="2" Margin="0,0,6,0"
VerticalAlignment="Center"
ToolTip.Tip="{Binding FilterStatusText}">
<icons:PackIconLucide Kind="ListFilter" Width="16" Height="16"
Opacity="{Binding FilterIconOpacity}"/>
</Border>
<TextBox Grid.Column="1" Text="{Binding SearchText}" VerticalAlignment="Center"
Watermark="{x:Static lang:Resources.Board_SearchPlaceholder}">
<TextBox.KeyBindings>
<KeyBinding Gesture="Enter" Command="{Binding SearchCommand}"/>
</TextBox.KeyBindings>
</TextBox>
<Button Grid.Column="2" Margin="4,0,0,0" Command="{Binding ClearSearchCommand}"
ToolTip.Tip="{x:Static lang:Resources.Board_ClearSearch}">
<icons:PackIconLucide Kind="X" Width="16" Height="16"/>
</Button>
<Button Grid.Column="3" Margin="4,0,0,0" Command="{Binding SearchCommand}"
ToolTip.Tip="{x:Static lang:Resources.Board_Search}">
<icons:PackIconLucide Kind="Search" Width="16" Height="16"/>
</Button>
<Button Grid.Column="4" Margin="12,0,0,0" Command="{Binding AddNewColumnCommand}">
<StackPanel Orientation="Horizontal" Spacing="6">
<icons:PackIconLucide Kind="Plus" Width="16" Height="16"/>
<TextBlock Text="{x:Static lang:Resources.Board_AddColumn}"/>
</StackPanel>
</Button>
<Button Grid.Column="5" Margin="4,0,0,0">
<StackPanel Orientation="Horizontal" Spacing="6">
<icons:PackIconLucide Kind="SlidersHorizontal" Width="16" Height="16"/>
<TextBlock Text="{x:Static lang:Resources.Board_Display}"/>
</StackPanel>
<Button.Flyout>
<Flyout Placement="BottomEdgeAlignedRight">
<StackPanel Width="280" Spacing="12" Margin="4">
<StackPanel Spacing="4">
<TextBlock Text="{x:Static lang:Resources.Board_ColumnWidth}"/>
<ComboBox ItemsSource="{Binding Display.Presets}"
SelectedItem="{Binding Display.SelectedPreset}"
HorizontalAlignment="Stretch">
<ComboBox.ItemTemplate>
<DataTemplate x:DataType="vmBase:OptionItem">
<TextBlock Text="{Binding Label}"/>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
<StackPanel Orientation="Horizontal" Spacing="8"
IsVisible="{Binding Display.IsCustom}">
<TextBlock Text="{x:Static lang:Resources.WidthDialog_Pixels}"
VerticalAlignment="Center"/>
<NumericUpDown Value="{Binding Display.CustomPixels}"
Minimum="160" Maximum="720" Width="120"/>
</StackPanel>
</StackPanel>
<StackPanel Spacing="4">
<TextBlock Text="{x:Static lang:Resources.Board_SortCard}"/>
<ComboBox ItemsSource="{Binding Display.SortOptions}"
SelectedItem="{Binding Display.SelectedCardSort}"
HorizontalAlignment="Stretch">
<ComboBox.ItemTemplate>
<DataTemplate x:DataType="vmBase:OptionItem">
<TextBlock Text="{Binding Label}"/>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
</StackPanel>
<StackPanel Spacing="4">
<TextBlock Text="{x:Static lang:Resources.Board_SortColumn}"/>
<ComboBox ItemsSource="{Binding Display.SortOptions}"
SelectedItem="{Binding Display.SelectedColumnSort}"
HorizontalAlignment="Stretch">
<ComboBox.ItemTemplate>
<DataTemplate x:DataType="vmBase:OptionItem">
<TextBlock Text="{Binding Label}"/>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
</StackPanel>
</StackPanel>
</Flyout>
</Button.Flyout>
</Button>
</Grid>
<!-- Board surface: columns horizontally, each scrolling its cards vertically. -->
<ScrollViewer Grid.Row="1" HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Disabled">
<ItemsControl ItemsSource="{Binding Columns}" Margin="8">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal" Spacing="12"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
</ScrollViewer>
<TextBlock Grid.Row="1" Text="{x:Static lang:Resources.Board_NoColumns}"
IsVisible="{Binding HasNoColumns}"
HorizontalAlignment="Center" VerticalAlignment="Center" Opacity="0.6"/>
</Grid>
</UserControl>
+147
View File
@@ -0,0 +1,147 @@
using Avalonia.Controls;
using YKanBan.ViewModels.Board;
using YKanBan.ViewModels.Dialogs;
using YKanBan.Views.Dialogs;
namespace YKanBan.Views.Board;
public partial class BoardView : UserControl {
private bool _registered;
public BoardView() {
InitializeComponent();
}
protected override void OnDataContextChanged(EventArgs e) {
base.OnDataContextChanged(e);
if (DataContext is BoardViewModel board && !_registered) {
_registered = true;
board.AddColumn.RegisterHandler(_ => EditColumnAsync(board, null));
board.EditColumn.RegisterHandler(column => EditColumnAsync(board, column));
board.DeleteColumn.RegisterHandler(column => DeleteColumnAsync(board, column));
board.AddCard.RegisterHandler(column => EditCardAsync(board, column, null));
board.EditCard.RegisterHandler(card => EditCardAsync(board, null, card));
board.DeleteCard.RegisterHandler(card => DeleteCardAsync(board, card));
board.MoveCard.RegisterHandler(card => MoveCardAsync(board, card));
board.ShowSearchError.RegisterHandler(ShowSearchErrorAsync);
}
}
/// <summary>
/// Gets the window that owns this board, used as the dialog owner.
/// </summary>
private Window? OwningWindow => TopLevel.GetTopLevel(this) as Window;
/// <summary>
/// Shows the add/edit column dialog and reloads on success.
/// </summary>
private async Task EditColumnAsync(BoardViewModel board, ColumnViewModel? column) {
if (OwningWindow is not Window owner) {
return;
}
var dialog = new ColumnEditorDialog {
DataContext = new ColumnEditorViewModel(board.Repository, column?.Model),
};
if (await dialog.ShowDialog<bool>(owner)) {
board.Reload();
}
}
/// <summary>
/// Confirms and deletes a column, then reloads.
/// </summary>
private async Task DeleteColumnAsync(BoardViewModel board, ColumnViewModel column) {
if (OwningWindow is not Window owner) {
return;
}
bool confirmed = true;
if (board.Config.Confirmations.DeleteColumn) {
var dialog = new DeleteColumnConfirmDialog {
DataContext = new DeleteColumnConfirmViewModel(column.Title, column.CardCount),
};
confirmed = await dialog.ShowDialog<bool>(owner);
}
if (!confirmed) {
return;
}
board.Repository.DeleteColumn(column.Id);
board.Reload();
}
/// <summary>
/// Shows the add/edit card dialog and reloads on success.
/// </summary>
private async Task EditCardAsync(BoardViewModel board, ColumnViewModel? column, CardViewModel? card) {
if (OwningWindow is not Window owner) {
return;
}
long columnId = card?.ColumnId ?? column!.Id;
var dialog = new CardEditorDialog {
DataContext = new CardEditorViewModel(board.Repository, columnId, card?.Model),
};
if (await dialog.ShowDialog<bool>(owner)) {
board.Reload();
}
}
/// <summary>
/// Confirms and deletes a card, then reloads.
/// </summary>
private async Task DeleteCardAsync(BoardViewModel board, CardViewModel card) {
if (OwningWindow is not Window owner) {
return;
}
bool confirmed = true;
if (board.Config.Confirmations.DeleteCard) {
var dialog = new DeleteCardConfirmDialog {
DataContext = new DeleteCardConfirmViewModel(card.Id),
};
confirmed = await dialog.ShowDialog<bool>(owner);
}
if (!confirmed) {
return;
}
board.Repository.DeleteCard(card.Id);
board.Reload();
}
/// <summary>
/// Shows the move-card dialog and reloads when a destination is chosen.
/// </summary>
private async Task MoveCardAsync(BoardViewModel board, CardViewModel card) {
if (OwningWindow is not Window owner) {
return;
}
var dialog = new MoveCardDialog {
DataContext = new MoveCardViewModel(board.Repository.GetColumns(), card.ColumnId),
};
if (await dialog.ShowDialog<long?>(owner) is long targetColumnId) {
board.Repository.MoveCard(card.Id, targetColumnId);
board.Reload();
}
}
/// <summary>
/// Shows the search syntax error dialog.
/// </summary>
private async Task ShowSearchErrorAsync(string detail) {
if (OwningWindow is not Window owner) {
return;
}
var dialog = new SearchErrorDialog {
DataContext = new SearchErrorViewModel(detail),
};
await dialog.ShowDialog(owner);
}
}
+63
View File
@@ -0,0 +1,63 @@
<UserControl xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:vm="using:YKanBan.ViewModels.Board"
xmlns:lang="using:YKanBan"
xmlns:icons="using:IconPacks.Avalonia.Lucide"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d" d:DesignWidth="320" d:DesignHeight="120"
x:Class="YKanBan.Views.Board.CardView"
x:DataType="vm:CardViewModel">
<Border Background="{DynamicResource CardBackgroundBrush}"
BorderBrush="{DynamicResource CardBorderBrush}"
BorderThickness="1" CornerRadius="6" Padding="8"
Cursor="Hand" Tapped="OnCardTapped">
<Grid RowDefinitions="Auto,Auto,Auto">
<!-- Row 1: id, title and the corner menu. -->
<Grid Grid.Row="0" ColumnDefinitions="Auto,*,Auto">
<TextBlock Grid.Column="0" Text="{Binding IdText}" FontWeight="Bold" VerticalAlignment="Center"/>
<TextBlock Grid.Column="1" Text="{Binding TitleText}" IsVisible="{Binding HasTitle}"
VerticalAlignment="Center" Margin="4,0"
TextWrapping="NoWrap" TextTrimming="CharacterEllipsis"
ToolTip.Tip="{Binding TitleText}"/>
<Button Grid.Column="2" Padding="4,2" VerticalAlignment="Center"
Tapped="OnMenuButtonTapped">
<icons:PackIconLucide Kind="EllipsisVertical" Width="16" Height="16"/>
<Button.Flyout>
<MenuFlyout>
<MenuItem Header="{x:Static lang:Resources.Card_Move}" Command="{Binding MoveCommand}"/>
<MenuItem Header="{x:Static lang:Resources.Card_Delete}" Command="{Binding DeleteCommand}"/>
</MenuFlyout>
</Button.Flyout>
</Button>
</Grid>
<!-- Row 2: content preview. -->
<TextBlock Grid.Row="1" Text="{Binding PreviewContent}" IsVisible="{Binding HasContent}"
TextWrapping="Wrap" FontSize="12" Opacity="0.85" Margin="0,4,0,0"/>
<!-- Row 3: tag badges. -->
<ItemsControl Grid.Row="2" ItemsSource="{Binding TagBadges}" IsVisible="{Binding HasTags}"
Margin="0,4,0,0">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate x:DataType="vm:TagBadgeViewModel">
<Border Background="{Binding Background}" CornerRadius="8"
Padding="6,2" Margin="0,0,4,4"
ToolTip.Tip="{Binding ToolTipText}">
<TextBlock Text="{Binding Name}" Foreground="{Binding Foreground}" FontSize="11"/>
</Border>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Grid>
</Border>
</UserControl>
+26
View File
@@ -0,0 +1,26 @@
using Avalonia.Controls;
using Avalonia.Input;
using YKanBan.ViewModels.Board;
namespace YKanBan.Views.Board;
public partial class CardView : UserControl {
public CardView() {
InitializeComponent();
}
/// <summary>
/// Clicking the card body opens the card editor.
/// </summary>
private void OnCardTapped(object? sender, TappedEventArgs e) {
if (DataContext is CardViewModel card) {
card.EditCommand.Execute(null);
}
}
/// <summary>
/// Stops the corner menu button's tap from bubbling to the card body.
/// </summary>
private void OnMenuButtonTapped(object? sender, TappedEventArgs e) => e.Handled = true;
}
+55
View File
@@ -0,0 +1,55 @@
<UserControl xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:vm="using:YKanBan.ViewModels.Board"
xmlns:lang="using:YKanBan"
xmlns:icons="using:IconPacks.Avalonia.Lucide"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d" d:DesignWidth="320" d:DesignHeight="600"
x:Class="YKanBan.Views.Board.ColumnView"
x:DataType="vm:ColumnViewModel">
<Border Width="{Binding Width}" MinWidth="160" MaxWidth="720"
Background="{DynamicResource BoardColumnBackgroundBrush}"
BorderBrush="{DynamicResource BoardColumnBorderBrush}"
BorderThickness="1" CornerRadius="8" VerticalAlignment="Stretch">
<Grid RowDefinitions="Auto,*" Margin="10">
<Grid Grid.Row="0" ColumnDefinitions="*,Auto,Auto">
<StackPanel Grid.Column="0" Orientation="Horizontal" Spacing="6" VerticalAlignment="Center">
<TextBlock Text="{Binding Title}" FontWeight="SemiBold"
TextTrimming="CharacterEllipsis" ToolTip.Tip="{Binding ToolTipText}"/>
<TextBlock Text="{Binding CardCount}" Opacity="0.6" VerticalAlignment="Center"/>
</StackPanel>
<Button Grid.Column="1" Margin="4,0,0,0" Padding="4,2"
Command="{Binding AddCardCommand}"
ToolTip.Tip="{x:Static lang:Resources.Column_AddCard}">
<icons:PackIconLucide Kind="Plus" Width="16" Height="16"/>
</Button>
<Button Grid.Column="2" Margin="2,0,0,0" Padding="4,2">
<icons:PackIconLucide Kind="EllipsisVertical" Width="16" Height="16"/>
<Button.Flyout>
<MenuFlyout>
<MenuItem Header="{x:Static lang:Resources.Column_Edit}" Command="{Binding EditCommand}"/>
<MenuItem Header="{x:Static lang:Resources.Column_Delete}" Command="{Binding DeleteCommand}"/>
</MenuFlyout>
</Button.Flyout>
</Button>
</Grid>
<ScrollViewer Grid.Row="1" VerticalScrollBarVisibility="Auto" Margin="0,8,0,0">
<ItemsControl ItemsSource="{Binding Cards}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Spacing="8"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
</ScrollViewer>
</Grid>
</Border>
</UserControl>
+9
View File
@@ -0,0 +1,9 @@
using Avalonia.Controls;
namespace YKanBan.Views.Board;
public partial class ColumnView : UserControl {
public ColumnView() {
InitializeComponent();
}
}
+5 -5
View File
@@ -3,13 +3,13 @@ using Avalonia.Interactivity;
namespace YKanBan.Views.Dialogs; namespace YKanBan.Views.Dialogs;
public partial class AboutDialog : Window public partial class AboutDialog : Window {
{ public AboutDialog() {
public AboutDialog()
{
InitializeComponent(); InitializeComponent();
} }
/// <summary>Closes the dialog.</summary> /// <summary>
/// Closes the dialog.
/// </summary>
private void OnCloseClick(object? sender, RoutedEventArgs e) => Close(); private void OnCloseClick(object? sender, RoutedEventArgs e) => Close();
} }
@@ -0,0 +1,74 @@
<Window xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:vm="using:YKanBan.ViewModels.Dialogs"
xmlns:lang="using:YKanBan"
xmlns:icons="using:IconPacks.Avalonia.Lucide"
xmlns:conv="using:Avalonia.Data.Converters"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d" d:DesignWidth="520" d:DesignHeight="560"
x:Class="YKanBan.Views.Dialogs.CardEditorDialog"
x:DataType="vm:CardEditorViewModel"
Title="{Binding WindowTitle}"
Width="520" Height="560" MinWidth="520" MinHeight="560" CanResize="True"
WindowStartupLocation="CenterOwner"
ShowInTaskbar="False">
<Grid RowDefinitions="*,Auto" Margin="20">
<ScrollViewer Grid.Row="0" VerticalScrollBarVisibility="Auto">
<StackPanel Spacing="6">
<TextBlock Text="{x:Static lang:Resources.CardDialog_Title}"/>
<TextBox Text="{Binding Title}"/>
<TextBlock Text="{x:Static lang:Resources.CardDialog_Content}" Margin="0,6,0,0"/>
<TextBox Text="{Binding Content}" AcceptsReturn="True" TextWrapping="Wrap"
VerticalContentAlignment="Top" Height="160"/>
<TextBlock Text="{x:Static lang:Resources.CardDialog_Tags}" Margin="0,6,0,0"/>
<ItemsControl ItemsSource="{Binding AssignedTags}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate x:DataType="vm:AssignedTagViewModel">
<Border Background="{Binding Background}" CornerRadius="8"
Padding="6,2" Margin="0,0,4,4">
<StackPanel Orientation="Horizontal" Spacing="4">
<TextBlock Text="{Binding Name}" Foreground="{Binding Foreground}"
FontSize="11" VerticalAlignment="Center"/>
<Button Command="{Binding RemoveCommand}" Padding="0"
Background="Transparent" BorderThickness="0">
<icons:PackIconLucide Kind="X" Width="10" Height="10"
Foreground="{Binding Foreground}"/>
</Button>
</StackPanel>
</Border>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
<Button Content="{x:Static lang:Resources.CardDialog_AddTag}"
Command="{Binding AddTagCommand}" HorizontalAlignment="Left"/>
<StackPanel Spacing="2" IsVisible="{Binding !IsNew}" Opacity="0.7" Margin="0,8,0,0">
<TextBlock Text="{Binding IdLine}"/>
<TextBlock Text="{Binding CreatedLine}"/>
<TextBlock Text="{Binding ModifiedLine}"/>
</StackPanel>
<TextBlock Text="{Binding ErrorMessage}"
IsVisible="{Binding ErrorMessage, Converter={x:Static conv:ObjectConverters.IsNotNull}}"
Foreground="{DynamicResource ErrorTextBrush}" TextWrapping="Wrap" Margin="0,4,0,0"/>
</StackPanel>
</ScrollViewer>
<StackPanel Grid.Row="1" Orientation="Horizontal" HorizontalAlignment="Right"
Spacing="8" Margin="0,16,0,0">
<Button Content="{x:Static lang:Resources.Common_Ok}" Click="OnOkClick" MinWidth="90" IsDefault="True"/>
<Button Content="{x:Static lang:Resources.Common_Cancel}" Click="OnCancelClick" MinWidth="90"
IsCancel="True"/>
</StackPanel>
</Grid>
</Window>
@@ -0,0 +1,97 @@
using Avalonia.Controls;
using Avalonia.Interactivity;
using Avalonia.Threading;
using YKanBan.Models;
using YKanBan.ViewModels;
using YKanBan.ViewModels.Dialogs;
namespace YKanBan.Views.Dialogs;
public partial class CardEditorDialog : Window {
private bool _allowClose;
public CardEditorDialog() {
InitializeComponent();
}
protected override void OnDataContextChanged(EventArgs e) {
base.OnDataContextChanged(e);
if (DataContext is CardEditorViewModel viewModel) {
viewModel.ShowTagPicker.RegisterHandler(ShowTagPickerAsync);
}
}
/// <summary>
/// Shows the nested tag picker, owned by this dialog.
/// </summary>
private async Task<TagModel?> ShowTagPickerAsync(Unit input) {
if (DataContext is not CardEditorViewModel viewModel) {
return null;
}
var dialog = new TagPickerDialog {
DataContext = new TagPickerViewModel(
viewModel.Repository,
viewModel.AssignedTags.Select(row => row.Tag.Id).ToList()),
};
return await dialog.ShowDialog<TagModel?>(this);
}
/// <summary>
/// Writes the card and closes when accepted.
/// </summary>
private void OnOkClick(object? sender, RoutedEventArgs e) {
if (DataContext is CardEditorViewModel viewModel && viewModel.TryAccept()) {
_allowClose = true;
Close(true);
}
}
/// <summary>
/// Requests a close, confirming the discard first when needed.
/// </summary>
private void OnCancelClick(object? sender, RoutedEventArgs e) => _ = RequestCloseAsync();
/// <summary>
/// Intercepts the window close button to run the discard confirmation.
/// </summary>
protected override void OnClosing(WindowClosingEventArgs e) {
base.OnClosing(e);
if (_allowClose) {
return;
}
if (HasUnsavedChanges && DiscardConfirmEnabled) {
e.Cancel = true;
Dispatcher.UIThread.Post(() => _ = RequestCloseAsync());
} else {
_allowClose = true;
}
}
/// <summary>
/// Confirms the discard and closes, or stays open when declined.
/// </summary>
private async Task RequestCloseAsync() {
if (HasUnsavedChanges && DiscardConfirmEnabled) {
var dialog = new DiscardEditConfirmDialog { DataContext = new DiscardEditConfirmViewModel() };
if (!await dialog.ShowDialog<bool>(this)) {
return;
}
}
_allowClose = true;
Close(false);
}
/// <summary>
/// Gets whether the editor has unsaved changes.
/// </summary>
private bool HasUnsavedChanges => DataContext is CardEditorViewModel viewModel && viewModel.HasChanges;
/// <summary>
/// Gets whether the discard confirmation setting is enabled.
/// </summary>
private static bool DiscardConfirmEnabled => App.Services?.Config.Confirmations.DiscardEdit == true;
}
@@ -0,0 +1,36 @@
<Window xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:vm="using:YKanBan.ViewModels.Dialogs"
xmlns:lang="using:YKanBan"
xmlns:conv="using:Avalonia.Data.Converters"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d" d:DesignWidth="420" d:DesignHeight="300"
x:Class="YKanBan.Views.Dialogs.ColumnEditorDialog"
x:DataType="vm:ColumnEditorViewModel"
Title="{Binding WindowTitle}"
Width="420" Height="300" MinWidth="420" MinHeight="300" CanResize="True"
WindowStartupLocation="CenterOwner"
ShowInTaskbar="False">
<Grid RowDefinitions="*,Auto" Margin="20">
<StackPanel Grid.Row="0" Spacing="6">
<TextBlock Text="{x:Static lang:Resources.ColumnDialog_Title}"/>
<TextBox Text="{Binding Title}"/>
<TextBlock Text="{x:Static lang:Resources.ColumnDialog_Description}" Margin="0,6,0,0"/>
<TextBox Text="{Binding Description}" AcceptsReturn="True" TextWrapping="Wrap"
VerticalContentAlignment="Top" Height="80"/>
<TextBlock Text="{Binding ErrorMessage}"
IsVisible="{Binding ErrorMessage, Converter={x:Static conv:ObjectConverters.IsNotNull}}"
Foreground="{DynamicResource ErrorTextBrush}" TextWrapping="Wrap" Margin="0,4,0,0"/>
</StackPanel>
<StackPanel Grid.Row="1" Orientation="Horizontal" HorizontalAlignment="Right"
Spacing="8" Margin="0,16,0,0">
<Button Content="{x:Static lang:Resources.Common_Ok}" Click="OnOkClick" MinWidth="90" IsDefault="True"/>
<Button Content="{x:Static lang:Resources.Common_Cancel}" Click="OnCancelClick" MinWidth="90" IsCancel="True"/>
</StackPanel>
</Grid>
</Window>
@@ -0,0 +1,26 @@
using Avalonia.Controls;
using Avalonia.Interactivity;
using YKanBan.ViewModels.Dialogs;
namespace YKanBan.Views.Dialogs;
public partial class ColumnEditorDialog : Window {
public ColumnEditorDialog() {
InitializeComponent();
}
/// <summary>
/// Writes the column and closes when accepted.
/// </summary>
private void OnOkClick(object? sender, RoutedEventArgs e) {
if (DataContext is ColumnEditorViewModel viewModel && viewModel.TryAccept()) {
Close(true);
}
}
/// <summary>
/// Closes without writing.
/// </summary>
private void OnCancelClick(object? sender, RoutedEventArgs e) => Close(false);
}
@@ -0,0 +1,24 @@
<Window xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:vm="using:YKanBan.ViewModels.Dialogs"
xmlns:lang="using:YKanBan"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d" d:DesignWidth="420" d:DesignHeight="200"
x:Class="YKanBan.Views.Dialogs.DeleteCardConfirmDialog"
x:DataType="vm:DeleteCardConfirmViewModel"
Title="{x:Static lang:Resources.Confirm_DeleteCard_Title}"
Width="420" Height="200" MinWidth="420" MinHeight="200" CanResize="True"
WindowStartupLocation="CenterOwner"
ShowInTaskbar="False">
<Grid RowDefinitions="*,Auto" Margin="20">
<TextBlock Grid.Row="0" Text="{Binding Message}" TextWrapping="Wrap" VerticalAlignment="Top"/>
<StackPanel Grid.Row="1" Orientation="Horizontal" HorizontalAlignment="Right" Spacing="8">
<Button Content="{x:Static lang:Resources.Common_Delete}" Click="OnConfirmClick"
MinWidth="90" IsDefault="True"/>
<Button Content="{x:Static lang:Resources.Common_Cancel}" Click="OnCancelClick"
MinWidth="90" IsCancel="True"/>
</StackPanel>
</Grid>
</Window>
@@ -0,0 +1,20 @@
using Avalonia.Controls;
using Avalonia.Interactivity;
namespace YKanBan.Views.Dialogs;
public partial class DeleteCardConfirmDialog : Window {
public DeleteCardConfirmDialog() {
InitializeComponent();
}
/// <summary>
/// Confirms the deletion.
/// </summary>
private void OnConfirmClick(object? sender, RoutedEventArgs e) => Close(true);
/// <summary>
/// Cancels the deletion.
/// </summary>
private void OnCancelClick(object? sender, RoutedEventArgs e) => Close(false);
}
@@ -0,0 +1,24 @@
<Window xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:vm="using:YKanBan.ViewModels.Dialogs"
xmlns:lang="using:YKanBan"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d" d:DesignWidth="420" d:DesignHeight="200"
x:Class="YKanBan.Views.Dialogs.DeleteColumnConfirmDialog"
x:DataType="vm:DeleteColumnConfirmViewModel"
Title="{x:Static lang:Resources.Confirm_DeleteColumn_Title}"
Width="420" Height="200" MinWidth="420" MinHeight="200" CanResize="True"
WindowStartupLocation="CenterOwner"
ShowInTaskbar="False">
<Grid RowDefinitions="*,Auto" Margin="20">
<TextBlock Grid.Row="0" Text="{Binding Message}" TextWrapping="Wrap" VerticalAlignment="Top"/>
<StackPanel Grid.Row="1" Orientation="Horizontal" HorizontalAlignment="Right" Spacing="8">
<Button Content="{x:Static lang:Resources.Common_Delete}" Click="OnConfirmClick"
MinWidth="90" IsDefault="True"/>
<Button Content="{x:Static lang:Resources.Common_Cancel}" Click="OnCancelClick"
MinWidth="90" IsCancel="True"/>
</StackPanel>
</Grid>
</Window>
@@ -0,0 +1,20 @@
using Avalonia.Controls;
using Avalonia.Interactivity;
namespace YKanBan.Views.Dialogs;
public partial class DeleteColumnConfirmDialog : Window {
public DeleteColumnConfirmDialog() {
InitializeComponent();
}
/// <summary>
/// Confirms the deletion.
/// </summary>
private void OnConfirmClick(object? sender, RoutedEventArgs e) => Close(true);
/// <summary>
/// Cancels the deletion.
/// </summary>
private void OnCancelClick(object? sender, RoutedEventArgs e) => Close(false);
}
@@ -0,0 +1,24 @@
<Window xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:vm="using:YKanBan.ViewModels.Dialogs"
xmlns:lang="using:YKanBan"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d" d:DesignWidth="420" d:DesignHeight="200"
x:Class="YKanBan.Views.Dialogs.DeleteTagConfirmDialog"
x:DataType="vm:DeleteTagConfirmViewModel"
Title="{x:Static lang:Resources.DeleteTag_Confirm_Title}"
Width="420" Height="200" MinWidth="420" MinHeight="200" CanResize="True"
WindowStartupLocation="CenterOwner"
ShowInTaskbar="False">
<Grid RowDefinitions="*,Auto" Margin="20">
<TextBlock Grid.Row="0" Text="{Binding Message}" TextWrapping="Wrap" VerticalAlignment="Top"/>
<StackPanel Grid.Row="1" Orientation="Horizontal" HorizontalAlignment="Right" Spacing="8">
<Button Content="{x:Static lang:Resources.Common_Delete}" Click="OnConfirmClick"
MinWidth="90" IsDefault="True"/>
<Button Content="{x:Static lang:Resources.Common_Cancel}" Click="OnCancelClick"
MinWidth="90" IsCancel="True"/>
</StackPanel>
</Grid>
</Window>
@@ -0,0 +1,20 @@
using Avalonia.Controls;
using Avalonia.Interactivity;
namespace YKanBan.Views.Dialogs;
public partial class DeleteTagConfirmDialog : Window {
public DeleteTagConfirmDialog() {
InitializeComponent();
}
/// <summary>
/// Confirms the deletion.
/// </summary>
private void OnConfirmClick(object? sender, RoutedEventArgs e) => Close(true);
/// <summary>
/// Cancels the deletion.
/// </summary>
private void OnCancelClick(object? sender, RoutedEventArgs e) => Close(false);
}
@@ -0,0 +1,24 @@
<Window xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:vm="using:YKanBan.ViewModels.Dialogs"
xmlns:lang="using:YKanBan"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d" d:DesignWidth="420" d:DesignHeight="200"
x:Class="YKanBan.Views.Dialogs.DiscardEditConfirmDialog"
x:DataType="vm:DiscardEditConfirmViewModel"
Title="{x:Static lang:Resources.Confirm_Discard_Title}"
Width="420" Height="200" MinWidth="420" MinHeight="200" CanResize="True"
WindowStartupLocation="CenterOwner"
ShowInTaskbar="False">
<Grid RowDefinitions="*,Auto" Margin="20">
<TextBlock Grid.Row="0" Text="{Binding Message}" TextWrapping="Wrap" VerticalAlignment="Top"/>
<StackPanel Grid.Row="1" Orientation="Horizontal" HorizontalAlignment="Right" Spacing="8">
<Button Content="{x:Static lang:Resources.Common_Ok}" Click="OnConfirmClick"
MinWidth="90" IsDefault="True"/>
<Button Content="{x:Static lang:Resources.Common_Cancel}" Click="OnCancelClick"
MinWidth="90" IsCancel="True"/>
</StackPanel>
</Grid>
</Window>
@@ -0,0 +1,20 @@
using Avalonia.Controls;
using Avalonia.Interactivity;
namespace YKanBan.Views.Dialogs;
public partial class DiscardEditConfirmDialog : Window {
public DiscardEditConfirmDialog() {
InitializeComponent();
}
/// <summary>
/// Confirms discarding the changes.
/// </summary>
private void OnConfirmClick(object? sender, RoutedEventArgs e) => Close(true);
/// <summary>
/// Keeps editing.
/// </summary>
private void OnCancelClick(object? sender, RoutedEventArgs e) => Close(false);
}
@@ -0,0 +1,21 @@
<Window xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:vm="using:YKanBan.ViewModels.Dialogs"
xmlns:lang="using:YKanBan"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d" d:DesignWidth="460" d:DesignHeight="200"
x:Class="YKanBan.Views.Dialogs.ExportDoneDialog"
x:DataType="vm:ExportDoneViewModel"
Title="{x:Static lang:Resources.Export_Done_Title}"
Width="460" Height="200" MinWidth="460" MinHeight="200" CanResize="True"
WindowStartupLocation="CenterOwner"
ShowInTaskbar="False">
<Grid RowDefinitions="*,Auto" Margin="20">
<TextBlock Grid.Row="0" Text="{Binding Message}" TextWrapping="Wrap" VerticalAlignment="Top"/>
<Button Grid.Row="1" Content="{x:Static lang:Resources.Common_Ok}"
Click="OnOkClick" HorizontalAlignment="Right" MinWidth="90"
IsDefault="True" IsCancel="True"/>
</Grid>
</Window>
@@ -0,0 +1,15 @@
using Avalonia.Controls;
using Avalonia.Interactivity;
namespace YKanBan.Views.Dialogs;
public partial class ExportDoneDialog : Window {
public ExportDoneDialog() {
InitializeComponent();
}
/// <summary>
/// Closes the dialog.
/// </summary>
private void OnOkClick(object? sender, RoutedEventArgs e) => Close();
}
@@ -0,0 +1,39 @@
<Window xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:vm="using:YKanBan.ViewModels.Dialogs"
xmlns:vmBase="using:YKanBan.ViewModels"
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="380" d:DesignHeight="200"
x:Class="YKanBan.Views.Dialogs.MoveCardDialog"
x:DataType="vm:MoveCardViewModel"
Title="{x:Static lang:Resources.MoveDialog_Title}"
Width="380" Height="200" MinWidth="380" MinHeight="200" CanResize="True"
WindowStartupLocation="CenterOwner"
ShowInTaskbar="False">
<Grid RowDefinitions="*,Auto" Margin="20">
<StackPanel Grid.Row="0" Spacing="6">
<TextBlock Text="{x:Static lang:Resources.MoveDialog_Target}"/>
<ComboBox ItemsSource="{Binding Targets}" SelectedItem="{Binding SelectedTarget}"
HorizontalAlignment="Stretch">
<ComboBox.ItemTemplate>
<DataTemplate x:DataType="vmBase:OptionItem">
<TextBlock Text="{Binding Label}"/>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
<TextBlock Text="{x:Static lang:Resources.MoveDialog_NoTargets}"
IsVisible="{Binding !CanMove}" Opacity="0.7" TextWrapping="Wrap"/>
</StackPanel>
<StackPanel Grid.Row="1" Orientation="Horizontal" HorizontalAlignment="Right"
Spacing="8" Margin="0,16,0,0">
<Button Content="{x:Static lang:Resources.Common_Ok}" Click="OnOkClick"
MinWidth="90" IsDefault="True" IsEnabled="{Binding CanMove}"/>
<Button Content="{x:Static lang:Resources.Common_Cancel}" Click="OnCancelClick"
MinWidth="90" IsCancel="True"/>
</StackPanel>
</Grid>
</Window>
Loaded 100 of 119 files, more files were not shown because too many files have changed in this diff. Show more