Skip to content

Commit

Permalink
Implement RichSuggestBox (#3650)
Browse files Browse the repository at this point in the history
<!-- 🚨 Please Do Not skip any instructions and information mentioned below as they are all required and essential to evaluate and test the PR. By fulfilling all the required information you will be able to reduce the volume of questions and most likely help merge the PR faster 🚨 -->

<!-- 📝 It is preferred if you keep the "☑️ Allow edits by maintainers" checked in the Pull Request Template as it increases collaboration with the Toolkit maintainers by permitting commits to your PR branch (only) created from your fork.  This can let us quickly make fixes for minor typos or forgotten StyleCop issues during review without needing to wait on you doing extra work. Let us help you help us! 🎉 -->


## Fixes #
<!-- Add the relevant issue number after the "#" mentioned above (for ex: Fixes #1234) which will automatically close the issue once the PR is merged. -->
Closes #3649 

<!-- Add a brief overview here of the feature/bug & fix. -->
Implement rich suggest text control as discussed in the issue.

## PR Type
What kind of change does this PR introduce?
<!-- Please uncomment one or more that apply to this PR. -->

<!-- - Bugfix -->
- Feature
<!-- - Code style update (formatting) -->
<!-- - Refactoring (no functional changes, no api changes) -->
<!-- - Build or CI related changes -->
<!-- - Documentation content changes -->
<!-- - Sample app changes -->
<!-- - Other... Please describe: -->


## What is the current behavior?
<!-- Please describe the current behavior that you are modifying, or link to a relevant issue. -->
None. The control did not exist before this PR.


## What is the new behavior?
<!-- Describe how was this issue resolved or changed? -->
'RichSuggestBox' is now a usable control in the `Microsoft.Toolkit.Uwp.UI.Controls` namespace.


## PR Checklist

Please check if your PR fulfills the following requirements:

- [ ] Tested code with current [supported SDKs](../readme.md#supported)
- [x] Pull Request has been submitted to the documentation repository [instructions](..\contributing.md#docs). Link: MicrosoftDocs/WindowsCommunityToolkitDocs#558
- [x] Sample in sample app has been added / updated (for bug fixes / features)
    - [x] Icon has been created (if new sample) following the [Thumbnail Style Guide and templates](https://github.com/windows-toolkit/WindowsCommunityToolkit-design-assets)
- [ ] New major technical changes in the toolkit have or will be added to the [Wiki](https://github.com/windows-toolkit/WindowsCommunityToolkit/wiki) e.g. build changes, source generators, testing infrastructure, sample creation changes, etc...
- [x] Tests for the changes have been added (for bug fixes / features) (if applicable)
- [x] Header has been added to all new source files (run *build/UpdateHeaders.bat*)
- [x] Contains **NO** breaking changes

<!-- If this PR contains a breaking change, please describe the impact and migration path for existing applications below. 
     Please note that breaking changes are likely to be rejected within minor release cycles or held until major versions. -->


## Other information

### Convenient issue tracker

- Limited styling options for tokens. Only text styling options are available.
- Tokens are raw text and not UI elements. UI events (e.g. `UIElement.PointerEntered`) are not available. ~~This makes behaviors like showing flyout when hover mouse over the token impossible.~~
- Tokens are always underlined.
- Tokens cannot adapt to theme change dynamically. They will lose foreground color while having the same background color which will most likely introduce bad contrast.
- Cannot disable spelling check on tokens (token text may have red underline).
- ~~Cannot use Tab to select a suggestion due to conflict with the accessibility feature.~~
- Deleted tokens will be kept in an internal list until cleared programmatically to support Undo and Redo.

### RichEditBox issues

Below are `RichEditBox` related issues encountered during the development of this control.

- Getting `Link` property from a range might change the range.
- Replacing a formatted link at the beginning of the document does not reset the formatting. The replaced text still has the same formatting.
- Setting the `Link` property can sometimes fail but only when the target text is at the beginning of the document.
- There is no event for when text is about to change. `TextChanging` and `SelectionChanging` are invoked after the text has changed.
- Character format foreground color cannot display a range of colors (e.g. #F7FFB3)
  • Loading branch information
msftbot[bot] authored Aug 26, 2021
2 parents d9e8845 + 46bd862 commit fe9ac89
Show file tree
Hide file tree
Showing 29 changed files with 2,890 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -274,6 +274,7 @@
<Content Include="SamplePages\Graph\PersonView.png" />
<Content Include="SamplePages\Primitives\ConstrainedBox.png" />
<Content Include="SamplePages\Primitives\SwitchPresenter.png" />
<Content Include="SamplePages\RichSuggestBox\RichSuggestBox.png" />
<Content Include="SamplePages\TabbedCommandBar\TabbedCommandBar.png" />
<Content Include="SamplePages\Animations\Effects\FadeBehavior.png" />
<Content Include="SamplePages\ColorPicker\ColorPicker.png" />
Expand Down Expand Up @@ -506,6 +507,10 @@
<Compile Include="SamplePages\MetadataControl\MetadataControlPage.xaml.cs">
<DependentUpon>MetadataControlPage.xaml</DependentUpon>
</Compile>
<Compile Include="SamplePages\RichSuggestBox\RichSuggestBoxPage.xaml.cs">
<DependentUpon>RichSuggestBoxPage.xaml</DependentUpon>
</Compile>
<Compile Include="SamplePages\RichSuggestBox\SuggestionTemplateSelector.cs" />
<Compile Include="SamplePages\TilesBrush\TilesBrushPage.xaml.cs">
<DependentUpon>TilesBrushPage.xaml</DependentUpon>
</Compile>
Expand Down Expand Up @@ -627,6 +632,7 @@
<SubType>Designer</SubType>
</Content>
<Content Include="SamplePages\KeyDownTriggerBehavior\KeyDownTriggerBehaviorXaml.bind" />
<Content Include="SamplePages\RichSuggestBox\RichSuggestBoxCode.bind" />
</ItemGroup>
<ItemGroup>
<Compile Include="App.xaml.cs">
Expand Down Expand Up @@ -986,6 +992,14 @@
<Content Include="SamplePages\Primitives\SwitchPresenter.bind">
<SubType>Designer</SubType>
</Content>
<Content Include="SamplePages\RichSuggestBox\RichSuggestBoxXaml.bind">
<SubType>Designer</SubType>
<Generator>MSBuild:Compile</Generator>
</Content>
<Page Include="SamplePages\RichSuggestBox\RichSuggestBoxPage.xaml">
<SubType>Designer</SubType>
<Generator>MSBuild:Compile</Generator>
</Page>
<Page Include="SamplePages\TilesBrush\TilesBrushPage.xaml">
<Generator>MSBuild:Compile</Generator>
<SubType>Designer</SubType>
Expand Down
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
private void SuggestingBox_OnTokenPointerOver(RichSuggestBox sender, RichSuggestTokenPointerOverEventArgs args)
{
var flyout = (Flyout)FlyoutBase.GetAttachedFlyout(sender);
var pointerPosition = args.CurrentPoint.Position;

if (flyout?.Content is ContentPresenter cp && sender.TextDocument.Selection.Type != SelectionType.Normal &&
(!flyout.IsOpen || cp.Content != args.Token.Item))
{
this._dispatcherQueue.TryEnqueue(() =>
{
cp.Content = args.Token.Item;
flyout.ShowAt(sender, new FlyoutShowOptions
{
Position = pointerPosition,
ExclusionRect = sender.GetRectFromRange(args.Range),
ShowMode = FlyoutShowMode.TransientWithDismissOnPointerMoveAway,
});
});
}
}

private void SuggestingBox_OnSuggestionChosen(RichSuggestBox sender, SuggestionChosenEventArgs args)
{
if (args.Prefix == "#")
{
args.Format.BackgroundColor = Colors.DarkOrange;
args.Format.ForegroundColor = Colors.OrangeRed;
args.Format.Bold = FormatEffect.On;
args.Format.Italic = FormatEffect.On;
args.DisplayText = ((SampleDataType)args.SelectedItem).Text;
}
else
{
args.DisplayText = ((SampleEmailDataType)args.SelectedItem).DisplayName;
}
}

private void SuggestingBox_OnSuggestionRequested(RichSuggestBox sender, SuggestionRequestedEventArgs args)
{
if (args.Prefix == "#")
{
sender.ItemsSource =
this._samples.Where(x => x.Text.Contains(args.QueryText, StringComparison.OrdinalIgnoreCase));
}
else
{
sender.ItemsSource =
this._emailSamples.Where(x => x.DisplayName.Contains(args.QueryText, StringComparison.OrdinalIgnoreCase));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<Page x:Class="Microsoft.Toolkit.Uwp.SampleApp.SamplePages.RichSuggestBoxPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:controls="using:Microsoft.Toolkit.Uwp.UI.Controls"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="using:Microsoft.Toolkit.Uwp.SampleApp.SamplePages"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<Page.Resources>
<ResourceDictionary>
<local:SuggestionTemplateSelector x:Key="SuggestionTemplateSelector" />
<local:NameToColorConverter x:Key="NameToColorConverter" />
</ResourceDictionary>
</Page.Resources>

<Grid Visibility="Collapsed">
<controls:RichSuggestBox />
<ListView />
</Grid>
</Page>
Original file line number Diff line number Diff line change
@@ -0,0 +1,191 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Toolkit.Uwp.UI;
using Microsoft.Toolkit.Uwp.UI.Controls;
using Windows.System;
using Windows.UI;
using Windows.UI.Text;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;

namespace Microsoft.Toolkit.Uwp.SampleApp.SamplePages
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class RichSuggestBoxPage : Page, IXamlRenderListener
{
private readonly List<SampleEmailDataType> _emailSamples = new List<SampleEmailDataType>()
{
new SampleEmailDataType() { FirstName = "Marcus", FamilyName = "Perryman" },
new SampleEmailDataType() { FirstName = "Michael", FamilyName = "Hawker" },
new SampleEmailDataType() { FirstName = "Matt", FamilyName = "Lacey" },
new SampleEmailDataType() { FirstName = "Alexandre", FamilyName = "Chohfi" },
new SampleEmailDataType() { FirstName = "Filip", FamilyName = "Wallberg" },
new SampleEmailDataType() { FirstName = "Shane", FamilyName = "Weaver" },
new SampleEmailDataType() { FirstName = "Vincent", FamilyName = "Gromfeld" },
new SampleEmailDataType() { FirstName = "Sergio", FamilyName = "Pedri" },
new SampleEmailDataType() { FirstName = "Alex", FamilyName = "Wilber" },
new SampleEmailDataType() { FirstName = "Allan", FamilyName = "Deyoung" },
new SampleEmailDataType() { FirstName = "Adele", FamilyName = "Vance" },
new SampleEmailDataType() { FirstName = "Grady", FamilyName = "Archie" },
new SampleEmailDataType() { FirstName = "Megan", FamilyName = "Bowen" },
new SampleEmailDataType() { FirstName = "Ben", FamilyName = "Walters" },
new SampleEmailDataType() { FirstName = "Debra", FamilyName = "Berger" },
new SampleEmailDataType() { FirstName = "Emily", FamilyName = "Braun" },
new SampleEmailDataType() { FirstName = "Christine", FamilyName = "Cline" },
new SampleEmailDataType() { FirstName = "Enrico", FamilyName = "Catteneo" },
new SampleEmailDataType() { FirstName = "Davit", FamilyName = "Badalyan" },
new SampleEmailDataType() { FirstName = "Diego", FamilyName = "Siciliani" },
new SampleEmailDataType() { FirstName = "Raul", FamilyName = "Razo" },
new SampleEmailDataType() { FirstName = "Miriam", FamilyName = "Graham" },
new SampleEmailDataType() { FirstName = "Lynne", FamilyName = "Robbins" },
new SampleEmailDataType() { FirstName = "Lydia", FamilyName = "Holloway" },
new SampleEmailDataType() { FirstName = "Nestor", FamilyName = "Wilke" },
new SampleEmailDataType() { FirstName = "Patti", FamilyName = "Fernandez" },
new SampleEmailDataType() { FirstName = "Pradeep", FamilyName = "Gupta" },
new SampleEmailDataType() { FirstName = "Joni", FamilyName = "Sherman" },
new SampleEmailDataType() { FirstName = "Isaiah", FamilyName = "Langer" },
new SampleEmailDataType() { FirstName = "Irvin", FamilyName = "Sayers" },
new SampleEmailDataType() { FirstName = "Tung", FamilyName = "Huynh" },
};

private readonly List<SampleDataType> _samples = new List<SampleDataType>()
{
new SampleDataType() { Text = "Account", Icon = Symbol.Account },
new SampleDataType() { Text = "Add Friend", Icon = Symbol.AddFriend },
new SampleDataType() { Text = "Attach", Icon = Symbol.Attach },
new SampleDataType() { Text = "Attach Camera", Icon = Symbol.AttachCamera },
new SampleDataType() { Text = "Audio", Icon = Symbol.Audio },
new SampleDataType() { Text = "Block Contact", Icon = Symbol.BlockContact },
new SampleDataType() { Text = "Calculator", Icon = Symbol.Calculator },
new SampleDataType() { Text = "Calendar", Icon = Symbol.Calendar },
new SampleDataType() { Text = "Camera", Icon = Symbol.Camera },
new SampleDataType() { Text = "Contact", Icon = Symbol.Contact },
new SampleDataType() { Text = "Favorite", Icon = Symbol.Favorite },
new SampleDataType() { Text = "Link", Icon = Symbol.Link },
new SampleDataType() { Text = "Mail", Icon = Symbol.Mail },
new SampleDataType() { Text = "Map", Icon = Symbol.Map },
new SampleDataType() { Text = "Phone", Icon = Symbol.Phone },
new SampleDataType() { Text = "Pin", Icon = Symbol.Pin },
new SampleDataType() { Text = "Rotate", Icon = Symbol.Rotate },
new SampleDataType() { Text = "Rotate Camera", Icon = Symbol.RotateCamera },
new SampleDataType() { Text = "Send", Icon = Symbol.Send },
new SampleDataType() { Text = "Tags", Icon = Symbol.Tag },
new SampleDataType() { Text = "UnFavorite", Icon = Symbol.UnFavorite },
new SampleDataType() { Text = "UnPin", Icon = Symbol.UnPin },
new SampleDataType() { Text = "Zoom", Icon = Symbol.Zoom },
new SampleDataType() { Text = "ZoomIn", Icon = Symbol.ZoomIn },
new SampleDataType() { Text = "ZoomOut", Icon = Symbol.ZoomOut },
};

private RichSuggestBox _rsb;
private RichSuggestBox _tsb;
private DispatcherQueue _dispatcherQueue;

public RichSuggestBoxPage()
{
this.InitializeComponent();
this._dispatcherQueue = DispatcherQueue.GetForCurrentThread();
Loaded += (sender, e) => { this.OnXamlRendered(this); };
}

public void OnXamlRendered(FrameworkElement control)
{
if (this._rsb != null)
{
this._rsb.SuggestionChosen -= this.SuggestingBox_OnSuggestionChosen;
this._rsb.SuggestionRequested -= this.SuggestingBox_OnSuggestionRequested;
}

if (this._tsb != null)
{
this._tsb.SuggestionChosen -= this.SuggestingBox_OnSuggestionChosen;
this._tsb.SuggestionRequested -= this.SuggestingBox_OnSuggestionRequested;
this._tsb.TokenPointerOver -= this.SuggestingBox_OnTokenPointerOver;
}

if (control.FindChild("SuggestingBox") is RichSuggestBox rsb)
{
this._rsb = rsb;
this._rsb.SuggestionChosen += this.SuggestingBox_OnSuggestionChosen;
this._rsb.SuggestionRequested += this.SuggestingBox_OnSuggestionRequested;
}

if (control.FindChild("PlainTextSuggestingBox") is RichSuggestBox tsb)
{
this._tsb = tsb;
this._tsb.SuggestionChosen += this.SuggestingBox_OnSuggestionChosen;
this._tsb.SuggestionRequested += this.SuggestingBox_OnSuggestionRequested;
this._tsb.TokenPointerOver += this.SuggestingBox_OnTokenPointerOver;
}

if (control.FindChild("TokenListView1") is ListView tls1)
{
tls1.ItemsSource = this._rsb?.Tokens;
}

if (control.FindChild("TokenListView2") is ListView tls2)
{
tls2.ItemsSource = this._tsb?.Tokens;
}
}

private void SuggestingBox_OnTokenPointerOver(RichSuggestBox sender, RichSuggestTokenPointerOverEventArgs args)
{
var flyout = (Flyout)FlyoutBase.GetAttachedFlyout(sender);
var pointerPosition = args.CurrentPoint.Position;

if (flyout?.Content is ContentPresenter cp && sender.TextDocument.Selection.Type != SelectionType.Normal &&
(!flyout.IsOpen || cp.Content != args.Token.Item))
{
this._dispatcherQueue.TryEnqueue(() =>
{
cp.Content = args.Token.Item;
flyout.ShowAt(sender, new FlyoutShowOptions
{
Position = pointerPosition,
ExclusionRect = sender.GetRectFromRange(args.Range),
ShowMode = FlyoutShowMode.TransientWithDismissOnPointerMoveAway,
});
});
}
}

private void SuggestingBox_OnSuggestionChosen(RichSuggestBox sender, SuggestionChosenEventArgs args)
{
if (args.Prefix == "#")
{
args.Format.BackgroundColor = Colors.DarkOrange;
args.Format.ForegroundColor = Colors.OrangeRed;
args.Format.Bold = FormatEffect.On;
args.Format.Italic = FormatEffect.On;
args.DisplayText = ((SampleDataType)args.SelectedItem).Text;
}
else
{
args.DisplayText = ((SampleEmailDataType)args.SelectedItem).DisplayName;
}
}

private void SuggestingBox_OnSuggestionRequested(RichSuggestBox sender, SuggestionRequestedEventArgs args)
{
if (args.Prefix == "#")
{
sender.ItemsSource =
this._samples.Where(x => x.Text.Contains(args.QueryText, StringComparison.OrdinalIgnoreCase));
}
else
{
sender.ItemsSource =
this._emailSamples.Where(x => x.DisplayName.Contains(args.QueryText, StringComparison.OrdinalIgnoreCase));
}
}
}
}
Loading

0 comments on commit fe9ac89

Please sign in to comment.