A Swiss Army knife for developers.
C# blazorcross-platformcsharpdesktopdesktop-appdesktop-applicationdeveloper-toolsextensiblefluentfluent-designlinuxmacosmicasyntax-highlightingtypescriptwindowswindows-10windows-11winui
[DevToys 2.0] Added search bar + keyboard navigation in context menu (#840)
Etienne BAUDOUXd42637ca7a0a
diff --git a/.vscode/settings.json b/.vscode/settings.jsonindex e9553a72a..ea88f81e0 100644--- a/.vscode/settings.json+++ b/.vscode/settings.json@@ -17,5 +17,5 @@},"emmet.includeLanguages": {"aspnetcorerazor": "html"- },+ }}diff --git a/src/app/dev/DevToys.Api/TextSpan.cs b/src/app/dev/DevToys.Api/TextSpan.csindex 57cd148d7..50340548a 100644--- a/src/app/dev/DevToys.Api/TextSpan.cs+++ b/src/app/dev/DevToys.Api/TextSpan.cs@@ -27,4 +27,9 @@ public record TextSpan/// Gets the length of the span./// </summary>public int Length { get; }++ /// <summary>+ /// Gets the end position of the span.+ /// </summary>+ public int EndPosition => StartPosition + Length;}diff --git a/src/app/dev/DevToys.Api/Tool/GUI/Components/IUISinglelineTextInput.cs b/src/app/dev/DevToys.Api/Tool/GUI/Components/IUISinglelineTextInput.csindex 6772d9ef5..3a92af71b 100644--- a/src/app/dev/DevToys.Api/Tool/GUI/Components/IUISinglelineTextInput.cs+++ b/src/app/dev/DevToys.Api/Tool/GUI/Components/IUISinglelineTextInput.cs@@ -103,7 +103,7 @@ internal class UISingleLineTextInput : UITitledElement, IUISingleLineTextInputnameof(TextSpan.StartPosition),"The start position of the selection is greater than the text length.");}- else if (_selection.StartPosition + _selection.Length > Text.Length)+ else if (_selection.EndPosition > Text.Length){ThrowHelper.ThrowArgumentOutOfRangeException(nameof(TextSpan.Length),diff --git a/src/app/dev/DevToys.Blazor/Components/AutoSuggestBox/AutoSuggestBox.razor b/src/app/dev/DevToys.Blazor/Components/AutoSuggestBox/AutoSuggestBox.razorindex df1c5244d..2f872efe2 100644--- a/src/app/dev/DevToys.Blazor/Components/AutoSuggestBox/AutoSuggestBox.razor+++ b/src/app/dev/DevToys.Blazor/Components/AutoSuggestBox/AutoSuggestBox.razor@@ -1,20 +1,42 @@@namespace DevToys.Blazor.Components@inherits StyledComponentBase+@typeparam TElement<CascadingValue Value="this" IsFixed="true">- <TextBox @ref="_textBox"- Class="@(FinalCssClasses)"- Style="@(Style)"- @attributes="AdditionalAttributes"- Type="TextBoxTypes.Search"- Header="@Header"- Placeholder="@Placeholder"- IsEnabled="IsEnabled"- IsReadOnly="@IsReadOnly"- @bind-Text="Query"- OnTextChanged="@OnTextBoxTextChangedAsync">- <Buttons>- <FontIcon Glyph="@('\uF68F')" Style="transform: unset; left: 0; height: 16px; margin-left: 4px; margin-right: 4px;" />- </Buttons>- </TextBox>+ <div id="@Id" style="@Style">+ <TextBox @ref="_textBox"+ Class="@(FinalCssClasses)"+ @attributes="AdditionalAttributes"+ Type="TextBoxTypes.Search"+ Header="@Header"+ Placeholder="@Placeholder"+ IsEnabled="@IsEnabled"+ IsReadOnly="@IsReadOnly"+ OnTextChanged="@OnTextBoxTextChangedAsync"+ @onkeydown="@OnTextBoxKeyPress"+ @onfocusout="@OnTextBoxFocusLost">+ <Buttons>+ <FontIcon Glyph="@('\uF68F')" Style="transform: unset; left: 0; height: 16px; margin-left: 4px; margin-right: 4px;" />+ </Buttons>+ </TextBox>++ <Popover Open="_showDropDown"+ AnchorOrigin="Origin.BottomLeft"+ TransformOrigin="Origin.TopLeft"+ RelativeWidth="true"+ Class="auto-suggest-box-drop-down"+ @ontouchend:stopPropagation>+ <CascadingValue Value="@this" IsFixed="true">+ <ListBox @ref="_resultListBox"+ Items="@Items"+ Context="item"+ RaiseSelectionEventOnKeyboardNavigation="false"+ OnSelectedIndexChanged="OnSelectedIndexChanged">+ <ItemTemplate>+ @ItemTemplate(item)+ </ItemTemplate>+ </ListBox>+ </CascadingValue>+ </Popover>+ </div></CascadingValue>\ No newline at end of filediff --git a/src/app/dev/DevToys.Blazor/Components/AutoSuggestBox/AutoSuggestBox.razor.cs b/src/app/dev/DevToys.Blazor/Components/AutoSuggestBox/AutoSuggestBox.razor.csindex ca501fd2f..ee84a4633 100644--- a/src/app/dev/DevToys.Blazor/Components/AutoSuggestBox/AutoSuggestBox.razor.cs+++ b/src/app/dev/DevToys.Blazor/Components/AutoSuggestBox/AutoSuggestBox.razor.cs@@ -1,8 +1,13 @@-namespace DevToys.Blazor.Components;+using System.Collections.Specialized;+using Microsoft.AspNetCore.Components.Web;-public partial class AutoSuggestBox : StyledComponentBase+namespace DevToys.Blazor.Components;++public partial class AutoSuggestBox<TElement> : StyledComponentBase, IDisposable where TElement : class{private TextBox? _textBox = default!;+ private ListBox<TElement>? _resultListBox = default!;+ private bool _showDropDown;[Parameter]public string? Header { get; set; }@@ -10,23 +15,119 @@ public partial class AutoSuggestBox : StyledComponentBase[Parameter]public string? Placeholder { get; set; }- [Parameter]- public string? Query { get; set; }-[Parameter]public bool IsReadOnly { get; set; }[Parameter]public EventCallback<string> QueryChanged { get; set; }+ [Parameter]+ public EventCallback<TElement?> QuerySubmitted { get; set; }++ [Parameter]+ public ICollection<TElement>? Items { get; set; }++ [Parameter]+ public RenderFragment<TElement> ItemTemplate { get; set; } = default!;++ public string? Query => _textBox?.Text;+internal ValueTask<bool> FocusAsync(){Guard.IsNotNull(_textBox);return _textBox.FocusAsync();}+ protected override void OnAfterRender(bool firstRender)+ {+ base.OnAfterRender(firstRender);++ if (firstRender)+ {+ if (Items is INotifyCollectionChanged notifyCollection)+ {+ notifyCollection.CollectionChanged += OnItemsChanged;+ }+ }+ }++ private void OnItemsChanged(object? sender, NotifyCollectionChangedEventArgs e)+ {+ Guard.IsNotNull(Items);+ _showDropDown = IsEnabled && !IsReadOnly && Items.Count > 0;+ }+private Task OnTextBoxTextChangedAsync(string text){return QueryChanged.InvokeAsync(text);}++ private void OnSelectedIndexChanged(int index)+ {+ SubmitQuery();+ }++ private void OnTextBoxKeyPress(KeyboardEventArgs ev)+ {+ if (string.Equals(ev.Key, "Enter", StringComparison.OrdinalIgnoreCase))+ {+ SubmitQuery();+ }+ else if (_showDropDown && _resultListBox is not null && Items is not null)+ {+ if (string.Equals(ev.Key, "ArrowDown", StringComparison.OrdinalIgnoreCase))+ {+ _resultListBox.SelectNextItem();+ }+ else if (string.Equals(ev.Key, "ArrowUp", StringComparison.OrdinalIgnoreCase))+ {+ _resultListBox.SelectPreviousItem();+ }+ }+ }++ private void OnTextBoxFocusLost()+ {+ // Bug workaround: user may click on an item in the drop down list. Text box will lose focus+ // before the item click event propagate. So we introduce a small delay here, to let time to propagate the event+ // before closing the drop down.+ // NOTE: This approach can be an issue if the user do a long-press on an item. Alternative possibility: track whether the focus+ // is in the list box?+ Task.Delay(150).ContinueWith(_ =>+ {+ InvokeAsync(() =>+ {+ _showDropDown = false;+ StateHasChanged();+ });+ });+ }++ private void SubmitQuery()+ {+ if (QuerySubmitted.HasDelegate)+ {+ TElement? selectedItem = null;+ if (_resultListBox is not null)+ {+ selectedItem = _resultListBox.SelectedItem;+ if (selectedItem == null && _resultListBox.Items?.Count > 0)+ {+ selectedItem = _resultListBox.Items.First();+ }+ }+ QuerySubmitted.InvokeAsync(selectedItem);+ _showDropDown = false;+ }+ }++ public void Dispose()+ {+ if (Items is INotifyCollectionChanged notifyCollection)+ {+ notifyCollection.CollectionChanged -= OnItemsChanged;+ }++ GC.SuppressFinalize(this);+ }}diff --git a/src/app/dev/DevToys.Blazor/Components/AutoSuggestBox/AutoSuggestBox.razor.scss b/src/app/dev/DevToys.Blazor/Components/AutoSuggestBox/AutoSuggestBox.razor.scssindex e69de29bb..9433dc05f 100644--- a/src/app/dev/DevToys.Blazor/Components/AutoSuggestBox/AutoSuggestBox.razor.scss+++ b/src/app/dev/DevToys.Blazor/Components/AutoSuggestBox/AutoSuggestBox.razor.scss@@ -0,0 +1,8 @@+.auto-suggest-box-drop-down {+ -webkit-border-radius: var(--overlay-corner-radius) !important;+ -webkit-border-top-left-radius: 0px !important;+ -webkit-border-top-right-radius: 0px !important;+ border-radius: var(--overlay-corner-radius) !important;+ border-top-left-radius: 0px !important;+ border-top-right-radius: 0px !important;+}diff --git a/src/app/dev/DevToys.Blazor/Components/ContextMenu/ContextMenu.razor b/src/app/dev/DevToys.Blazor/Components/ContextMenu/ContextMenu.razorindex 31d7a6809..082fab1c6 100644--- a/src/app/dev/DevToys.Blazor/Components/ContextMenu/ContextMenu.razor+++ b/src/app/dev/DevToys.Blazor/Components/ContextMenu/ContextMenu.razor@@ -22,38 +22,39 @@Style="@(PopoverStyle)"@ontouchend:stopPropagation><CascadingValue Value="@this" IsFixed="true">- <FocusTrapper @ref="_focusTrapper"- Style="display: contents;"- OnEscapeKeyPressed="OnEscapeKeyPressedAsync">- <ul class="menu-flyout" role="menu">- @if (Items is not null)- {- foreach (ContextMenuItem item in Items)- {- <li role="menuitem"- class="@($"context-menu-item {(item.IsEnabled ? string.Empty : "disabled")}")"- tabindex="0"- @onclick="@(() => OnItemClickAsync(item))"- @onkeypress="@((ev) => OnItemKeyPressAsync(ev, item))">- <div class="icon-container">- <FontIcon Glyph="@item.IconGlyph" FontFamily="@item.IconFontFamily" />- </div>- <TextBlock Class="text"- NoWrap="true">- @item.Text- </TextBlock>- @if (!string.IsNullOrWhiteSpace(item.KeyboardShortcut))- {- <TextBlock Appearance="TextBlockAppearance.Caption"- NoWrap="true"- Class="keyboard-accelerator">- @item.KeyboardShortcut- </TextBlock>- }- </li>- }- }- </ul>+ <FocusTrapper Style="display: contents;"+ OnEscapeKeyPressed="OnEscapeKeyPressedAsync"+ @onfocusout="OnEscapeKeyPressedAsync">+ <ListBox @ref="_listBox"+ Items="Items"+ Context="item"+ Role="menu"+ OverrideDefaultItemTemplate="true"+ Virtualize="false"+ RaiseSelectionEventOnKeyboardNavigation="false"+ OnSelectedIndexChanged="OnContextMenuItemSelected"+ Class="context-menu-list-box"+ @onkeydown="OnListBoxKeyDown">+ <ItemTemplate>+ <li role="menuitem"+ class="@($"context-menu-item {(_listBox!.SelectedItem == item ? "selected" : string.Empty)} {(item.IsEnabled ? string.Empty : "disabled")}")"+ aria-disabled="@(item.IsEnabled ? string.Empty : "true")">+ <div class="icon-container">+ <FontIcon Glyph="@item.IconGlyph" FontFamily="@item.IconFontFamily" />+ </div>+ <TextBlock Class="text"+ NoWrap="true"+ Text="@item.Text" />+ @if (!string.IsNullOrWhiteSpace(item.KeyboardShortcut))+ {+ <TextBlock Appearance="TextBlockAppearance.Caption"+ NoWrap="true"+ Class="keyboard-accelerator"+ Text="@item.KeyboardShortcut" />+ }+ </li>+ </ItemTemplate>+ </ListBox></FocusTrapper></CascadingValue></Popover>diff --git a/src/app/dev/DevToys.Blazor/Components/ContextMenu/ContextMenu.razor.cs b/src/app/dev/DevToys.Blazor/Components/ContextMenu/ContextMenu.razor.csindex 298d7a932..d0f3a9676 100644--- a/src/app/dev/DevToys.Blazor/Components/ContextMenu/ContextMenu.razor.cs+++ b/src/app/dev/DevToys.Blazor/Components/ContextMenu/ContextMenu.razor.cs@@ -4,12 +4,11 @@ using Microsoft.AspNetCore.Components.Web;namespace DevToys.Blazor.Components;-// TODO: handle Up and Down arrow navigation in the list of context menu items.// TODO: Close the context menu when the window lose focus or get resized.public partial class ContextMenu : StyledComponentBase{private bool _isOpen;- private FocusTrapper? _focusTrapper;+ private ListBox<ContextMenuItem>? _listBox;[Inject]internal ContextMenuService ContextMenuService { get; set; } = default!;@@ -24,7 +23,7 @@ public partial class ContextMenu : StyledComponentBase/// Gets or sets the menu items to display in the context menu./// </summary>[Parameter]- public IReadOnlyList<ContextMenuItem>? Items { get; set; }+ public ICollection<ContextMenuItem>? Items { get; set; }[Parameter]public EventCallback OnContextMenuOpening { get; set; }@@ -41,9 +40,9 @@ public partial class ContextMenu : StyledComponentBase{await base.OnAfterRenderAsync(firstRender);- if (_isOpen && _focusTrapper is not null)+ if (_isOpen && _listBox is not null){- await _focusTrapper.FocusAsync();+ await _listBox.FocusAsync();}}@@ -109,21 +108,20 @@ public partial class ContextMenu : StyledComponentBase}}- private async Task OnItemClickAsync(ContextMenuItem item)+ private void OnListBoxKeyDown(KeyboardEventArgs ev){- if (item.IsEnabled)+ if (_listBox is not null && string.Equals(ev.Key, "Tab", StringComparison.OrdinalIgnoreCase)){- CloseMenuAsync(null).Forget();- await item.OnClick.InvokeAsync();+ _listBox.SelectNextItem();}}- private async Task OnItemKeyPressAsync(KeyboardEventArgs ev, ContextMenuItem item)+ private void OnContextMenuItemSelected(int itemIndex){- if (string.Equals(ev.Code, "Enter", StringComparison.OrdinalIgnoreCase)- || string.Equals(ev.Code, "Space", StringComparison.OrdinalIgnoreCase))+ if (_listBox is not null && _listBox.SelectedItem is not null && _listBox.SelectedItem.IsEnabled){- await OnItemClickAsync(item);+ CloseMenuAsync(null).Forget();+ _listBox.SelectedItem.OnClick.InvokeAsync().Forget();}}}diff --git a/src/app/dev/DevToys.Blazor/Components/ContextMenu/ContextMenu.razor.scss b/src/app/dev/DevToys.Blazor/Components/ContextMenu/ContextMenu.razor.scssindex e30236169..a441cb3ba 100644--- a/src/app/dev/DevToys.Blazor/Components/ContextMenu/ContextMenu.razor.scss+++ b/src/app/dev/DevToys.Blazor/Components/ContextMenu/ContextMenu.razor.scss@@ -1,5 +1,3 @@-@use "../../Assets/sass/devtoys" as *;-.context-menu {display: contents;position: relative;@@ -9,29 +7,23 @@}}-.menu-flyout {- margin: 0px;- padding: 4px;- min-inline-size: 75px;- box-sizing: border-box;- border-radius: var(--overlay-corner-radius);- border: 1px solid var(--menu-flyout-presenter-border);- background-color: var(--menu-flyout-presenter-background);- -webkit-backdrop-filter: var(--menu-flyout-presenter-backdrop-filter);- backdrop-filter: var(--menu-flyout-presenter-backdrop-filter);- background-clip: padding-box;- box-shadow: var(--menu-flyout-presenter-shadow);+.context-menu-list-box {+ .list-box:focus, .list-box:focus-visible, .list-box:focus-within {+ outline: none;+ }.context-menu-item {padding: 5px 8px;cursor: default;- border-radius: inherit;+ border-radius: var(--control-corner-radius);background-color: var(--context-menu-item-background);color: var(--context-menu-item-foreground);display: flex;gap: 8px;+ margin: 3px;- &:hover {+ &:hover, &:focus, &:focus-visible, &.selected {+ outline: none;background-color: var(--context-menu-item-background-pointer-over);}@@ -76,4 +68,4 @@align-self: center;}}-}\ No newline at end of file+}diff --git a/src/app/dev/DevToys.Blazor/Components/FocusTrapper/FocusTrapper.razor.cs b/src/app/dev/DevToys.Blazor/Components/FocusTrapper/FocusTrapper.razor.csindex 6e9e80629..5ca29fbc2 100644--- a/src/app/dev/DevToys.Blazor/Components/FocusTrapper/FocusTrapper.razor.cs+++ b/src/app/dev/DevToys.Blazor/Components/FocusTrapper/FocusTrapper.razor.cs@@ -20,6 +20,12 @@ public partial class FocusTrapper : JSStyledComponentBasereturn JSRuntime.InvokeVoidWithErrorHandlingAsync("devtoys.DOM.setFocus", Element);}+ public override async ValueTask DisposeAsync()+ {+ await (await JSModule).InvokeVoidAsync("dispose", Element);+ await base.DisposeAsync();+ }+protected override async Task OnAfterRenderAsync(bool firstRender){await base.OnAfterRenderAsync(firstRender);@@ -37,10 +43,4 @@ public partial class FocusTrapper : JSStyledComponentBaseOnEscapeKeyPressed.InvokeAsync();}}-- public override async ValueTask DisposeAsync()- {- await (await JSModule).InvokeVoidAsync("dispose", Element);- await base.DisposeAsync();- }}diff --git a/src/app/dev/DevToys.Blazor/Components/FontIcon/FontIcon.razor b/src/app/dev/DevToys.Blazor/Components/FontIcon/FontIcon.razorindex 0ebf7536f..c73e3a9e4 100644--- a/src/app/dev/DevToys.Blazor/Components/FontIcon/FontIcon.razor+++ b/src/app/dev/DevToys.Blazor/Components/FontIcon/FontIcon.razor@@ -7,6 +7,8 @@style="@Style"@ref=Element@attributes="AdditionalAttributes"- data-glyph='@Glyph'>+ data-glyph='@Glyph'+ aria-hidden="true"+ role="presentation"></i></CascadingValue>\ No newline at end of filediff --git a/src/app/dev/DevToys.Blazor/Components/ListBox/ListBox.razor b/src/app/dev/DevToys.Blazor/Components/ListBox/ListBox.razornew file mode 100644index 000000000..fead02f44--- /dev/null+++ b/src/app/dev/DevToys.Blazor/Components/ListBox/ListBox.razor@@ -0,0 +1,59 @@+@namespace DevToys.Blazor.Components+@inherits JSStyledComponentBase+@typeparam TElement++<ScrollViewer Orientation="Orientation.Vertical"+ IsEnabled="@IsEnabled"+ Class="@FinalCssClasses"+ Style="@Style"+ AdditionalAttributes="@AdditionalAttributes">+ <ul @ref="Element"+ role="@Role"+ class="list-box"+ tabindex="0"+ @onkeydown="OnKeyDown">++ @if (Virtualize)+ {+ <Virtualize Items="@Items" Context="item">+ @RenderItem(item)+ </Virtualize>+ }+ else if (Items is not null)+ {+ foreach (var item in Items)+ {+ @RenderItem(item)+ }+ }++ </ul>+</ScrollViewer>++@code {+ private RenderFragment<TElement> RenderItem { get; set; } = default!;++ protected override Task OnInitializedAsync()+ {+ RenderItem = (item) => __builder =>+ {+ @if (!OverrideDefaultItemTemplate)+ {+ <ListBoxItem OnSelected="OnItemClick"+ IsSelected="object.ReferenceEquals(item, SelectedItem)"+ Item="item">+ @ItemTemplate(item)+ </ListBoxItem>+ }+ else+ {+ <div class="@((object.ReferenceEquals(item, SelectedItem) ? "selected" : string.Empty))"+ @onclick="@(() => OnItemClick(item))">+ @ItemTemplate(item)+ </div>+ }+ };++ return base.OnInitializedAsync();+ }+}\ No newline at end of filediff --git a/src/app/dev/DevToys.Blazor/Components/ListBox/ListBox.razor.cs b/src/app/dev/DevToys.Blazor/Components/ListBox/ListBox.razor.csnew file mode 100644index 000000000..c19211959--- /dev/null+++ b/src/app/dev/DevToys.Blazor/Components/ListBox/ListBox.razor.cs@@ -0,0 +1,216 @@+using System.Collections.Specialized;+using Microsoft.AspNetCore.Components.Web;++namespace DevToys.Blazor.Components;++public partial class ListBox<TElement> : JSStyledComponentBase where TElement : class+{+ private int _oldSelectedIndex;++ [Parameter]+ public ICollection<TElement>? Items { get; set; }++ [Parameter]+ public RenderFragment<TElement> ItemTemplate { get; set; } = default!;++ [Parameter]+ public int SelectedIndex { get; set; } = -1;++ [Parameter]+ public EventCallback<int> OnSelectedIndexChanged { get; set; }++ [Parameter]+ public string Role { get; set; } = "listbox";++ [Parameter]+ public bool OverrideDefaultItemTemplate { get; set; }++ [Parameter]+ public bool Virtualize { get; set; } = true;++ [Parameter]+ public bool RaiseSelectionEventOnKeyboardNavigation { get; set; } = true;++ internal TElement? SelectedItem { get; private set; }++ internal ValueTask<bool> FocusAsync()+ {+ return JSRuntime.InvokeVoidWithErrorHandlingAsync("devtoys.DOM.setFocus", Element);+ }+ internal void SelectNextItem()+ {+ if (Items is not null)+ {+ if (SelectedIndex == -1 || SelectedIndex == Items.Count - 1)+ {+ SetSelectedIndex(0, raiseEvent: RaiseSelectionEventOnKeyboardNavigation);+ }+ else+ {+ SetSelectedIndex(SelectedIndex + 1, raiseEvent: RaiseSelectionEventOnKeyboardNavigation);+ }+ }+ }++ internal void SelectPreviousItem()+ {+ if (Items is not null)+ {+ if (SelectedIndex == -1 || SelectedIndex == 0)+ {+ SetSelectedIndex(Items.Count - 1, raiseEvent: RaiseSelectionEventOnKeyboardNavigation);+ }+ else+ {+ SetSelectedIndex(SelectedIndex - 1, raiseEvent: RaiseSelectionEventOnKeyboardNavigation);+ }+ }+ }++ internal void SetSelectedIndex(int index)+ {+ SetSelectedIndex(index, raiseEvent: false);+ }++ internal void SetSelectedItem(TElement? item)+ {+ SetSelectedItem(item, raiseEvent: false);+ }++ public override ValueTask DisposeAsync()+ {+ if (Items is INotifyCollectionChanged notifyCollection)+ {+ notifyCollection.CollectionChanged -= OnItemsChanged;+ }+ return base.DisposeAsync();+ }++ protected override void OnParametersSet()+ {+ base.OnParametersSet();++ if (_oldSelectedIndex != SelectedIndex)+ {+ SetSelectedIndex(SelectedIndex, raiseEvent: false);+ }+ }++ protected override void OnAfterRender(bool firstRender)+ {+ base.OnAfterRender(firstRender);++ if (firstRender)+ {+ if (Items is INotifyCollectionChanged notifyCollection)+ {+ notifyCollection.CollectionChanged += OnItemsChanged;+ }+ }+ }++ private void SetSelectedIndex(int index, bool raiseEvent)+ {+ if (index >= Items?.Count)+ {+ ThrowHelper.ThrowArgumentOutOfRangeException(nameof(index));+ }++ SelectedIndex = index;+ _oldSelectedIndex = index;+ if (index > -1)+ {+ Guard.IsNotNull(Items);+ SelectedItem = Items.ElementAt(index);+ }+ else+ {+ SelectedItem = default;+ }++ if (raiseEvent)+ {+ RaiseOnSelectedIndexChanged();+ }++ StateHasChanged();+ }++ private void SetSelectedItem(TElement? item, bool raiseEvent)+ {+ Guard.IsNotNull(Items);+ if (item == SelectedItem)+ {+ return;+ }+ else if (item is null)+ {+ SetSelectedIndex(-1, raiseEvent);+ }+ else if (Items is IList<TElement> itemsList)+ {+ int itemIndex = itemsList.IndexOf(item);+ SetSelectedIndex(itemIndex, raiseEvent);+ }+ else+ {+ int i = 0;+ foreach (TElement childItem in Items)+ {+ if (object.ReferenceEquals(childItem, item))+ {+ SetSelectedIndex(i, raiseEvent);+ return;+ }+ i++;+ }++ SetSelectedIndex(-1, raiseEvent);+ }+ }++ private void RaiseOnSelectedIndexChanged()+ {+ if (OnSelectedIndexChanged.HasDelegate)+ {+ OnSelectedIndexChanged.InvokeAsync(SelectedIndex);+ }+ }++ private void OnItemsChanged(object? sender, NotifyCollectionChangedEventArgs e)+ {+ SetSelectedItem(SelectedItem, raiseEvent: false);+ }++ private void OnItemClick(object? selectedItem)+ {+ SetSelectedItem(selectedItem as TElement, raiseEvent: true);+ }++ private void OnKeyDown(KeyboardEventArgs ev)+ {+ if (Items is not null && Items.Count > 0)+ {+ if (string.Equals(ev.Key, "Enter", StringComparison.OrdinalIgnoreCase))+ {+ RaiseOnSelectedIndexChanged();+ }+ else if (string.Equals(ev.Key, "ArrowDown", StringComparison.OrdinalIgnoreCase))+ {+ SelectNextItem();+ }+ else if (string.Equals(ev.Key, "ArrowUp", StringComparison.OrdinalIgnoreCase))+ {+ SelectPreviousItem();+ }+ else if (string.Equals(ev.Key, "Home", StringComparison.OrdinalIgnoreCase))+ {+ SetSelectedIndex(Math.Min(0, Items.Count - 1));+ }+ else if (string.Equals(ev.Key, "End", StringComparison.OrdinalIgnoreCase))+ {+ SetSelectedIndex(Items.Count - 1);+ }+ }+ }+}diff --git a/src/app/dev/DevToys.Blazor/Components/ListBox/ListBox.razor.scss b/src/app/dev/DevToys.Blazor/Components/ListBox/ListBox.razor.scssnew file mode 100644index 000000000..bd4d8ab45--- /dev/null+++ b/src/app/dev/DevToys.Blazor/Components/ListBox/ListBox.razor.scss@@ -0,0 +1,4 @@+.list-box {+ margin: 0px;+ padding: 0px;+}diff --git a/src/app/dev/DevToys.Blazor/Components/ListBox/ListBoxItem.razor b/src/app/dev/DevToys.Blazor/Components/ListBox/ListBoxItem.razorindex 8718398a8..9c9ad33ff 100644--- a/src/app/dev/DevToys.Blazor/Components/ListBox/ListBoxItem.razor+++ b/src/app/dev/DevToys.Blazor/Components/ListBox/ListBoxItem.razor@@ -4,6 +4,7 @@<CascadingValue Value="this" IsFixed="true"><li class="list-box-item @(FinalCssClasses)"style="@(Style)"+ role="listitem"@ref=Element@attributes="AdditionalAttributes"@onclick="OnClickAsync">diff --git a/src/app/dev/DevToys.Blazor/Components/ListBox/ListBoxItem.razor.scss b/src/app/dev/DevToys.Blazor/Components/ListBox/ListBoxItem.razor.scssindex 2e7f99d33..b82d6f773 100644--- a/src/app/dev/DevToys.Blazor/Components/ListBox/ListBoxItem.razor.scss+++ b/src/app/dev/DevToys.Blazor/Components/ListBox/ListBoxItem.razor.scss@@ -2,11 +2,10 @@.list-box-item {@include flex( $align: center, $inline: true );- inline-size: calc(100% - 10px);position: relative;box-sizing: border-box;flex: 0 0 auto;- margin: 3px 5px;+ margin: 3px;padding-inline: 12px;border-radius: var(--control-corner-radius);outline: none;diff --git a/src/app/dev/DevToys.Blazor/Components/NavBar/NavBar.razor b/src/app/dev/DevToys.Blazor/Components/NavBar/NavBar.razorindex 5ad4fcc86..f144fc001 100644--- a/src/app/dev/DevToys.Blazor/Components/NavBar/NavBar.razor+++ b/src/app/dev/DevToys.Blazor/Components/NavBar/NavBar.razor@@ -4,6 +4,7 @@@inherits JSStyledComponentBase@typeparam TElement+@typeparam TSearchElement<CascadingValue Value="this" IsFixed="true"><div id=@Id@@ -62,6 +63,7 @@string searchButtonStyle = $"margin: 6px 4px 8px 5px; {(_sidebarState.IsCollapsed ? string.Empty : "display: none;")}";string searchTextBoxStyle = $"margin: 6px 17px 12px 16px; {(_sidebarState.IsCollapsed ? "display: none;" : string.Empty)}";+ // TODO: Localize<Button Appearance="ButtonAppearance.Stealth"Class="button-icon"Style="@searchButtonStyle"@@ -71,15 +73,19 @@<FontIcon Glyph="@('\uF68F')" /></Button><AutoSuggestBox @ref="_autoSuggestBox"- Style="@searchTextBoxStyle"- Placeholder="Type to search for tools...">+ Style="@searchTextBoxStyle"+ Placeholder="@SearchBarPlaceholder"+ QueryChanged="@SearchQueryChanged"+ QuerySubmitted="@SearchQuerySubmitted"+ Items="@SearchResultItems"+ ItemTemplate="@SearchResultItemTemplate"></AutoSuggestBox>}</div><div class="sidebar-body"><ScrollViewer Orientation="Orientation.Vertical">- <ul class="sidebar-items">+ <ul class="sidebar-items" role="listbox">@if (MenuItemsSource is not null){@foreach (TElement item in MenuItemsSource)@@ -87,6 +93,7 @@<NavBarItem Item="item"OwnerNavBar="@this"TElement="TElement"+ TSearchElement="TSearchElement"TitleTemplate="NavBarItemTitleTemplate"IconTemplate="NavBarItemIconTemplate"Children="item is IGroup itemGroup ? itemGroup.ChildrenItems : null"@@ -97,15 +104,18 @@</ScrollViewer></div><div class="sidebar-footer">- <ul class="sidebar-items">+ <ul class="sidebar-items" role="listbox">@if (FooterMenuItemsSource is not null){- <li class="sidebar-item-separator" style="margin-top: 0px;"/>+ <li class="sidebar-item-separator"+ style="margin-top: 0px;"+ role="separator"/>@foreach (TElement item in FooterMenuItemsSource){<NavBarItem Item="item"OwnerNavBar="@this"TElement="TElement"+ TSearchElement="TSearchElement"TitleTemplate="NavBarItemTitleTemplate"IconTemplate="NavBarItemIconTemplate"Children="item is IGroup itemGroup ? itemGroup.ChildrenItems : null"diff --git a/src/app/dev/DevToys.Blazor/Components/NavBar/NavBar.razor.cs b/src/app/dev/DevToys.Blazor/Components/NavBar/NavBar.razor.csindex 94b06abcb..138370903 100644--- a/src/app/dev/DevToys.Blazor/Components/NavBar/NavBar.razor.cs+++ b/src/app/dev/DevToys.Blazor/Components/NavBar/NavBar.razor.cs@@ -3,10 +3,13 @@ using Microsoft.AspNetCore.Components.Web;namespace DevToys.Blazor.Components;-public partial class NavBar<TElement> : JSStyledComponentBase where TElement : class+public partial class NavBar<TElement, TSearchElement>+ : JSStyledComponentBase+ where TElement : class+ where TSearchElement : class{private readonly NavBarState _sidebarState = new();- private AutoSuggestBox _autoSuggestBox = default!;+ private AutoSuggestBox<TSearchElement> _autoSuggestBox = default!;public string NavId { get; } = NewId();@@ -66,6 +69,36 @@ public partial class NavBar<TElement> : JSStyledComponentBase where TElement : c[Parameter]public EventCallback<bool> OnHiddenStateChanged { get; set; }+ /// <summary>+ /// Raised when the text in the search bar changed.+ /// </summary>+ [Parameter]+ public EventCallback<string> SearchQueryChanged { get; set; }++ /// <summary>+ /// Raised when the user press Enter in the search box or explicitly select an item in the search result list.+ /// </summary>+ [Parameter]+ public EventCallback<TSearchElement?> SearchQuerySubmitted { get; set; }++ /// <summary>+ /// Gets or sets the placeholder to display in the search bar.+ /// </summary>+ [Parameter]+ public string SearchBarPlaceholder { get; set; } = string.Empty;++ /// <summary>+ /// Gets or sets the list of items to display in the search bar's drop down list.+ /// </summary>+ [Parameter]+ public ICollection<TSearchElement>? SearchResultItems { get; set; }++ /// <summary>+ /// Gets or sets the template of search bar result item to use.+ /// </summary>+ [Parameter]+ public RenderFragment<TSearchElement> SearchResultItemTemplate { get; set; } = default!;+public NavBar(){_sidebarState.IsHiddenChanged += SidebarState_IsHiddenChanged;@@ -128,6 +161,9 @@ public partial class NavBar<TElement> : JSStyledComponentBase where TElement : cprivate void SidebarState_IsHiddenChanged(object? sender, EventArgs e){- OnHiddenStateChanged.InvokeAsync(_sidebarState.IsHidden);+ if (OnHiddenStateChanged.HasDelegate)+ {+ OnHiddenStateChanged.InvokeAsync(_sidebarState.IsHidden);+ }}}diff --git a/src/app/dev/DevToys.Blazor/Components/NavBar/NavBarItem.razor b/src/app/dev/DevToys.Blazor/Components/NavBar/NavBarItem.razorindex 5f021d816..ab344be16 100644--- a/src/app/dev/DevToys.Blazor/Components/NavBar/NavBarItem.razor+++ b/src/app/dev/DevToys.Blazor/Components/NavBar/NavBarItem.razor@@ -3,6 +3,7 @@@inherits StyledComponentBase@typeparam TElement+@typeparam TSearchElement<CascadingValue Value="this" IsFixed="true">@if (Item is ISeparator)@@ -18,6 +19,7 @@Item="Item"IsSelected="Item == OwnerNavBar.SelectedItem"Class="@FinalCssClasses"+ Style="margin: 3px 5px;"OnSelected=@OnItemSelectedAsync><div class="sidebar-item-icon">@IconTemplate(Item)@@ -41,12 +43,13 @@@if (isGroupWithChildren && IsExpanded){- <ul class="sidebar-items children">+ <ul class="sidebar-items children" role="listbox">@foreach (var childItem in group!.ChildrenItems!){<NavBarItem Item="childItem as TElement"OwnerNavBar="OwnerNavBar"TElement="TElement"+ TSearchElement="TSearchElement"TitleTemplate="TitleTemplate"IconTemplate="IconTemplate"Children="childItem is IGroup childItemGroup ? childItemGroup.ChildrenItems : null"@@ -58,6 +61,6 @@}else{- ThrowHelper.ThrowInvalidDataException($"{nameof(NavBarItem<TElement>)}.{nameof(Item)} is expected to implement '{nameof(IItem)}', '{nameof(IGroup)}' or '{nameof(ISeparator)}'");+ ThrowHelper.ThrowInvalidDataException($"{nameof(NavBarItem<TElement, TSearchElement>)}.{nameof(Item)} is expected to implement '{nameof(IItem)}', '{nameof(IGroup)}' or '{nameof(ISeparator)}'");}</CascadingValue>\ No newline at end of filediff --git a/src/app/dev/DevToys.Blazor/Components/NavBar/NavBarItem.razor.cs b/src/app/dev/DevToys.Blazor/Components/NavBar/NavBarItem.razor.csindex 412221ef6..95eb349ec 100644--- a/src/app/dev/DevToys.Blazor/Components/NavBar/NavBarItem.razor.cs+++ b/src/app/dev/DevToys.Blazor/Components/NavBar/NavBarItem.razor.cs@@ -2,12 +2,15 @@namespace DevToys.Blazor.Components;-public partial class NavBarItem<TElement> : StyledComponentBase where TElement : class+public partial class NavBarItem<TElement, TSearchElement>+ : StyledComponentBase+ where TElement : class+ where TSearchElement : class{private bool _isExpanded;[Parameter]- public NavBar<TElement> OwnerNavBar { get; set; } = default!;+ public NavBar<TElement, TSearchElement> OwnerNavBar { get; set; } = default!;[Parameter]public TElement Item { get; set; } = default!;diff --git a/src/app/dev/DevToys.Blazor/Components/Popover/Popover.razor.scss b/src/app/dev/DevToys.Blazor/Components/Popover/Popover.razor.scssindex 1b810bcda..679a6d41d 100644--- a/src/app/dev/DevToys.Blazor/Components/Popover/Popover.razor.scss+++ b/src/app/dev/DevToys.Blazor/Components/Popover/Popover.razor.scss@@ -1,5 +1,3 @@-@use "../../Assets/sass/devtoys" as *;-.popover {outline: 0;z-index: calc(var(--popover-zindex) + 1);@@ -17,6 +15,18 @@&.popover-open {opacity: 1;transition: opacity;++ margin: 0px;+ padding: 0px;+ min-inline-size: 75px;+ box-sizing: border-box;+ border-radius: var(--overlay-corner-radius);+ border: 1px solid var(--menu-flyout-presenter-border);+ background-color: var(--menu-flyout-presenter-background);+ -webkit-backdrop-filter: var(--menu-flyout-presenter-backdrop-filter);+ backdrop-filter: var(--menu-flyout-presenter-backdrop-filter);+ background-clip: padding-box;+ box-shadow: var(--menu-flyout-presenter-shadow);}&:not(.popover-open ) {@@ -30,4 +40,4 @@.popover-cascading-value {z-index: calc(var(--popover-zindex) + 3);}-}*/\ No newline at end of file+}*/diff --git a/src/app/dev/DevToys.Blazor/Components/TextBlock/TextBlock.razor.cs b/src/app/dev/DevToys.Blazor/Components/TextBlock/TextBlock.razor.csindex 1c65f6e0d..9329270d7 100644--- a/src/app/dev/DevToys.Blazor/Components/TextBlock/TextBlock.razor.cs+++ b/src/app/dev/DevToys.Blazor/Components/TextBlock/TextBlock.razor.cs@@ -1,20 +1,33 @@-using Microsoft.AspNetCore.Components.Rendering;+using DevToys.Api;+using Microsoft.AspNetCore.Components.Rendering;namespace DevToys.Blazor.Components;public class TextBlock : StyledComponentBase{+ /// <summary>+ /// Gets or sets the appearance of the text.+ /// </summary>[Parameter]public TextBlockAppearance Appearance { get; set; } = TextBlockAppearance.Body;+ /// <summary>+ /// Gets or sets whether the text can wrap or not.+ /// </summary>[Parameter]public bool NoWrap { get; set; }/// <summary>- /// Gets or sets the content to be rendered inside the component.+ /// Gets or sets the text to display.+ /// </summary>+ [Parameter]+ public string? Text { get; set; }++ /// <summary>+ /// Gets or sets spans to highlight./// </summary>[Parameter]- public RenderFragment? ChildContent { get; set; }+ public TextSpan[]? HighlightedSpans { get; set; }protected override void BuildRenderTree(RenderTreeBuilder builder){@@ -22,7 +35,45 @@ public class TextBlock : StyledComponentBasebuilder.AddAttribute(1, "id", Id);builder.AddAttribute(2, "class", $"text-block type-{Appearance.Class} {(NoWrap ? "no-wrap" : string.Empty)} {FinalCssClasses}");builder.AddAttribute(3, "style", Style);- builder.AddContent(4, ChildContent);++ if (HighlightedSpans is null || HighlightedSpans.Length == 0)+ {+ builder.AddContent(4, Text);+ }+ else if (!string.IsNullOrEmpty(Text!))+ {+ // Create a set of `text <mark> highlighted span </mark> text`+ int sequence = 4;+ int lastPlainTextStartPosition = 0;++ foreach (TextSpan highlightedSpan in HighlightedSpans.OrderBy(span => span.StartPosition))+ {+ string nonHighlightedText+ = Text.Substring(+ lastPlainTextStartPosition,+ Math.Max(0, highlightedSpan.StartPosition - lastPlainTextStartPosition));+ builder.AddContent(+ ++sequence,+ nonHighlightedText);++ builder.OpenElement(++sequence, "mark");++ string highlightedText+ = Text.Substring(+ highlightedSpan.StartPosition,+ highlightedSpan.Length);+ builder.AddContent(+ ++sequence,+ highlightedText);++ lastPlainTextStartPosition = highlightedSpan.EndPosition;++ builder.CloseElement();+ }++ builder.AddContent(sequence, Text.Substring(lastPlainTextStartPosition));+ }+builder.CloseElement();}}diff --git a/src/app/dev/DevToys.Blazor/Components/TextBlock/TextBlock.razor.scss b/src/app/dev/DevToys.Blazor/Components/TextBlock/TextBlock.razor.scssindex bd5c4b553..b4e4ec3bc 100644--- a/src/app/dev/DevToys.Blazor/Components/TextBlock/TextBlock.razor.scss+++ b/src/app/dev/DevToys.Blazor/Components/TextBlock/TextBlock.razor.scss@@ -9,6 +9,11 @@-webkit-font-smoothing: antialiased;-moz-osx-font-smoothing: grayscale;+ mark {+ background-color: var(--text-box-selection-highlight-color);+ color: currentColor;+ }+&.type- {&subtitle,&title,diff --git a/src/app/dev/DevToys.Blazor/Components/TextBox/TextBox.razor b/src/app/dev/DevToys.Blazor/Components/TextBox/TextBox.razorindex cd6f73735..d27d24148 100644--- a/src/app/dev/DevToys.Blazor/Components/TextBox/TextBox.razor+++ b/src/app/dev/DevToys.Blazor/Components/TextBox/TextBox.razor@@ -9,7 +9,7 @@@if (!string.IsNullOrWhiteSpace(Header)){- <TextBlock Appearance="TextBlockAppearance.Body" Class="text-box-header">@Header</TextBlock>+ <TextBlock Appearance="TextBlockAppearance.Body" Class="text-box-header" Text="@Header" />}<div class="text-box-container @(IsEnabled ? string.Empty : "disabled") @(_isContextMenuOpened ? "is-context-menu-opened" : string.Empty)"diff --git a/src/app/dev/DevToys.Blazor/Components/TextBox/TextBox.razor.cs b/src/app/dev/DevToys.Blazor/Components/TextBox/TextBox.razor.csindex 84a14fbb8..be0a4330e 100644--- a/src/app/dev/DevToys.Blazor/Components/TextBox/TextBox.razor.cs+++ b/src/app/dev/DevToys.Blazor/Components/TextBox/TextBox.razor.cs@@ -73,6 +73,22 @@ public partial class TextBox : MefComponentBasereturn JSRuntime.InvokeVoidWithErrorHandlingAsync("devtoys.DOM.setFocus", _input.Element);}+ public override async ValueTask DisposeAsync()+ {+ await (await JSModule).InvokeVoidAsync("dispose", Element);+ await base.DisposeAsync();+ }++ protected override async Task OnAfterRenderAsync(bool firstRender)+ {+ await base.OnAfterRenderAsync(firstRender);++ if (firstRender)+ {+ await (await JSModule).InvokeVoidAsync("initializeKeyboardTracking", Element);+ }+ }+private void OnClearClick(){SetTextAsync(string.Empty).Forget();@@ -169,7 +185,7 @@ public partial class TextBox : MefComponentBase{TextSpan selection = await GetSelectionAsync();Text ??= string.Empty;- string newText = Text.Substring(0, selection.StartPosition) + (string)clipboardData + Text.Substring(selection.StartPosition + selection.Length);+ string newText = Text.Substring(0, selection.StartPosition) + (string)clipboardData + Text.Substring(selection.EndPosition);await SetTextAsync(newText);}}diff --git a/src/app/dev/DevToys.Blazor/Components/TextBox/TextBox.razor.js b/src/app/dev/DevToys.Blazor/Components/TextBox/TextBox.razor.jsindex 24b30f9db..0a05c277b 100644--- a/src/app/dev/DevToys.Blazor/Components/TextBox/TextBox.razor.js+++ b/src/app/dev/DevToys.Blazor/Components/TextBox/TextBox.razor.js@@ -7,4 +7,23 @@ export function getSelectionSpan(input) {export function selectAll(input) {input.setSelectionRange(0, input.value.length);}+export function initializeKeyboardTracking(input) {+ input.addEventListener("keydown", onKeyDown);+ input.addEventListener("keypress", onKeyPress);+}+export function dispose(input) {+ input.removeEventListener("keydown", onKeyDown);+ input.removeEventListener("keydown", onKeyPress);+}+// Forbid Up/Down keys, as this text box should stays as a single-line text input anyway.+function onKeyDown(e) {+ if (e.key === "ArrowDown" || e.key === "ArrowUp") {+ e.preventDefault();+ }+}+function onKeyPress(e) {+ if (e.key === "ArrowDown" || e.key === "ArrowUp") {+ e.preventDefault();+ }+}//# sourceMappingURL=TextBox.razor.js.map\ No newline at end of filediff --git a/src/app/dev/DevToys.Blazor/Components/TextBox/TextBox.razor.ts b/src/app/dev/DevToys.Blazor/Components/TextBox/TextBox.razor.tsindex 9827386e2..734336383 100644--- a/src/app/dev/DevToys.Blazor/Components/TextBox/TextBox.razor.ts+++ b/src/app/dev/DevToys.Blazor/Components/TextBox/TextBox.razor.ts@@ -8,4 +8,27 @@ export function getSelectionSpan(input: HTMLInputElement): number[] {export function selectAll(input: HTMLInputElement): void {input.setSelectionRange(0, input.value.length);+}++export function initializeKeyboardTracking(input: HTMLInputElement): void {+ input.addEventListener("keydown", onKeyDown);+ input.addEventListener("keypress", onKeyPress);+}++export function dispose(input: HTMLInputElement): void {+ input.removeEventListener("keydown", onKeyDown);+ input.removeEventListener("keydown", onKeyPress);+}++// Forbid Up/Down keys, as this text box should stays as a single-line text input anyway.+function onKeyDown(e: KeyboardEvent): void {+ if (e.key === "ArrowDown" || e.key === "ArrowUp") {+ e.preventDefault();+ }+}++function onKeyPress(e: KeyboardEvent): void {+ if (e.key === "ArrowDown" || e.key === "ArrowUp") {+ e.preventDefault();+ }}\ No newline at end of filediff --git a/src/app/dev/DevToys.Blazor/Pages/Index.razor b/src/app/dev/DevToys.Blazor/Pages/Index.razorindex 3c63c893a..a701f1a92 100644--- a/src/app/dev/DevToys.Blazor/Pages/Index.razor+++ b/src/app/dev/DevToys.Blazor/Pages/Index.razor@@ -2,6 +2,7 @@@using DevToys.Blazor.Pages.SubPages@using DevToys.Core.Tools.ViewItems;+@using DevToys.Core.Tools;@namespace DevToys.Blazor.Pages@inherits MefComponentBase@@ -14,18 +15,34 @@OnClick="ContextMenuService.OnCloseContextMenuRequested" /><!-- Navigation View -->+<!-- TODO: Localize --><NavBar TElement="INotifyPropertyChanged"+ TSearchElement="GuiToolViewItem"MenuItemsSource="@ViewModel.HeaderAndBodyToolViewItems"FooterMenuItemsSource="@ViewModel.FooterToolViewItems"CanGoBack="@ViewModel.CanGoBack"@bind-SelectedItem="ViewModel.SelectedMenuItem"OnBackButtonClicked="OnBackButtonClicked"- OnHiddenStateChanged="OnHiddenStateChanged">+ OnHiddenStateChanged="OnHiddenStateChanged"+ SearchBarPlaceholder="Type to search for tools..."+ SearchQueryChanged="OnSearchQueryChanged"+ SearchQuerySubmitted="OnSearchQuerySubmitted"+ SearchResultItems="ViewModel.SearchResults"><!-- Header --><Header>- <TextBlock>DevToys</TextBlock>+ <TextBlock Text="DevToys" /></Header>+ <!-- Search box's result item design -->+ <SearchResultItemTemplate Context="item">+ <div class="sidebar-item-icon">+ <FontIcon FontFamily="@item.ToolInstance.IconFontName" Glyph="@item.ToolInstance.IconGlyph" />+ </div>+ <div class="sidebar-item-text">+ <TextBlock NoWrap="true" Text="@item.ToolInstance.LongDisplayTitle" HighlightedSpans="@item.MatchedSpans" />+ </div>+ </SearchResultItemTemplate>+<!-- Item design --><NavBarItemIconTemplate Context="item">@{@@ -58,7 +75,7 @@title = groupViewItem.DisplayTitle;}- <TextBlock NoWrap="true">@title</TextBlock>+ <TextBlock NoWrap="true" Text="@title" />}</NavBarItemTitleTemplate>@@ -69,7 +86,7 @@if (ViewModel.SelectedMenuItem is GuiToolViewItem guiToolViewItem){<div class="entranceThemeTransition">- <TextBlock Appearance="TextBlockAppearance.TitleLarge">@guiToolViewItem.ToolInstance.LongOrShortDisplayTitle</TextBlock>+ <TextBlock Appearance="TextBlockAppearance.TitleLarge" Text="@guiToolViewItem.ToolInstance.LongOrShortDisplayTitle" /><!-- TODO: Place here a component that takes in argument the guiToolViewItem --><Button IsEnabled="true" @onclick="OnSetFavorite">Set favorite</Button>diff --git a/src/app/dev/DevToys.Blazor/Pages/Index.razor.cs b/src/app/dev/DevToys.Blazor/Pages/Index.razor.csindex 6732f0c1e..c551e70e0 100644--- a/src/app/dev/DevToys.Blazor/Pages/Index.razor.cs+++ b/src/app/dev/DevToys.Blazor/Pages/Index.razor.cs@@ -67,6 +67,17 @@ public partial class Index : MefComponentBase}}+ private void OnSearchQueryChanged(string searchQuery)+ {+ ViewModel.SearchQuery = searchQuery;+ ViewModel.SearchBoxTextChangedCommand.Execute(null);+ }++ private void OnSearchQuerySubmitted(GuiToolViewItem? selectedItem)+ {+ ViewModel.SearchBoxQuerySubmittedCommand.Execute(selectedItem);+ }+internal void OnSetFavorite(){// WARNING: This should be done in ToolPageViewModel. Doing it here just for demo.diff --git a/src/app/dev/DevToys.Blazor/Pages/SubPages/ToolGroup.razor b/src/app/dev/DevToys.Blazor/Pages/SubPages/ToolGroup.razorindex f3dfcd651..3375d05db 100644--- a/src/app/dev/DevToys.Blazor/Pages/SubPages/ToolGroup.razor+++ b/src/app/dev/DevToys.Blazor/Pages/SubPages/ToolGroup.razor@@ -8,10 +8,10 @@Style="padding: 2.5rem"OnItemClick=@OnToolSelected><Header>- <TextBlock Appearance="@TextBlockAppearance.Subtitle" Style="font-size: 24px !important">@ViewModel.HeaderText</TextBlock>+ <TextBlock Appearance="@TextBlockAppearance.Subtitle" Style="font-size: 24px !important" Text="@ViewModel.HeaderText" /></Header><GroupHeaderTemplate Context="item">- <TextBlock Appearance="@TextBlockAppearance.Subtitle">@item</TextBlock>+ <TextBlock Appearance="@TextBlockAppearance.Subtitle" Text="@item" /></GroupHeaderTemplate><ItemTemplate Context="item"><div class="tool-group-grid-view-item">@@ -19,10 +19,10 @@<FontIcon Class="fonticon" FontFamily="@item.IconFontName" Glyph="@item.IconGlyph" /></div><div class="title">- <TextBlock Appearance="@TextBlockAppearance.BodyStrong">@item.LongOrShortDisplayTitle</TextBlock>+ <TextBlock Appearance="@TextBlockAppearance.BodyStrong" Text="@item.LongOrShortDisplayTitle" /></div><div class="description">- <TextBlock Appearance="@TextBlockAppearance.Caption">@item.Description</TextBlock>+ <TextBlock Appearance="@TextBlockAppearance.Caption" Text="@item.Description" /></div><div class="buttons" @onclick:stopPropagation="true"><Button Class="button"diff --git a/src/app/dev/DevToys.Business/Models/SearchBoxTextChangedReason.cs b/src/app/dev/DevToys.Business/Models/SearchBoxTextChangedReason.csdeleted file mode 100644index 458133e96..000000000--- a/src/app/dev/DevToys.Business/Models/SearchBoxTextChangedReason.cs+++ /dev/null@@ -1,20 +0,0 @@-namespace DevToys.Business.Models;--// Copy of Windows.UI.Xaml.Controls.AutoSuggestionBoxTextChangeReason-internal enum SearchBoxTextChangedReason-{- /// <summary>- /// The user edited the text.- /// </summary>- UserInput = 0,-- /// <summary>- /// The text was changed via code.- /// </summary>- ProgrammaticChange = 1,-- /// <summary>- /// The user selected one of the items in the auto-suggestion box.- /// </summary>- SuggestionChosen = 2-}diff --git a/src/app/dev/DevToys.Business/ViewModels/MainWindowViewModel.cs b/src/app/dev/DevToys.Business/ViewModels/MainWindowViewModel.csindex 98010e98a..c8c422447 100644--- a/src/app/dev/DevToys.Business/ViewModels/MainWindowViewModel.cs+++ b/src/app/dev/DevToys.Business/ViewModels/MainWindowViewModel.cs@@ -255,16 +255,10 @@ internal sealed partial class MainWindowViewModel : ObservableRecipient/// <summary>/// Command invoked when the search box's text changed./// </summary>- /// <param name="reason">The reason for which the text has changed.</param>[RelayCommand]- private void SearchBoxTextChanged(SearchBoxTextChangedReason reason)+ private void SearchBoxTextChanged(){- // Since selecting an item will also change the text,- // only listen to changes caused by user entering text.- if (reason == SearchBoxTextChangedReason.UserInput)- {- _guiToolProvider.SearchTools(SearchQuery, SearchResults);- }+ _guiToolProvider.SearchTools(SearchQuery, SearchResults);}/// <summary>diff --git a/src/app/dev/DevToys.Core/Tools/GuiToolProvider.cs b/src/app/dev/DevToys.Core/Tools/GuiToolProvider.csindex 266b68dc1..005776477 100644--- a/src/app/dev/DevToys.Core/Tools/GuiToolProvider.cs+++ b/src/app/dev/DevToys.Core/Tools/GuiToolProvider.cs@@ -1,5 +1,6 @@using System.Collections.ObjectModel;using System.Reflection;+using System.Text.RegularExpressions;using DevToys.Api;using DevToys.Core.Tools.Metadata;using DevToys.Core.Tools.ViewItems;@@ -621,7 +622,8 @@ public sealed partial class GuiToolProvidermatches.AddRange(spans);}- matchedSpans = matches.Distinct().ToArray();+ // Sort spans and make sure no span overlap.+ matchedSpans = CleanUpMatchedSpans(matches);}private static void WeightMatch(@@ -686,6 +688,37 @@ public sealed partial class GuiToolProvider}}+ private static TextSpan[] CleanUpMatchedSpans(List<TextSpan>? spans)+ {+ if (spans is null)+ {+ return Array.Empty<TextSpan>();+ }++ spans.Sort((x, y) => x.StartPosition.CompareTo(y.StartPosition));++ for (int i = 0; i < spans.Count - 1; i++)+ {+ if (spans[i].EndPosition > spans[i + 1].StartPosition)+ {+ if (spans[i].EndPosition >= spans[i + 1].EndPosition)+ {+ spans.RemoveAt(i + 1);+ i--;+ }+ else+ {+ spans[i]+ = new TextSpan(+ spans[i].StartPosition,+ spans[i].Length - (spans[i].EndPosition - spans[i + 1].StartPosition));+ }+ }+ }++ return spans.ToArray();+ }+[LoggerMessage(0, LogLevel.Information, "Set '{toolName}' as the most recently used tool.")]partial void LogSetMostRecentUsedTool(string toolName);}