-
Notifications
You must be signed in to change notification settings - Fork 0
Add Cmd-K command palette and keyboard router #59
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Cellcote
wants to merge
1
commit into
main
Choose a base branch
from
feat/keyboard_shortcuts
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,12 @@ | ||
| namespace Conclave.App.Commands; | ||
|
|
||
| // One thing the user can invoke from the palette (or, later, a hotkey). `CanExecute` | ||
| // gates visibility/availability — e.g. "Cancel turn" only surfaces when a session has | ||
| // an in-flight CTS. Named `AppCommand` to avoid colliding with the BCL's | ||
| // System.Windows.Input.ICommand-style "Command" type some Avalonia code picks up. | ||
| public sealed record AppCommand( | ||
| string Id, | ||
| string Title, | ||
| string? Group, | ||
| Func<bool> CanExecute, | ||
| Action Execute); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,23 @@ | ||
| namespace Conclave.App.Commands; | ||
|
|
||
| // Owns the catalog of static commands (palette.open, prefs.open, ...). Dynamic | ||
| // per-session commands ("Switch to <name>") are produced on demand by the palette | ||
| // VM and not registered here — they'd churn every time a session is added/removed. | ||
| public sealed class CommandRegistry | ||
| { | ||
| private readonly Dictionary<string, AppCommand> _byId = new(); | ||
|
|
||
| public IReadOnlyCollection<AppCommand> All => _byId.Values; | ||
|
|
||
| public void Register(AppCommand cmd) => _byId[cmd.Id] = cmd; | ||
|
|
||
| public AppCommand? Get(string id) => _byId.GetValueOrDefault(id); | ||
|
|
||
| public bool TryExecute(string id) | ||
| { | ||
| if (!_byId.TryGetValue(id, out var cmd)) return false; | ||
| if (!cmd.CanExecute()) return false; | ||
| cmd.Execute(); | ||
| return true; | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,50 @@ | ||
| namespace Conclave.App.Commands; | ||
|
|
||
| // Subsequence-based fuzzy matcher for the command palette. All query chars must | ||
| // appear in order in the candidate. Score rewards consecutive matches and matches | ||
| // at word boundaries — the "ns" in "**N**ew **s**ession" beats "**n**ew sessio**n**s" | ||
| // even though both match. | ||
| // | ||
| // Returns (score, matchedIndices) so the UI can highlight the matched chars. Score | ||
| // of 0 means no match; higher is better. | ||
| public static class FuzzyMatch | ||
| { | ||
| public static (int Score, int[] Indices) Score(string query, string candidate) | ||
| { | ||
| if (string.IsNullOrEmpty(query)) return (1, Array.Empty<int>()); | ||
| if (string.IsNullOrEmpty(candidate)) return (0, Array.Empty<int>()); | ||
|
|
||
| var indices = new int[query.Length]; | ||
| int score = 0; | ||
| int qi = 0; | ||
| int lastMatch = -2; | ||
|
|
||
| for (int ci = 0; ci < candidate.Length && qi < query.Length; ci++) | ||
| { | ||
| char qc = char.ToLowerInvariant(query[qi]); | ||
| char cc = char.ToLowerInvariant(candidate[ci]); | ||
| if (qc != cc) continue; | ||
|
|
||
| indices[qi] = ci; | ||
| // Bonus: consecutive match (no gap from previous match). | ||
| if (ci == lastMatch + 1) score += 5; | ||
| // Bonus: matched at start of string. | ||
| if (ci == 0) score += 8; | ||
| // Bonus: matched at a word boundary (after space/punctuation). | ||
| else if (IsBoundary(candidate[ci - 1])) score += 4; | ||
| // Base: every match contributes a small amount so longer matches outscore shorter | ||
| // (when ties happen on bonuses). | ||
| score += 1; | ||
| lastMatch = ci; | ||
| qi++; | ||
| } | ||
|
|
||
| if (qi < query.Length) return (0, Array.Empty<int>()); // unmatched chars left | ||
| // Penalty: shorter candidates of equal match are preferable. Subtract a tiny bit | ||
| // per unused char so "new session" beats "newest sessions" for "new s". | ||
| score -= candidate.Length / 8; | ||
| return (Math.Max(score, 1), indices); | ||
| } | ||
|
|
||
| private static bool IsBoundary(char c) => c is ' ' or '-' or '_' or '.' or '/' or ':'; | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,95 @@ | ||
| using Avalonia.Input; | ||
|
|
||
| namespace Conclave.App.Commands; | ||
|
|
||
| // A single key + modifier combo, normalised so equality works regardless of how the | ||
| // chord was entered. `cmd` parses to Meta on macOS and Control elsewhere — this is | ||
| // the same convention VS Code uses, and it's what users expect when sharing keymaps | ||
| // across machines. | ||
| public readonly record struct KeyChord(Key Key, KeyModifiers Modifiers) | ||
| { | ||
| public static KeyChord FromEvent(KeyEventArgs e) => new(e.Key, NormaliseModifiers(e.KeyModifiers)); | ||
|
|
||
| // Strip Shift when the underlying key already encodes case-sensitivity (letters/digits)? | ||
| // No — we want Shift to be significant for chords like "shift+G". Just clear stray | ||
| // modifier bits Avalonia might emit (none today, future-proofing only). | ||
| private static KeyModifiers NormaliseModifiers(KeyModifiers m) => m; | ||
|
|
||
| // "cmd+k", "ctrl+shift+p", "esc". Returns null on parse failure rather than | ||
| // throwing — bad keymaps shouldn't crash the app, they should just be ignored. | ||
| public static KeyChord? Parse(string spec) | ||
| { | ||
| if (string.IsNullOrWhiteSpace(spec)) return null; | ||
| var parts = spec.Split('+', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); | ||
| if (parts.Length == 0) return null; | ||
| var mods = KeyModifiers.None; | ||
| Key? key = null; | ||
| foreach (var raw in parts) | ||
| { | ||
| switch (raw.ToLowerInvariant()) | ||
| { | ||
| case "cmd": | ||
| case "meta": | ||
| case "win": | ||
| mods |= OperatingSystem.IsMacOS() ? KeyModifiers.Meta : KeyModifiers.Control; | ||
| break; | ||
| case "ctrl": | ||
| case "control": | ||
| mods |= KeyModifiers.Control; | ||
| break; | ||
| case "shift": | ||
| mods |= KeyModifiers.Shift; | ||
| break; | ||
| case "alt": | ||
| case "option": | ||
| mods |= KeyModifiers.Alt; | ||
| break; | ||
| default: | ||
| if (!TryParseKey(raw, out var parsed)) return null; | ||
| key = parsed; | ||
| break; | ||
| } | ||
| } | ||
| return key is null ? null : new KeyChord(key.Value, mods); | ||
| } | ||
|
|
||
| private static bool TryParseKey(string raw, out Key key) | ||
| { | ||
| // Single-char shortcuts: "k", "p". Avalonia's Key enum names letters as A..Z. | ||
| if (raw.Length == 1 && char.IsLetter(raw[0])) | ||
| return Enum.TryParse(raw.ToUpperInvariant(), out key); | ||
|
|
||
| // Common aliases users will type before the formal name. | ||
| switch (raw.ToLowerInvariant()) | ||
| { | ||
| case "esc": key = Key.Escape; return true; | ||
| case "enter": | ||
| case "return": key = Key.Enter; return true; | ||
| case "space": key = Key.Space; return true; | ||
| } | ||
|
|
||
| return Enum.TryParse(raw, ignoreCase: true, out key); | ||
| } | ||
|
|
||
| public string Display | ||
| { | ||
| get | ||
| { | ||
| var parts = new List<string>(4); | ||
| if (Modifiers.HasFlag(KeyModifiers.Control)) parts.Add(OperatingSystem.IsMacOS() ? "⌃" : "Ctrl"); | ||
| if (Modifiers.HasFlag(KeyModifiers.Alt)) parts.Add(OperatingSystem.IsMacOS() ? "⌥" : "Alt"); | ||
| if (Modifiers.HasFlag(KeyModifiers.Shift)) parts.Add(OperatingSystem.IsMacOS() ? "⇧" : "Shift"); | ||
| if (Modifiers.HasFlag(KeyModifiers.Meta)) parts.Add(OperatingSystem.IsMacOS() ? "⌘" : "Win"); | ||
| parts.Add(KeyDisplay(Key)); | ||
| return OperatingSystem.IsMacOS() ? string.Concat(parts) : string.Join("+", parts); | ||
| } | ||
| } | ||
|
|
||
| private static string KeyDisplay(Key k) => k switch | ||
| { | ||
| Key.Escape => "Esc", | ||
| Key.Enter => "↵", | ||
| Key.Space => "Space", | ||
| _ => k.ToString(), | ||
| }; | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,69 @@ | ||
| using System.Text.Json; | ||
|
|
||
| namespace Conclave.App.Commands; | ||
|
|
||
| // Maps key chords to command ids. Defaults are baked in code; user overrides come from | ||
| // the settings table as JSON of the form `[ { "key": "cmd+k", "command": "palette.open" } ]`. | ||
| // Overrides are merged on top of defaults — a user can rebind without losing the rest. | ||
| public sealed class KeyMap | ||
| { | ||
| private readonly Dictionary<KeyChord, string> _bindings = new(); | ||
|
|
||
| public IReadOnlyDictionary<KeyChord, string> Bindings => _bindings; | ||
|
|
||
| public void Bind(string chord, string commandId) | ||
| { | ||
| if (KeyChord.Parse(chord) is { } parsed) _bindings[parsed] = commandId; | ||
| } | ||
|
|
||
| public void Bind(KeyChord chord, string commandId) => _bindings[chord] = commandId; | ||
|
|
||
| public string? Lookup(KeyChord chord) => _bindings.GetValueOrDefault(chord); | ||
|
|
||
| // First chord bound to the given command id, for display purposes. Linear scan — | ||
| // we never have enough bindings for a reverse index to be worth the maintenance. | ||
| public KeyChord? FindForCommand(string commandId) | ||
| { | ||
| foreach (var (chord, id) in _bindings) | ||
| if (id == commandId) return chord; | ||
| return null; | ||
| } | ||
|
|
||
| // Defaults — kept minimal until we agree on the catalog. Cmd-K is the only one | ||
| // we're confident in shipping right now. | ||
| public static KeyMap Defaults() | ||
| { | ||
| var map = new KeyMap(); | ||
| map.Bind("cmd+k", "palette.open"); | ||
| return map; | ||
| } | ||
|
|
||
| // Manual JsonDocument walk rather than JsonSerializer.Deserialize so we don't pull | ||
| // in reflection-based deserialization — the project publishes with NativeAOT and the | ||
| // schema is trivial enough that hand-rolling is cleaner than wiring up a source-gen | ||
| // JsonSerializerContext. | ||
| public void ApplyOverridesJson(string? json) | ||
| { | ||
| if (string.IsNullOrWhiteSpace(json)) return; | ||
| try | ||
| { | ||
| using var doc = JsonDocument.Parse(json); | ||
| if (doc.RootElement.ValueKind != JsonValueKind.Array) return; | ||
| foreach (var entry in doc.RootElement.EnumerateArray()) | ||
| { | ||
| if (entry.ValueKind != JsonValueKind.Object) continue; | ||
| if (!entry.TryGetProperty("key", out var keyEl) || keyEl.ValueKind != JsonValueKind.String) continue; | ||
| if (!entry.TryGetProperty("command", out var cmdEl) || cmdEl.ValueKind != JsonValueKind.String) continue; | ||
| var keyStr = keyEl.GetString(); | ||
| var cmdStr = cmdEl.GetString(); | ||
| if (string.IsNullOrWhiteSpace(keyStr) || string.IsNullOrWhiteSpace(cmdStr)) continue; | ||
| if (KeyChord.Parse(keyStr) is { } chord) _bindings[chord] = cmdStr; | ||
| } | ||
| } | ||
| catch (JsonException) | ||
| { | ||
| // Bad JSON — keep defaults. Users get told via a settings UI later; for now | ||
| // we just don't apply broken overrides. | ||
| } | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,47 @@ | ||
| using Avalonia.Controls; | ||
| using Avalonia.Input; | ||
| using Avalonia.Interactivity; | ||
|
|
||
| namespace Conclave.App.Commands; | ||
|
|
||
| // Window-level keyboard router. Listens on the tunnel phase so app-level chords with a | ||
| // modifier (Cmd-K, Ctrl-Shift-P) win even when a TextBox would otherwise consume the | ||
| // keystroke. Plain-key chords (no modifier) are handled on the bubble phase so typing | ||
| // in inputs still works normally. | ||
| public static class KeyRouter | ||
| { | ||
| public static void Attach(Window window, CommandRegistry registry, KeyMap map) | ||
| { | ||
| window.AddHandler(InputElement.KeyDownEvent, (s, e) => OnKey(e, registry, map, tunneling: true), | ||
| RoutingStrategies.Tunnel); | ||
| window.AddHandler(InputElement.KeyDownEvent, (s, e) => OnKey(e, registry, map, tunneling: false), | ||
| RoutingStrategies.Bubble); | ||
| } | ||
|
|
||
| private static void OnKey(KeyEventArgs e, CommandRegistry registry, KeyMap map, bool tunneling) | ||
| { | ||
| if (e.Handled) return; | ||
|
|
||
| var chord = KeyChord.FromEvent(e); | ||
| // Modifier keys arriving on their own (e.g. holding ⌘) come through as | ||
| // Key.LeftCommand / LWin / etc. Skip — they aren't a chord on their own. | ||
| if (IsModifierKey(e.Key)) return; | ||
|
|
||
| bool hasGlobalModifier = chord.Modifiers.HasFlag(KeyModifiers.Meta) | ||
| || chord.Modifiers.HasFlag(KeyModifiers.Control); | ||
|
|
||
| // Tunnel phase only handles modifier-bearing chords — that's the whole point of | ||
| // grabbing them early. Plain-letter chords fall through to the bubble pass. | ||
| if (tunneling && !hasGlobalModifier) return; | ||
| if (!tunneling && hasGlobalModifier) return; // already considered on tunnel | ||
|
|
||
| if (map.Lookup(chord) is not { } commandId) return; | ||
| if (registry.TryExecute(commandId)) e.Handled = true; | ||
| } | ||
|
|
||
| private static bool IsModifierKey(Key k) => k | ||
| is Key.LeftCtrl or Key.RightCtrl | ||
| or Key.LeftShift or Key.RightShift | ||
| or Key.LeftAlt or Key.RightAlt | ||
| or Key.LWin or Key.RWin; | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Key.LeftMeta/Key.RightMetamissing fromIsModifierKeyAvalonia exposes
Key.LeftMetaandKey.RightMetafor the macOS Command key (in addition toKey.LWin/Key.RWin). If either value is what Avalonia actually emits when the user holds Command alone on macOS,IsModifierKeyreturnsfalse,KeyChord.FromEventbuilds a chord whoseKeyisLeftMeta/RightMeta,map.Lookupfinds nothing, and the event falls through harmlessly — but the guard's intent (skip bare-modifier keystrokes entirely) is violated. Adding both values keeps the intent sound across platform variations: