feat(themes): edit and restore persistent document themes

Refs #7

Co-Authored-By: Codex (GPT-6) <noreply@openai.com>
Signed-off-by: James Maes <jmaes@dmdbrands.com>
This commit is contained in:
James MaesandCodex committed 2026-10-10 20:44:51 -05:00
1 parent 77dd04da96
commit 30ca0943c0
14 files changed
+415 -88

No files matched your search

+2 -1
View File
@@ -1,6 +1,6 @@
# MarkdownViewr
> In development: a Windows counterpart to [Darin's markdownViewr](https://github.com/darinkelkhoff/markdownViewr), built with AppKit. The first reader implementation opens Markdown, renders GFM and supports manual and automatic reload. The 20 original document themes are implemented; user-theme editing, navigation and printing remain in development; hosted automatic-reload acceptance is pending. See [the feature plan](docs/PRODUCT.md) and [development tasks](docs/TODO.md). No Windows release is available yet.
> In development: a Windows counterpart to [Darin's markdownViewr](https://github.com/darinkelkhoff/markdownViewr), built with AppKit. The first reader implementation opens Markdown, renders GFM and supports manual and automatic reload. The 20 original document themes are implemented; user-theme editing is implemented with acceptance pending; navigation and printing remain in development. Hosted reader/reload and both installed update channels pass. See [the feature plan](docs/PRODUCT.md) and [development tasks](docs/TODO.md). No Windows release is available yet.
A Windows Markdown viewer with live reload, themes and document navigation.
@@ -32,6 +32,7 @@ Prerelease tags (`v1.2.3-beta.1`) publish to the `dev` channel
- **Live reload:** saves automatically refresh the document, including replacement saves. Deletion keeps the last version visible until the file is restored. The relative reading position is preserved.
- **File → Reload:** reread the current file manually. Local images stay within the document folder; remote images and authored scripts/styles are blocked.
- **View → Document theme:** choose one of Darin's 20 built-in palettes. The saved document palette is independent of the Windows shell theme; changing it retains the reading position.
- **View → Edit document theme:** edit colors, code font/size and custom CSS. Keep its name to override a built-in, or enter a new name to create a custom theme. Invalid input keeps the editor open. **Restore built-in themes** removes built-in edits after confirmation and keeps separately named custom themes.
- **View:** choose the light, dark, or system shell theme; turn the startup splash and the
startup update check on or off. Choices are saved immediately.
- **Help → Activity log:** a live view of the app's log, with an errors-only filter and a
+1 -1
View File
@@ -2,7 +2,7 @@
Build a Windows counterpart to [Darin Kelkhoff's markdownViewr](https://github.com/darinkelkhoff/markdownViewr), using the KofTwentyTwo AppKit foundations and standards. The agreed display name is MarkdownViewr, repository MarkdownViewr.Windows, and permanent application ID markdownviewr-windows.
The first reader implementation opens Markdown with a Windows picker or literal launch argument, renders sanitized GFM and supports bounded local images, manual reload and automatic saves with relative scroll preservation. The original 20 document themes and persistent palette selection are implemented. First-reader hosted UI acceptance passed; the new live-reload scenarios await hosted acceptance. The full feature list below remains the target; the first reader is not a completed port.
The first reader implementation opens Markdown with a Windows picker or literal launch argument, renders sanitized GFM and supports bounded local images, manual reload and automatic saves with relative scroll preservation. The original 20 document themes and persistent palette selection are implemented. Hosted reader/live-reload/theme selection and both installed update channels passed on 77dd04d. Editable custom themes, color/code-font/CSS controls and restoration are implemented; their new dialog/browser acceptance is pending. The full feature list below remains the target; the first reader is not a completed port.
## Reference and feature scope
+43 -74
View File
@@ -2,87 +2,56 @@
Updated: 2026-10-10
## Live reload milestone
## Active work
Active project: MarkdownViewr.Windows, feat/windows-viewer, draft PR #3.
Owner approved MarkdownViewr / MarkdownViewr.Windows / markdownviewr-windows.
The goal remains the full Windows counterpart to Darin's markdownViewr using AppKit.
MarkdownViewr.Windows is the full Windows counterpart to Darin's markdownViewr,
using published AppKit 0.1.0. Approved identity: MarkdownViewr / MarkdownViewr.Windows /
markdownviewr-windows. Topic feat/windows-viewer, draft PR #3; do not shrink PRODUCT.md scope.
First reader commit f1756d21ede53e95a7ff5ef8bd1490ef9495cb25 is published. Its hosted
CI 38098965780 fully passed: build/test, format, 13 actual native/UI tests and both
installed update channels. CodeQL 38098965738 and security 38098965817 also passed.
Scripts 38098965365 failed inside PSScriptAnalyzer 1.25.0 with a null-reference engine
exception, tracked in #5. No scripts/settings/workflow were changed; no retry or
suppression. The initial scripts run 38097167189 is terminal cancelled, not live.
Published head 77dd04da96b75938a1c1d38c8bebe4851c11a011 completed CI 38102249889 SUCCESS:
build/test, format, 26 native/UI tests, published 26/26 and installed stable/dev 25/25
each, with no skips. Four byte gates verified 536 files in both Velopack payloads;
AppKit update probes applied/restarted within both channels. These are synthetic test
packages, not signed production releases. CodeQL 38102249846/security 38102249838 passed.
Scripts 38102249407 failed inside unchanged PSScriptAnalyzer 1.25.0; issue #5 remains open.
No rules suppressed or failed runs restarted. Local baseline all 13 scripts passed;
this demonstrates intermittent behavior, not an engine fix.
Current next implementation adds a directory watcher with 350 ms debounce. It
survives atomic replacement, rename-away and deletion/recreation. Missing files keep
the last displayed snapshot; brief editor locks get bounded retries. Watchers dispose
on close and ignore stale selected-document callbacks. A core load scheduler coalesces
reloads while preserving picker selections and refreshes after a failed new open. Scroll capture/restore matches
Darin's relative scroll behavior when document height changes. Authored scripts and
native messaging stay disabled; fixed native queries check the current document URI,
and results are validated finite fractions before numeric-only restoration.
## Reader and theme evidence
Local evidence: zero-warning solution build; 82 core tests, zero skipped, 100% core
line coverage; 13 native filesystem/watcher tests passed, including loaded-file handle release and the
actual FileNotFoundException after deletion. Browser replacement,
deletion/recreation, editor lock, relative-scroll and remote-image denial tests have
been added but not run locally. Desktop reservation remains unanswered; do not drive
this desktop without availability. Reload head 09d14e6 hosted UI/published acceptance reproduced a deletion-status
timeout in both builds: 23 of 24 tests passed, including replacement, editor-lock,
scroll and remote-image denial. Diagnostics now preserve the exact assertion and
record observed status, exception type/HRESULT/thread access and app logs; root cause
is still unproven. Do not weaken or skip the deletion assertion. Issues #4 (reader boundary), #6 (reload) and #1 (full scope) remain open.
Reader provides picker/Ctrl+O/launch paths, sanitized GFM, bounded passive local images,
debounced saves/replacement/deletion recovery and guarded relative scroll. Directory
callbacks dispatch only; bounded editor-lock retries and load scheduling preserve old
snapshots and picker requests. Native status declared before WebView2 resolved the
embedded-provider traversal issue. Initial window also fits DPI-scaled monitor work
area. Exact initial/missing/recovery assertions were preserved throughout diagnosis.
Hosted actual replacement/lock/deletion/relative-scroll/remote-image tests now pass.
Diagnostic head 665ece7 is published. Hosted UI job 114356665681 in CI 38100976971
finished with 24/25 passed; deletion raised FileNotFoundException (0x80070002) on
the UI thread, but the status text was absent from automation. The next targeted
change exposes StatusText with an explicit automation ID, text-bound accessible
name and content view. The deletion assertion remains unchanged; it also requires
the initial Opened status to be accessible. Build and formatting pass locally;
hosted recovery proof is pending. Accessibility head 23928bc still failed the initial status lookup (24/25 UI tests passed); properties alone did not resolve it. The next diagnostic retains the native tree and fixture-window PNG in hosted installed evidence. No deletion assertion is weakened. Scripts 38100976565 reproduced the analyzer
engine crash; no scripts/settings/workflow changed and issue #5 remains open.
All 20 original JSON themes are embedded unchanged with Darin's MIT notice shipped.
Built-in selection persists independently of the AppKit shell; actual dark/light paint
and screenshots passed. Current local change adds saved user overrides/custom names,
native color/code-font/size/CSS controls, invalid-input validation and built-in restoration
that retains custom names. AppKit saves preferences atomically; corrupt saved themes are
discarded before catalog loading. Core 119 tests/100% coverage and zero-warning build
pass. New dialog/browser tests added but not run locally; next hosted acceptance pending.
Hosted diagnostic CI 38101512710 is terminal failure. Its retained app screenshot
shows the initial window extending off the hosted desktop, clipping the entire status
line. The next change fits initial size/position and minimum dimensions to the current
monitor work area using physical DPI-scaled pixels. Exact initial and deletion status
assertions remain unchanged. Theme commit 0507ca5 is local until this follow-up push;
117 core tests/100% coverage and zero-warning build/format passed. Real browser proof
of display fitting and theme selection remains pending.
## Authority and continuity
Fitted head fa0df78 passed 25/26 hosted native/UI tests, including the document-theme
choice, but still failed the initial status lookup. The retained fitted screenshot
shows the status line visibly inside the window; fitting fixed clipping, not the
remaining automation problem. Diagnostics encountered an unsupported IsOffscreen
property on a browser peer; reads now use ValueOrDefault. The next change declares
the native status peer before WebView2, retaining Grid.Row=2 and the same visual
layout, to test the embedded-provider traversal boundary. The theme test also checks
actual painted dark/light backgrounds and retains its fixture screenshot. No assertion
is weakened or skipped; proof remains pending.
Owner authorized signed/DCO commits, pushes, repository configuration and ticket updates.
No merges, tags/releases or new Azure attempts. Existing AppKit/standards/starter drafts
remain unmerged; current-SHA human acknowledgement and producer-bound checks enforced.
Actual Azure signing/final signatures remain unverified. Desktop reservation is unanswered;
do not run local GUI input without availability. Hosted fixtures use an isolated runner.
## Repository and authorization
Pinned reference: 6d08bc9d27d7d7b2c2fa95bb282da330b8cf9021 at
AppKit/artifacts/markdownviewr-reference. Preserve original MIT notices when adapting.
Evidence: artifacts/verified-reader-38102249889 contains installed TRX/JSON and screenshots;
artifacts/user-themes-final-core contains the current 100% coverage report.
Public repository: [MarkdownViewr.Windows](https://github.com/KofTwentyTwo/MarkdownViewr.Windows).
Setup Validate verified 16 producer-bound contexts, protected main and release tags,
selected Actions and the protected release environment. Signed/DCO topic commits,
current-SHA human acknowledgement and required checks remain enforced.
## Next
Owner authorized commit/push/configuration, not merges, tags or releases. Existing
AppKit/standards/starter drafts remain unmerged. Azure retries stay deferred; actual
CI signing and final signed release artifacts remain unverified. Published AppKit
0.1.0 is used; do not substitute unpublished 0.2.0 APIs.
## Next work
Verify reload/browser network acceptance and preserve its exact hosted handles.
Built-in theme implementation now loads all 20 original resources, with persistent document selection, Windows font fallbacks and viewport retention. 117 core tests pass at 100% coverage; zero-warning build and formatting pass. User-theme editing and actual browser selection acceptance remain pending. Continue TOC/collapse, source/find/vim navigation,
frontmatter, editor, print, multiple windows, recents and Windows associations.
Original reference is pinned at 6d08bc9d27d7d7b2c2fa95bb282da330b8cf9021 under
AppKit/artifacts/markdownviewr-reference. The 20 original JSON themes are embedded unchanged in the core assembly; their full MIT notice ships with the app.
retain Darin's MIT notices when adapting them. Full PRODUCT.md scope remains open.
Reference preparation: all 20 original JSON themes have been downloaded into
AppKit/artifacts/markdownviewr-reference/markdownViewr/Resources/themes and checked
against their Git blob hashes at the pinned commit. They now match the embedded app resources by Git blob hash.
Commit/push the verified editable-theme milestone; observe its exact hosted handles.
Update #4/#6 with their completed scoped acceptance and keep #1 full port/#7 theme work
and #5 analyzer investigation accurate. Continue TOC/collapse/source/find/vim navigation,
frontmatter, editor launch, printing, multiple windows/recents and Windows associations.
Finish standards inventory and exact final signed delivery before claiming completion.
+5 -3
View File
@@ -8,12 +8,14 @@
- [x] Test physical image containment, including junction escapes, and input size limits.
- [x] Update the threat model, renderer attributions and shipped library notices.
- [x] Verify first-reader hosted browser acceptance: 13 native/UI tests passed on f1756d2.
- [ ] Verify new live-reload/browser network scenarios on the exact next implementation head; capture UI screenshots.
- [x] Verify live reload/browser network scenarios and retain actual theme screenshots on head 77dd04d.
- [ ] Discuss the desired first release and Windows-specific behavior with the owner.
- [x] Implement/test directory watching and validated relative viewport state for saves/replacements/deletion recovery.
- [ ] Complete actual browser save/lock/replacement/deletion/scroll acceptance (issue #6).
- [x] Complete actual browser save/lock/replacement/deletion/scroll acceptance (issue #6): hosted native/UI 26/26; published 26/26; installed stable/dev 25/25 each.
- [x] Port Darin's 20 built-in themes and persistent document selection; validate schema, font escaping and invariant CSS.
- [ ] Verify hosted theme selection/viewport acceptance; add editable user themes, custom CSS and code font settings.
- [x] Verify hosted built-in theme selection and actual painted colors on 77dd04d.
- [x] Implement persisted editable theme overrides/custom names, color/code-font/CSS controls and built-in restoration.
- [ ] Complete hosted theme editor/validation/restoration acceptance (issue #7).
- [ ] Add TOC, section collapse, source pane, synchronized navigation, find and vim keys.
- [ ] Add YAML frontmatter modes, safe configured editor launch and printing options.
- [ ] Add multiple document windows, recent files and Windows activation/file associations.
+3 -3
View File
@@ -22,7 +22,7 @@ physical directory. It does not authorize native commands or remote resource acc
| Picker / literal process argument | Read-only bounded snapshot; no shell interpolation |
| Markdown / raw HTML | Explicit tag/attribute/scheme allowlist; disabled checkbox inputs; no authored scripts, CSS, IDs or classes |
| File change notifications | Directory subscription scoped to selected path; 350 ms quiet-period debounce; replacement/deletion recovery; bounded transient retries; subscriptions released on window close |
| Theme JSON / CSS | Embedded original palettes; bounded schema-version-one parser; validated hex colors and finite sizes; code-point escaped font names; less-than signs escaped before style embedding; no network capability |
| Theme JSON / CSS | Native editor and saved user overrides use the same bounded validation; corrupt theme settings are discarded before startup; restoration keeps separately named custom themes; embedded original palettes; bounded schema-version-one parser; validated hex colors and finite sizes; code-point escaped font names; less-than signs escaped before style embedding; no network capability |
| Browser viewport | Fixed origin-checked native query; validate two finite fractions; invariant numeric restore only; authored scripts/messages stay disabled |
| Browser surface | Scripts, messages, host objects, permissions, downloads, frames and popups disabled; restrictive CSP |
| Local images | Per-document URI prefix; one decode; filename/extension policy; final open-handle containment; 16 MiB limit |
@@ -47,9 +47,9 @@ physical directory. It does not authorize native commands or remote resource acc
## Remaining risks and work
This is a first reader, not a completed port. User themes, external editor commands,
This is a first reader, not a completed port. User theme editor acceptance, external editor commands,
print and any future browser bridge need their own controls and tests. Save watching is
implemented; real browser replacement/deletion/scroll acceptance remains pending.
implemented; hosted real browser replacement/deletion/scroll and remote-image denial pass on 77dd04d.
Local links to other documents and mailto links are currently blocked. WebView2 uses
the installed evergreen runtime; installed deployment acceptance remains required.
@@ -3,6 +3,7 @@
* SPDX-License-Identifier: MIT
*/
using System.Text.Json;
using KofTwentyTwo.AppKit.Settings;
@@ -13,4 +14,41 @@ public sealed class AppSettings : ShellSettings
{
/// <summary>The selected document theme; independent of the Windows shell theme.</summary>
public string DocumentTheme { get; set; } = "Catppuccin Mocha";
/// <summary>Validated JSON themes, saved atomically with the AppKit preferences.</summary>
public string[] UserThemes { get; set; } = [];
/// <inheritdoc/>
public override void Sanitize()
{
base.Sanitize();
if(string.IsNullOrWhiteSpace(DocumentTheme) || DocumentTheme.Length > 80 || DocumentTheme.Any(char.IsControl))
{
DocumentTheme = "Catppuccin Mocha";
}
UserThemes = (UserThemes ?? []).Where(IsValidTheme).ToArray();
}
/// <summary>A corrupt saved theme cannot prevent application startup or damage the bundled catalog.</summary>
private static bool IsValidTheme(string json)
{
if(string.IsNullOrEmpty(json))
{
return false;
}
try
{
_ = Themes.ReaderTheme.Parse(json);
return true;
}
catch(JsonException)
{
return false;
}
}
}
@@ -20,10 +20,11 @@ public sealed class ReaderTheme
/// <summary>Retains only the validated display name and generated CSS.</summary>
private ReaderTheme(string name, string styles)
private ReaderTheme(string name, string styles, string json)
{
Name = name;
Styles = styles;
Json = json;
}
@@ -38,6 +39,11 @@ public sealed class ReaderTheme
/// <summary>The validated source retained for editing without losing palette fields.</summary>
public string Json { get; }
/// <summary>Accepts the original schema, including themes without an explicit version number.</summary>
public static ReaderTheme Parse(string json)
{
@@ -59,7 +65,7 @@ public sealed class ReaderTheme
throw new JsonException("Theme names must contain 1–80 printable characters.");
}
string styles = BuildStyles(root);
return new ReaderTheme(name, styles);
return new ReaderTheme(name, styles, json);
}
@@ -25,6 +25,19 @@ public static class ThemeCatalog
/// <summary>User themes override matching built-in names; new names join the alphabetic catalog.</summary>
public static IReadOnlyList<ReaderTheme> Combine(IEnumerable<ReaderTheme> userThemes)
{
ArgumentNullException.ThrowIfNull(userThemes);
Dictionary<string, ReaderTheme> themes = s_builtIn.ToDictionary(theme => theme.Name, StringComparer.Ordinal);
foreach(ReaderTheme theme in userThemes)
{
themes[theme.Name] = theme;
}
return Array.AsReadOnly(themes.Values.OrderBy(theme => theme.Name, StringComparer.Ordinal).ToArray());
}
/// <summary>Parses the shipped JSON with the same validation used for user themes.</summary>
private static ReaderTheme[] LoadBuiltIn()
{
@@ -28,6 +28,8 @@
</MenuBarItem>
<MenuBarItem Title="View">
<MenuFlyoutSubItem x:Name="DocumentThemesMenu" Text="Document theme" />
<MenuFlyoutItem x:Name="EditDocumentThemeMenu" Text="Edit document theme..." Click="EditDocumentTheme_Click" />
<MenuFlyoutItem x:Name="RestoreDocumentThemesMenu" Text="Restore built-in themes" Click="RestoreDocumentThemes_Click" />
<MenuFlyoutSeparator />
<RadioMenuFlyoutItem x:Name="ThemeSystem" Text="System theme" GroupName="Theme" Tag="System" Click="Theme_Click" />
<RadioMenuFlyoutItem x:Name="ThemeLight" Text="Light theme" GroupName="Theme" Tag="Light" Click="Theme_Click" />
+66 -3
View File
@@ -28,6 +28,7 @@ public sealed partial class MainWindow : Window, IDisposable
private bool _closed;
private readonly Core.Documents.DocumentLoadScheduler _loads = new();
private DocumentWatcher? _watcher;
private IReadOnlyList<Core.Themes.ReaderTheme> _themes = [];
@@ -35,7 +36,8 @@ public sealed partial class MainWindow : Window, IDisposable
public MainWindow()
{
InitializeComponent();
_browser = new DocumentBrowser(DocumentView, message => StatusText.Text = message, Core.Themes.ThemeCatalog.Find(_settings.DocumentTheme));
_themes = Core.Themes.ThemeCatalog.Combine(_settings.UserThemes.Select(Core.Themes.ReaderTheme.Parse));
_browser = new DocumentBrowser(DocumentView, message => StatusText.Text = message, ActiveDocumentTheme());
CreateDocumentThemeMenu();
Title = AppIdentity.Info.DisplayName;
FitInitialWindow();
@@ -310,8 +312,9 @@ public sealed partial class MainWindow : Window, IDisposable
/// <summary>Builds the original document theme choices without mixing them with the AppKit shell theme.</summary>
private void CreateDocumentThemeMenu()
{
string selected = Core.Themes.ThemeCatalog.Find(_settings.DocumentTheme).Name;
foreach(Core.Themes.ReaderTheme theme in Core.Themes.ThemeCatalog.BuiltIn)
DocumentThemesMenu.Items.Clear();
string selected = ActiveDocumentTheme().Name;
foreach(Core.Themes.ReaderTheme theme in _themes)
{
var item = new RadioMenuFlyoutItem { Text = theme.Name, Tag = theme, GroupName = "DocumentTheme", IsChecked = string.Equals(selected, theme.Name, StringComparison.Ordinal) };
Microsoft.UI.Xaml.Automation.AutomationProperties.SetAutomationId(item, "DocumentTheme:" + theme.Name);
@@ -328,6 +331,66 @@ public sealed partial class MainWindow : Window, IDisposable
var theme = (Core.Themes.ReaderTheme)((FrameworkElement)sender).Tag;
_settings.DocumentTheme = theme.Name;
Save();
await ApplyDocumentThemeAsync(theme);
}
/// <summary>Resolves user overrides and safely falls back after a saved custom theme is removed.</summary>
private Core.Themes.ReaderTheme ActiveDocumentTheme()
=> _themes.FirstOrDefault(theme => string.Equals(theme.Name, _settings.DocumentTheme, StringComparison.Ordinal))
?? Core.Themes.ThemeCatalog.Find(null);
/// <summary>A same-name edit overrides the original; a new name creates a custom theme.</summary>
private async void EditDocumentTheme_Click(object sender, RoutedEventArgs e)
{
Core.Themes.ReaderTheme? edited = await ThemeEditor.ShowAsync(Content.XamlRoot, ActiveDocumentTheme());
if(edited is null || _closed)
{
return;
}
_settings.UserThemes = _settings.UserThemes
.Where(json => !string.Equals(Core.Themes.ReaderTheme.Parse(json).Name, edited.Name, StringComparison.Ordinal))
.Append(edited.Json).ToArray();
_settings.DocumentTheme = edited.Name;
Save();
RefreshDocumentThemes();
await ApplyDocumentThemeAsync(edited);
}
/// <summary>Restores original palettes and removes their overrides, retaining separately named custom themes.</summary>
private async void RestoreDocumentThemes_Click(object sender, RoutedEventArgs e)
{
var dialog = new ContentDialog { XamlRoot = Content.XamlRoot, Title = "Restore built-in themes?", Content = "Edits to the 20 built-in themes will be removed. Your separately named custom themes will be kept.", PrimaryButtonText = "Restore themes", CloseButtonText = "Cancel" };
if(await dialog.ShowAsync() != ContentDialogResult.Primary || _closed)
{
return;
}
var builtIn = Core.Themes.ThemeCatalog.BuiltIn.Select(theme => theme.Name).ToHashSet(StringComparer.Ordinal);
_settings.UserThemes = _settings.UserThemes.Where(json => !builtIn.Contains(Core.Themes.ReaderTheme.Parse(json).Name)).ToArray();
Save();
RefreshDocumentThemes();
await ApplyDocumentThemeAsync(ActiveDocumentTheme());
}
/// <summary>Rebuilds the visible catalog after a successful preference edit.</summary>
private void RefreshDocumentThemes()
{
_themes = Core.Themes.ThemeCatalog.Combine(_settings.UserThemes.Select(Core.Themes.ReaderTheme.Parse));
CreateDocumentThemeMenu();
}
/// <summary>Applies a theme without allowing browser errors to escape a native event handler.</summary>
private async Task ApplyDocumentThemeAsync(Core.Themes.ReaderTheme theme)
{
try
{
_browserInitialization ??= _browser.InitializeAsync();
+133
View File
@@ -0,0 +1,133 @@
/*
* Copyright (c) 2026 James Maes
* SPDX-License-Identifier: MIT
*/
using System.Text.Json;
using System.Text.Json.Nodes;
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
namespace MarkdownViewr.Windows;
/// <summary>Edits document appearance through native controls; invalid input leaves the editor open.</summary>
internal static class ThemeEditor
{
/// <summary>Returns a validated edited theme, or null after cancellation.</summary>
public static async Task<Core.Themes.ReaderTheme?> ShowAsync(XamlRoot xamlRoot, Core.Themes.ReaderTheme theme)
{
JsonNode source = JsonNode.Parse(theme.Json)!;
TextBox name = Field("Name (a new name creates a custom theme)", theme.Name, "ThemeEditorName", 80);
TextBox font = Field("Code font", source["fonts"]!["code"]!.GetValue<string>(), "ThemeEditorCodeFont", 80);
var size = new NumberBox { Header = "Code font size", Minimum = 6, Maximum = 96, Value = source["sizes"]!["codeFontSize"]!.GetValue<double>() };
Microsoft.UI.Xaml.Automation.AutomationProperties.SetAutomationId(size, "ThemeEditorCodeSize");
TextBox css = Field("Custom CSS", source["customCSS"]?.GetValue<string>() ?? "", "ThemeEditorCss", 128 * 1024);
css.AcceptsReturn = true;
css.Height = 160;
css.TextWrapping = TextWrapping.Wrap;
css.FontFamily = new Microsoft.UI.Xaml.Media.FontFamily("Consolas");
var error = new TextBlock { TextWrapping = TextWrapping.Wrap };
Microsoft.UI.Xaml.Automation.AutomationProperties.SetAutomationId(error, "ThemeEditorError");
var fields = new StackPanel { Spacing = 12 };
fields.Children.Add(name);
fields.Children.Add(font);
fields.Children.Add(size);
Dictionary<string, TextBox> colors = AddColors(fields, source["colors"]!.AsObject());
fields.Children.Add(css);
fields.Children.Add(error);
var dialog = new ContentDialog
{
XamlRoot = xamlRoot,
Title = "Edit document theme",
PrimaryButtonText = "Save theme",
CloseButtonText = "Cancel",
DefaultButton = ContentDialogButton.Primary,
Content = new ScrollViewer { Content = fields, Height = Math.Clamp(xamlRoot.Size.Height - 220, 120, 440), Width = 480, HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled },
};
Core.Themes.ReaderTheme? edited = null;
dialog.PrimaryButtonClick += (_, args) =>
{
try
{
edited = ReadEdited(source, name.Text, font.Text, size.Value, css.Text, colors);
}
catch(Exception exception) when(exception is JsonException or ArgumentException)
{
error.Text = exception.Message;
args.Cancel = true;
error.StartBringIntoView();
}
};
_ = await dialog.ShowAsync();
return edited;
}
/// <summary>Updates only the edited fields and runs the same schema/CSS validation as imported themes.</summary>
private static Core.Themes.ReaderTheme ReadEdited(JsonNode source, string name, string font, double size, string css, Dictionary<string, TextBox> colors)
{
if(!double.IsFinite(size))
{
throw new JsonException("Enter a code font size between 6 and 96.");
}
source["name"] = name.Trim();
source["fonts"]!["code"] = font.Trim();
source["sizes"]!["codeFontSize"] = size;
source["customCSS"] = css;
foreach((string key, TextBox value) in colors)
{
source["colors"]![key] = value.Text.Trim();
}
return Core.Themes.ReaderTheme.Parse(source.ToJsonString());
}
/// <summary>Keeps every palette field editable, including all heading and highlight colors.</summary>
private static Dictionary<string, TextBox> AddColors(StackPanel fields, JsonObject source)
{
var colors = new Dictionary<string, TextBox>(StringComparer.Ordinal);
foreach((string key, JsonNode? value) in source)
{
string? label = key switch
{
"background" => "Background",
"text" => "Text",
"heading1" => "Heading 1",
"heading2" => "Heading 2",
"heading3" => "Heading 3",
"heading4" => "Heading 4",
"heading5" => "Heading 5",
"heading6" => "Heading 6",
"link" => "Links",
"codeBackground" => "Code background",
"codeText" => "Code text",
"blockquoteBorder" => "Quote border",
"blockquoteBackground" => "Quote background",
"highlightBackground" => "Selection background",
"highlightText" => "Selection text",
_ => null,
};
if(label is null)
{
continue;
}
TextBox input = Field(label + " (#RRGGBB)", value!.GetValue<string>(), "ThemeEditorColor:" + key, 7);
colors.Add(key, input);
fields.Children.Add(input);
}
return colors;
}
/// <summary>Creates a labeled text control with a stable accessibility identifier.</summary>
private static TextBox Field(string label, string value, string id, int maximumLength)
{
var input = new TextBox { Header = label, Text = value, MaxLength = maximumLength };
Microsoft.UI.Xaml.Automation.AutomationProperties.SetAutomationId(input, id);
return input;
}
}
@@ -66,8 +66,9 @@ public class AppSettingsTests
{
using var temp = new TempDirectory();
var store = new KofTwentyTwo.AppKit.Settings.SettingsStore<AppSettings>(temp.File("settings.json"), AppSettingsContext.Default.AppSettings);
Assert.True(store.Save(new AppSettings { Theme = "Dark", DocumentTheme = "GitHub Light" }));
Assert.True(store.Save(new AppSettings { Theme = "Dark", DocumentTheme = "GitHub Light", UserThemes = [Themes.ThemeCatalog.Find("GitHub Light").Json] }));
Assert.Equal("Dark", store.Load().Theme);
Assert.Equal("GitHub Light", store.Load().DocumentTheme);
Assert.Equal(Themes.ThemeCatalog.Find("GitHub Light").Json, Assert.Single(store.Load().UserThemes));
}
}
@@ -28,6 +28,42 @@ public sealed class ReaderThemeTests
/// <summary>User edits replace bundled names without duplicates; new themes are sorted and retained.</summary>
[Fact]
public void Combine_UserOverridesAndNewTheme_PreservesEdits()
{
string original = OriginalJson();
var edited = ReaderTheme.Parse(original.Replace("#1e1e2e", "#123456", StringComparison.Ordinal));
var custom = ReaderTheme.Parse(original.Replace("Catppuccin Mocha", "A Custom Theme", StringComparison.Ordinal));
IReadOnlyList<ReaderTheme> combined = ThemeCatalog.Combine([edited, custom]);
Assert.Equal(21, combined.Count);
Assert.Same(custom, combined[0]);
Assert.Same(edited, combined.Single(theme => string.Equals(theme.Name, edited.Name, StringComparison.Ordinal)));
Assert.Contains("--background:#123456;", edited.Styles, StringComparison.Ordinal);
Assert.Equal(original.Replace("#1e1e2e", "#123456", StringComparison.Ordinal), edited.Json);
Assert.Equal(20, ThemeCatalog.Combine([]).Count);
Assert.Throws<ArgumentNullException>(() => ThemeCatalog.Combine(null!));
}
/// <summary>Preferences discard corrupt custom themes while retaining valid edits and repairing invalid selection names.</summary>
[Fact]
public void Sanitize_CorruptSavedThemes_KeepsValidThemes()
{
string json = OriginalJson();
var settings = new AppSettings { DocumentTheme = "\n", UserThemes = [null!, "", "{", json] };
settings.Sanitize();
Assert.Equal("Catppuccin Mocha", settings.DocumentTheme);
Assert.Equal([json], settings.UserThemes, StringComparer.Ordinal);
settings.UserThemes = null!;
settings.DocumentTheme = new string('x', 81);
settings.Sanitize();
Assert.Empty(settings.UserThemes);
Assert.Equal("Catppuccin Mocha", settings.DocumentTheme);
}
/// <summary>Color, font and size values become CSS variables using invariant numbers.</summary>
[Fact]
public void Parse_OriginalTheme_PreservesPaletteAndMapsFonts()
@@ -5,6 +5,7 @@
using System.Net;
using System.Net.Sockets;
using System.Text.Json;
using FlaUI.Core.AutomationElements;
using FlaUI.Core.Patterns;
using Xunit.Abstractions;
@@ -108,6 +109,68 @@ public class AppTests
}
/// <summary>A named custom theme saves all editing controls and applies its CSS to the actual browser.</summary>
[Fact]
public void ThemeEditor_NewCustomTheme_SavesAndPaintsChanges()
{
using var session = new AppSession(document: "# Custom theme acceptance\n\n`sample code`");
session.WaitFor(() => session.FindInApp(cf => cf.ByName("Custom theme acceptance")), "the document heading", TimeSpan.FromSeconds(30));
session.InvokeMenuItem("View", "EditDocumentThemeMenu");
session.EnterText("ThemeEditorName", "My reading theme");
session.EnterText("ThemeEditorCodeFont", "Consolas");
session.EnterText("ThemeEditorColor:background", "#112233");
session.EnterText("ThemeEditorCss", "html { background: #223344; }");
session.ClickButton("Save theme");
session.WaitForElementGone("ThemeEditorName");
WaitForDocumentColor(session, System.Drawing.Color.FromArgb(34, 51, 68));
using var settings = JsonDocument.Parse(session.ReadSettings());
Assert.Equal("My reading theme", settings.RootElement.GetProperty("DocumentTheme").GetString());
using var theme = JsonDocument.Parse(Assert.Single(settings.RootElement.GetProperty("UserThemes").EnumerateArray()).GetString()!);
Assert.Equal("Consolas", theme.RootElement.GetProperty("fonts").GetProperty("code").GetString());
Assert.Equal("#112233", theme.RootElement.GetProperty("colors").GetProperty("background").GetString());
Assert.Equal("html { background: #223344; }", theme.RootElement.GetProperty("customCSS").GetString());
Assert.NotNull(session.FindInApp(cf => cf.ByName("Custom theme acceptance")));
_output.WriteLine(session.DescribeDocumentStatus());
}
/// <summary>Invalid colors keep the dialog open; cancellation cannot create a saved override.</summary>
[Fact]
public void ThemeEditor_InvalidColorAndCancel_DoesNotPersist()
{
using var session = new AppSession();
session.InvokeMenuItem("View", "EditDocumentThemeMenu");
session.EnterText("ThemeEditorColor:background", "invalid");
session.ClickButton("Save theme");
session.WaitFor(() => session.FindInApp(cf => cf.ByName("Theme colors must use six-digit hexadecimal notation.")), "the color validation error");
Assert.NotNull(session.FindInApp(cf => cf.ByAutomationId("ThemeEditorName")));
session.ClickButton("Cancel");
session.WaitForElementGone("ThemeEditorName");
Assert.DoesNotContain("invalid", session.ReadSettings(), StringComparison.Ordinal);
}
/// <summary>Restoring built-ins removes an edited built-in palette after explicit confirmation.</summary>
[Fact]
public void ThemeEditor_BuiltInOverride_RestoresOriginalPalette()
{
using var session = new AppSession(document: "# Theme restore acceptance");
session.WaitFor(() => session.FindInApp(cf => cf.ByName("Theme restore acceptance")), "the document heading", TimeSpan.FromSeconds(30));
session.InvokeMenuItem("View", "EditDocumentThemeMenu");
session.EnterText("ThemeEditorColor:background", "#112233");
session.ClickButton("Save theme");
session.WaitForElementGone("ThemeEditorName");
WaitForDocumentColor(session, System.Drawing.Color.FromArgb(17, 34, 51));
session.InvokeMenuItem("View", "RestoreDocumentThemesMenu");
session.ClickButton("Restore themes");
WaitForDocumentColor(session, System.Drawing.Color.FromArgb(30, 30, 46));
using var settings = JsonDocument.Parse(session.ReadSettings());
Assert.Equal(0, settings.RootElement.GetProperty("UserThemes").GetArrayLength());
}
/// <summary>Updates: a build that was not installed by Velopack says updates need an install.</summary>
[Fact]
public void CheckForUpdates_InALooseBuild_SaysUpdatesNeedAnInstall()