|
2 | 2 | using Blazor.Diagrams.Core.Utils; |
3 | 3 | using System; |
4 | 4 | using System.Collections.Generic; |
| 5 | +using System.Linq; |
5 | 6 | using System.Threading.Tasks; |
6 | 7 |
|
7 | 8 | namespace Blazor.Diagrams.Core.Behaviors; |
8 | 9 |
|
9 | 10 | public class KeyboardShortcutsBehavior : Behavior |
10 | 11 | { |
11 | | - private readonly Dictionary<string, Func<Diagram, ValueTask>> _shortcuts; |
| 12 | + public record KeyboardShortcut(string Key, bool Ctrl, bool Shift, bool Alt, Func<Diagram, ValueTask> Action); |
| 13 | + |
| 14 | + private readonly Dictionary<string, KeyboardShortcut> _shortcuts; |
12 | 15 |
|
13 | 16 | public KeyboardShortcutsBehavior(Diagram diagram) : base(diagram) |
14 | 17 | { |
15 | | - _shortcuts = new Dictionary<string, Func<Diagram, ValueTask>>(); |
| 18 | + _shortcuts = new Dictionary<string, KeyboardShortcut>(); |
16 | 19 | SetShortcut("Delete", false, false, false, KeyboardShortcutsDefaults.DeleteSelection); |
17 | 20 | SetShortcut("g", true, false, true, KeyboardShortcutsDefaults.Grouping); |
18 | 21 |
|
19 | 22 | Diagram.KeyDown += OnDiagramKeyDown; |
20 | 23 | } |
21 | 24 |
|
| 25 | + public KeyboardShortcut[] GetShortcuts() |
| 26 | + { |
| 27 | + return _shortcuts.Values.ToArray(); |
| 28 | + } |
| 29 | + |
22 | 30 | public void SetShortcut(string key, bool ctrl, bool shift, bool alt, Func<Diagram, ValueTask> action) |
23 | 31 | { |
24 | 32 | var k = KeysUtils.GetStringRepresentation(ctrl, shift, alt, key); |
25 | | - _shortcuts[k] = action; |
| 33 | + _shortcuts[k] = new KeyboardShortcut(key, ctrl, shift, alt, action); |
26 | 34 | } |
27 | | - |
| 35 | + |
28 | 36 | public bool RemoveShortcut(string key, bool ctrl, bool shift, bool alt) |
29 | 37 | { |
30 | 38 | var k = KeysUtils.GetStringRepresentation(ctrl, shift, alt, key); |
31 | 39 | return _shortcuts.Remove(k); |
32 | 40 | } |
33 | 41 |
|
| 42 | + public void RemoveAllShortcuts() |
| 43 | + { |
| 44 | + _shortcuts.Clear(); |
| 45 | + } |
| 46 | + |
34 | 47 | private async void OnDiagramKeyDown(KeyboardEventArgs e) |
35 | 48 | { |
36 | 49 | var k = KeysUtils.GetStringRepresentation(e.CtrlKey, e.ShiftKey, e.AltKey, e.Key); |
37 | | - if (_shortcuts.TryGetValue(k, out var action)) |
| 50 | + if (_shortcuts.TryGetValue(k, out var shortcut)) |
38 | 51 | { |
39 | | - await action(Diagram); |
| 52 | + await shortcut.Action(Diagram); |
40 | 53 | } |
41 | 54 | } |
42 | 55 |
|
|
0 commit comments