diff --git a/.gitattributes b/.gitattributes index 1ff0c4230..5896c1692 100644 --- a/.gitattributes +++ b/.gitattributes @@ -17,7 +17,7 @@ # # Merging from the command prompt will add diff markers to the files if there # are conflicts (Merging from VS is not affected by the settings below, in VS -# the diff markers are never inserted). Diff markers may cause the following +# the diff markers are never inserted). Diff markers may cause the following # file extensions to fail to load in VS. An alternative would be to treat # these files as binary and thus will always conflict and require user # intervention with every merge. To do so, just uncomment the entries below @@ -46,9 +46,9 @@ ############################################################################### # diff behavior for common document formats -# +# # Convert binary document formats to text before diffing them. This feature -# is only available from the command line. Turn it on by uncommenting the +# is only available from the command line. Turn it on by uncommenting the # entries below. ############################################################################### #*.doc diff=astextplain diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md index 510e2f03e..1bdcc56d2 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.md +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -4,23 +4,26 @@ about: Create a report to help us fix something that isn't working as expected title: '' labels: "bug :bug:" assignees: '' - --- +IF NOT CERTAIN ABOUT THE ISSUE AND REQUIRE MORE CLARITY THEN PLEASE POST ON "QUESTIONS & HELP" CATEGORY OF THE DISCUSSIONS PLATFORM [https://github.com/CommunityToolkit/WindowsCommunityToolkit/discussions/categories/questions-help] WHERE YOU CAN DISCUSS AND ENGAGE WITH THE COMMUNITY TO GAIN FURTHER CLARITY REGARDING THE ISSUE 🚨 --> ## Describe the bug + A clear and concise description of what the bug is. - [ ] Is this bug a regression in the toolkit? If so, what toolkit version did you last see it work: ## Steps to Reproduce -- [ ] Can this be reproduced in the Sample App? (Either in a sample as-is or with new XAML pasted in the editor.) If so, please provide custom XAML or steps to reproduce. If not, let us know why it can't be reproduced (e.g. more complex setup, environment, dependencies, etc...) +- [ ] Can this be reproduced in the Sample App? (Either in a sample as-is or with new XAML pasted in the editor.) If so, please provide custom XAML or steps to reproduce. If not, let us know why it can't be reproduced (e.g. more complex setup, environment, dependencies, etc...) + + Steps to reproduce the behavior: + 1. Given the following environment (Sample App w/ XAML, Project with Isolated setup, etc...) 2. Go to '...' 3. Click on '....' @@ -30,46 +33,52 @@ Steps to reproduce the behavior: ## Expected behavior -A clear and concise description of what you expected to happen. + + ## Screenshots -If applicable, add screenshots to help explain your problem. + + ## Environment - -``` -NuGet Package(s): + + + +NuGet Package(s): Package Version(s): Windows 10 Build Number: + - [ ] Fall Creators Update (16299) - [ ] April 2018 Update (17134) - [ ] October 2018 Update (17763) - [ ] May 2019 Update (18362) - [ ] May 2020 Update (19041) -- [ ] Insider Build (build number: ) +- [ ] Insider Build ({build_number}) App min and target version: + - [ ] Fall Creators Update (16299) - [ ] April 2018 Update (17134) - [ ] October 2018 Update (17763) - [ ] May 2019 Update (18362) - [ ] May 2020 Update (19041) -- [ ] Insider Build (xxxxx) +- [ ] Insider Build ({build_number}) Device form factor: + - [ ] Desktop - [ ] Xbox - [ ] Surface Hub - [ ] IoT -Visual Studio -- [ ] 2017 (version: ) -- [ ] 2019 (version: ) -- [ ] 2019 Preview (version: ) +Visual Studio version: -``` +- [ ] 2017 (15.{minor_version}) +- [ ] 2019 (16.{minor_version}) +- [ ] 2022 (17.{minor_version}) ## Additional context -Add any other context about the problem here. + + diff --git a/.github/ISSUE_TEMPLATE/documentation.md b/.github/ISSUE_TEMPLATE/documentation.md index ef255cc78..1fd2f3c19 100644 --- a/.github/ISSUE_TEMPLATE/documentation.md +++ b/.github/ISSUE_TEMPLATE/documentation.md @@ -4,7 +4,6 @@ about: I have a documentation suggestion or question title: "[Docs]" labels: documentation assignees: '' - --- +IF NOT CERTAIN ABOUT THE FEATURE AND REQUIRE MORE CLARITY THEN PLEASE POST ON "IDEAS" CATEGORY OF THE DISCUSSIONS PLATFORM [https://github.com/CommunityToolkit/WindowsCommunityToolkit/discussions/categories/ideas] WHERE YOU CAN DISCUSS AND ENGAGE WITH THE COMMUNITY TO GAIN FURTHER CLARITY REGARDING THE FEATURE 🚨 --> ## Describe the problem this feature would solve + - ## Describe the solution + - ## Describe alternatives you've considered + - ## Additional context & Screenshots + diff --git a/.github/ISSUE_TEMPLATE/question.md b/.github/ISSUE_TEMPLATE/question.md index 01f64286d..b10fd188d 100644 --- a/.github/ISSUE_TEMPLATE/question.md +++ b/.github/ISSUE_TEMPLATE/question.md @@ -4,7 +4,6 @@ about: I have a question about how to use something in the toolkit. title: "[Question]" labels: "question :grey_question:" assignees: '' - --- - + +## Fixes -## Fixes # - + ## PR Type + What kind of change does this PR introduce? + @@ -23,30 +25,30 @@ What kind of change does this PR introduce? - ## What is the current behavior? + - ## What is the new behavior? - + ## PR Checklist -Please check if your PR fulfills the following requirements: +Please check if your PR fulfills the following requirements: -- [ ] Tested code with current [supported SDKs](../readme.md#supported) -- [ ] Pull Request has been submitted to the documentation repository [instructions](..\contributing.md#docs). Link: +- [ ] Tested code with current [supported SDKs](../#supported) +- [ ] Pull Request has been submitted to the documentation repository [instructions](../blob/main/Contributing.md#docs). Link: - [ ] Sample in sample app has been added / updated (for bug fixes / features) - - [ ] Icon has been created (if new sample) following the [Thumbnail Style Guide and templates](https://github.com/CommunityToolkit/WindowsCommunityToolkit-design-assets) + - [ ] Icon has been created (if new sample) following the [Thumbnail Style Guide and templates](https://github.com/CommunityToolkit/WindowsCommunityToolkit-design-assets) - [ ] New major technical changes in the toolkit have or will be added to the [Wiki](https://github.com/CommunityToolkit/WindowsCommunityToolkit/wiki) e.g. build changes, source generators, testing infrastructure, sample creation changes, etc... - [ ] Tests for the changes have been added (for bug fixes / features) (if applicable) -- [ ] Header has been added to all new source files (run *build/UpdateHeaders.bat*) +- [ ] Header has been added to all new source files (run _build/UpdateHeaders.bat_) - [ ] Contains **NO** breaking changes - +Please note that breaking changes are likely to be rejected within minor release cycles or held until major versions. --> ## Other information + + \ No newline at end of file diff --git a/.runsettings b/.runsettings index ff838beea..44f0672a1 100644 --- a/.runsettings +++ b/.runsettings @@ -1,6 +1,6 @@ - 0 + 0 0 ClassLevel diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md index 71537d29c..1f377cc37 100644 --- a/CODE_OF_CONDUCT.md +++ b/CODE_OF_CONDUCT.md @@ -68,9 +68,9 @@ members of the project's leadership. ## Attribution This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, -available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html +available at [homepage]: https://www.contributor-covenant.org For answers to common questions about this code of conduct, see -https://www.contributor-covenant.org/faq + diff --git a/Contributing.md b/Contributing.md index 6e784b363..f5e8ced45 100644 --- a/Contributing.md +++ b/Contributing.md @@ -1,39 +1,46 @@ -# Contributing to the Windows Community Toolkit :sparkles::sparkles: +# ✨ Contributing to the Windows Community Toolkit Thank you for exhibiting interest in contributing to the Windows Community Toolkit. The team is delighted to welcome you onboard to our exciting and growing project. Any contribution or value added go a long way to enhance the project! In the next few steps, you will be able to see a glimpse of ways you can contribute to the Windows Community Toolkit. -:rotating_light: **It is highly recommended to visit [Windows Community Toolkit Wiki](https://aka.ms/wct/wiki) where you can find complete and detail-oriented content of this page** :rotating_light: +🚨 **It is highly recommended to visit [Windows Community Toolkit Wiki](https://aka.ms/wct/wiki) where you can find complete and detail-oriented content of this page** 🚨 -## Questions :grey_question: -Due to the high volume of incoming issues please keep our GitHub issues for bug reports and feature requests. For general questions, there is a higher chance of getting your question answered on [StackOverflow](https://stackoverflow.com/questions/tagged/windows-community-toolkit) where questions should be tagged with the tag windows-community-toolkit. +## ❔ Questions + +Due to the high volume of incoming issues please keep our GitHub issues for bug reports and feature requests. For general questions, there is a higher chance of getting your question answered on [StackOverflow](https://stackoverflow.com/questions/tagged/windows-community-toolkit) where questions should be tagged with the tag `windows-community-toolkit`. For missing documentation related question, please file an issue at [Microsoft Docs](https://github.com/MicrosoftDocs/WindowsCommunityToolkitDocs/issues/new). -## Fix a Bug :bug: -If you find any bug, you can help the community by [submitting an issue](https://github.com/CommunityToolkit/WindowsCommunityToolkit/issues/new?assignees=&labels=bug+%3Abug%3A&template=bug_report.md&title=). Once the issue is filed, feel free to start working on the PR and submit a PR. +## πŸ› Fix a Bug -## Good First Issue :ok_hand: -If this is your first time contributing to the Windows Community Toolkit and do not have advanced level programming experience, we have got you covered :boom: WCT has a list of [good first issue](https://github.com/CommunityToolkit/WindowsCommunityToolkit/labels/good%20first%20issue%20%3Aok_hand%3A) that can be a great entryway to find and fix any issues that best fit your expertise or technical background. +If you find any bug, you can help the community by [submitting an issue](https://github.com/CommunityToolkit/WindowsCommunityToolkit/issues/new?template=bug_report.md&labels=bug+:bug:&title=[Bug]). Once the issue is filed, feel free to start working on the PR and submit a PR. -## Help Wanted :raising_hand: -WCT has a list of issues that are labeled as [help wanted](https://github.com/CommunityToolkit/WindowsCommunityToolkit/labels/help%20wanted%20%3Araising_hand%3A). The level of complexity in the list can vary but if you have an advanced level of programming experience, feel free to jump in to solve these issues. +## πŸ‘Œ Good First Issue -## Add New Feature :mailbox_with_mail: -* To contribute a new feature, fill out the [Feature Request Template](https://github.com/CommunityToolkit/WindowsCommunityToolkit/issues/new?assignees=&labels=feature+request+%3Amailbox_with_mail%3A&template=feature_request.md&title=%5BFeature%5D) and provide detailed information to express the proposal. -* Once the Feature Request is submitted, it will be open for discussion. -* If it gets approved by the team, proceed to submit a PR of the proposed Feature. -* If the PR contains an error-free code and the reviewer signs off, the PR will be merged. +If this is your first time contributing to the Windows Community Toolkit (_WCT_) and do not have advanced level programming experience, we have got you covered πŸ’₯ WCT has a list of [good first issue](https://github.com/CommunityToolkit/WindowsCommunityToolkit/labels/good%20first%20issue) that can be a great entryway to find and fix any issues that best fit your expertise or technical background. -## Add or Improve Documentation :page_with_curl: +## πŸ™‹ Help Wanted + +WCT also has a list of issues that are labeled as [help wanted](https://github.com/CommunityToolkit/WindowsCommunityToolkit/labels/help%20wanted). The level of complexity in the list can vary but if you have an advanced level of programming experience, feel free to jump in to solve these issues. + +## πŸ“¬ Add New Feature + +* To contribute a new feature, fill out the [Feature Request Template](https://github.com/CommunityToolkit/WindowsCommunityToolkit/issues/new?template=feature_request.md&labels=feature+request+:mailbox_with_mail:&title=[Feature]) and provide detailed information to express the proposal. +* Once the Feature Request is submitted, it will be open for discussion. +* If it gets approved by the team, proceed to submit a PR of the proposed Feature. +* If the PR contains an error-free code and the reviewer signs off, the PR will be merged. + +## πŸ“ Add or Improve Documentation Due to the involvement of multiple steps to add or improve documents; it is required to visit [Windows Community Toolkit Wiki](https://aka.ms/wct/wiki) and follow contribution guidelines. -## Create, Submit or Review Pull Request :rocket: -Anyone with write access can create a Pull Request by forking the Windows Community Toolkit Repository. Here is how you can [Create a Pull Request from fork](https://help.github.com/en/github/collaborating-with-issues-and-pull-requests/creating-a-pull-request-from-a-fork). Once you fork the Windows Community Toolkit repo, it is essential to create all changes in the feature branch of your forked repository. If you have the changes in the forked feature branch, you can then create a Pull Request in the main Windows Community Toolkit. +## πŸš€ Create, Submit or Review Pull Request + +Anyone can create a Pull Request by forking the Windows Community Toolkit Repository. Here is how you can [Create a Pull Request from fork](https://help.github.com/en/github/collaborating-with-issues-and-pull-requests/creating-a-pull-request-from-a-fork). Once you fork the Windows Community Toolkit repo, it is essential to create all changes in the feature branch of your forked repository. If you have the changes in the forked feature branch, you can then create a Pull Request in the main Windows Community Toolkit. Please visit [Windows Community Toolkit Wiki](https://aka.ms/wct/wiki) for detailed information and steps it requires to Submit or Review Pull Request. -# ThankYou :heart::heart: -**Thank you so much for contributing to this amazing project. We hope you will continue to add value and find yourself as a highly reliable source to the Windows Community Toolkit** +## πŸ’™ Thank You + +**Thank you so much for contributing to this amazing project. We hope you will continue to add value and find yourself as a highly reliable source to the Windows Community Toolkit.** diff --git a/License.md b/License.md index c5ae94030..5aefa46c6 100644 --- a/License.md +++ b/License.md @@ -1,13 +1,13 @@ # Windows Community Toolkit -Copyright (c) .NET Foundation and Contributors +Copyright Β© .NET Foundation and Contributors All rights reserved. -# MIT License (MIT) +## MIT License (MIT) -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the β€œSoftware”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. -THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/Microsoft.Toolkit.Mvvm.SourceGenerators/Attributes/NullabilityAttributesGenerator.cs b/Microsoft.Toolkit.Mvvm.SourceGenerators/Attributes/NullabilityAttributesGenerator.cs new file mode 100644 index 000000000..a0c2d6ef8 --- /dev/null +++ b/Microsoft.Toolkit.Mvvm.SourceGenerators/Attributes/NullabilityAttributesGenerator.cs @@ -0,0 +1,60 @@ +// 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.IO; +using System.Linq; +using System.Reflection; +using System.Text; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.Text; + +namespace Microsoft.Toolkit.Mvvm.SourceGenerators +{ + /// + /// A source generator for necessary nullability attributes. + /// + [Generator] + public sealed class NullabilityAttributesGenerator : ISourceGenerator + { + /// + public void Initialize(GeneratorInitializationContext context) + { + } + + /// + public void Execute(GeneratorExecutionContext context) + { + AddSourceCodeIfTypeIsNotPresent(context, "System.Diagnostics.CodeAnalysis.NotNullAttribute"); + AddSourceCodeIfTypeIsNotPresent(context, "System.Diagnostics.CodeAnalysis.NotNullIfNotNullAttribute"); + } + + /// + /// Adds the source for a given attribute type if it's not present already in the compilation. + /// + private void AddSourceCodeIfTypeIsNotPresent(GeneratorExecutionContext context, string typeFullName) + { + // Check that the target attributes are not available in the consuming project. To ensure that + // this works fine both in .NET (Core) and .NET Standard implementations, we also need to check + // that the target types are declared as public (we assume that in this case those types are from the BCL). + // This avoids issues on .NET Standard with Roslyn also seeing internal types from referenced assemblies. + if (context.Compilation.GetTypeByMetadataName(typeFullName) is { DeclaredAccessibility: Accessibility.Public }) + { + return; + } + + string + typeName = typeFullName.Split('.').Last(), + filename = $"Microsoft.Toolkit.Mvvm.SourceGenerators.EmbeddedResources.{typeName}.cs"; + + Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(filename); + StreamReader reader = new(stream); + + string + originalSource = reader.ReadToEnd(), + outputSource = originalSource.Replace("NETSTANDARD2_0", "true"); + + context.AddSource($"{typeFullName}.cs", SourceText.From(outputSource, Encoding.UTF8)); + } + } +} diff --git a/Microsoft.Toolkit.Mvvm.SourceGenerators/EmbeddedResources/INotifyPropertyChanged.cs b/Microsoft.Toolkit.Mvvm.SourceGenerators/EmbeddedResources/INotifyPropertyChanged.cs index 72d14de53..3f9a4a7c8 100644 --- a/Microsoft.Toolkit.Mvvm.SourceGenerators/EmbeddedResources/INotifyPropertyChanged.cs +++ b/Microsoft.Toolkit.Mvvm.SourceGenerators/EmbeddedResources/INotifyPropertyChanged.cs @@ -7,6 +7,7 @@ using System; using System.Collections.Generic; using System.ComponentModel; +using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; using System.Threading.Tasks; @@ -50,7 +51,7 @@ namespace Microsoft.Toolkit.Mvvm.ComponentModel /// /// The event is not raised if the current and new value for the target property are the same. /// - protected bool SetProperty(ref T field, T newValue, [CallerMemberName] string? propertyName = null) + protected bool SetProperty([NotNullIfNotNull("newValue")] ref T field, T newValue, [CallerMemberName] string? propertyName = null) { if (EqualityComparer.Default.Equals(field, newValue)) { @@ -75,7 +76,7 @@ namespace Microsoft.Toolkit.Mvvm.ComponentModel /// The instance to use to compare the input values. /// (optional) The name of the property that changed. /// if the property was changed, otherwise. - protected bool SetProperty(ref T field, T newValue, IEqualityComparer comparer, [CallerMemberName] string? propertyName = null) + protected bool SetProperty([NotNullIfNotNull("newValue")] ref T field, T newValue, IEqualityComparer comparer, [CallerMemberName] string? propertyName = null) { if (comparer.Equals(field, newValue)) { @@ -280,7 +281,7 @@ namespace Microsoft.Toolkit.Mvvm.ComponentModel /// is different than the previous one, and it does not mean the new /// instance passed as argument is in any particular state. /// - protected bool SetPropertyAndNotifyOnCompletion(ref TaskNotifier? taskNotifier, Task? newValue, [CallerMemberName] string? propertyName = null) + protected bool SetPropertyAndNotifyOnCompletion([NotNull] ref TaskNotifier? taskNotifier, Task? newValue, [CallerMemberName] string? propertyName = null) { return SetPropertyAndNotifyOnCompletion(taskNotifier ??= new(), newValue, static _ => { }, propertyName); } @@ -300,7 +301,7 @@ namespace Microsoft.Toolkit.Mvvm.ComponentModel /// /// The event is not raised if the current and new value for the target property are the same. /// - protected bool SetPropertyAndNotifyOnCompletion(ref TaskNotifier? taskNotifier, Task? newValue, Action callback, [CallerMemberName] string? propertyName = null) + protected bool SetPropertyAndNotifyOnCompletion([NotNull] ref TaskNotifier? taskNotifier, Task? newValue, Action callback, [CallerMemberName] string? propertyName = null) { return SetPropertyAndNotifyOnCompletion(taskNotifier ??= new(), newValue, callback, propertyName); } @@ -338,7 +339,7 @@ namespace Microsoft.Toolkit.Mvvm.ComponentModel /// is different than the previous one, and it does not mean the new /// instance passed as argument is in any particular state. /// - protected bool SetPropertyAndNotifyOnCompletion(ref TaskNotifier? taskNotifier, Task? newValue, [CallerMemberName] string? propertyName = null) + protected bool SetPropertyAndNotifyOnCompletion([NotNull] ref TaskNotifier? taskNotifier, Task? newValue, [CallerMemberName] string? propertyName = null) { return SetPropertyAndNotifyOnCompletion(taskNotifier ??= new(), newValue, static _ => { }, propertyName); } @@ -359,7 +360,7 @@ namespace Microsoft.Toolkit.Mvvm.ComponentModel /// /// The event is not raised if the current and new value for the target property are the same. /// - protected bool SetPropertyAndNotifyOnCompletion(ref TaskNotifier? taskNotifier, Task? newValue, Action?> callback, [CallerMemberName] string? propertyName = null) + protected bool SetPropertyAndNotifyOnCompletion([NotNull] ref TaskNotifier? taskNotifier, Task? newValue, Action?> callback, [CallerMemberName] string? propertyName = null) { return SetPropertyAndNotifyOnCompletion(taskNotifier ??= new(), newValue, callback, propertyName); } diff --git a/Microsoft.Toolkit.Mvvm.SourceGenerators/Microsoft.Toolkit.Mvvm.SourceGenerators.csproj b/Microsoft.Toolkit.Mvvm.SourceGenerators/Microsoft.Toolkit.Mvvm.SourceGenerators.csproj index 8e718f682..fa2804b32 100644 --- a/Microsoft.Toolkit.Mvvm.SourceGenerators/Microsoft.Toolkit.Mvvm.SourceGenerators.csproj +++ b/Microsoft.Toolkit.Mvvm.SourceGenerators/Microsoft.Toolkit.Mvvm.SourceGenerators.csproj @@ -9,6 +9,8 @@ + + @@ -17,6 +19,12 @@ PreserveNewest + + PreserveNewest + + + PreserveNewest + PreserveNewest diff --git a/Microsoft.Toolkit.Mvvm/Attributes/NotNullAttribute.cs b/Microsoft.Toolkit.Mvvm/Attributes/NotNullAttribute.cs new file mode 100644 index 000000000..7725aeeea --- /dev/null +++ b/Microsoft.Toolkit.Mvvm/Attributes/NotNullAttribute.cs @@ -0,0 +1,20 @@ +// 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. + +#if NETSTANDARD2_0 + +namespace System.Diagnostics.CodeAnalysis +{ + /// + /// Specifies that an output will not be null even if the corresponding type allows it. + /// Specifies that an input argument was not null when the call returns. + /// + /// Internal copy from the BCL attribute. + [AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.ReturnValue, Inherited = false)] + internal sealed class NotNullAttribute : Attribute + { + } +} + +#endif \ No newline at end of file diff --git a/Microsoft.Toolkit.Mvvm/Attributes/NotNullIfNotNullAttribute.cs b/Microsoft.Toolkit.Mvvm/Attributes/NotNullIfNotNullAttribute.cs new file mode 100644 index 000000000..df828c4de --- /dev/null +++ b/Microsoft.Toolkit.Mvvm/Attributes/NotNullIfNotNullAttribute.cs @@ -0,0 +1,27 @@ +// 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. + +#if NETSTANDARD2_0 + +namespace System.Diagnostics.CodeAnalysis +{ + /// + /// Specifies that the output will be non-null if the named parameter is non-null. + /// + /// Internal copy from the BCL attribute. + [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.ReturnValue, AllowMultiple = true, Inherited = false)] + internal sealed class NotNullIfNotNullAttribute : Attribute + { + /// + /// Initializes a new instance of the class. + /// + /// The associated parameter name. The output will be non-null if the argument to the parameter specified is non-null. + public NotNullIfNotNullAttribute(string parameterName) => ParameterName = parameterName; + + /// Gets the associated parameter name. + public string ParameterName { get; } + } +} + +#endif \ No newline at end of file diff --git a/Microsoft.Toolkit.Mvvm/ComponentModel/ObservableObject.cs b/Microsoft.Toolkit.Mvvm/ComponentModel/ObservableObject.cs index 5685e3ed4..41fa934cf 100644 --- a/Microsoft.Toolkit.Mvvm/ComponentModel/ObservableObject.cs +++ b/Microsoft.Toolkit.Mvvm/ComponentModel/ObservableObject.cs @@ -18,6 +18,7 @@ using System; using System.Collections.Generic; using System.ComponentModel; +using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; using System.Threading.Tasks; @@ -84,7 +85,7 @@ namespace Microsoft.Toolkit.Mvvm.ComponentModel /// The and events are not raised /// if the current and new value for the target property are the same. /// - protected bool SetProperty(ref T field, T newValue, [CallerMemberName] string? propertyName = null) + protected bool SetProperty([NotNullIfNotNull("newValue")] ref T field, T newValue, [CallerMemberName] string? propertyName = null) { // We duplicate the code here instead of calling the overload because we can't // guarantee that the invoked SetProperty will be inlined, and we need the JIT @@ -120,7 +121,7 @@ namespace Microsoft.Toolkit.Mvvm.ComponentModel /// The instance to use to compare the input values. /// (optional) The name of the property that changed. /// if the property was changed, otherwise. - protected bool SetProperty(ref T field, T newValue, IEqualityComparer comparer, [CallerMemberName] string? propertyName = null) + protected bool SetProperty([NotNullIfNotNull("newValue")] ref T field, T newValue, IEqualityComparer comparer, [CallerMemberName] string? propertyName = null) { if (comparer.Equals(field, newValue)) { @@ -340,7 +341,7 @@ namespace Microsoft.Toolkit.Mvvm.ComponentModel /// indicates that the new value being assigned to is different than the previous one, /// and it does not mean the new instance passed as argument is in any particular state. /// - protected bool SetPropertyAndNotifyOnCompletion(ref TaskNotifier? taskNotifier, Task? newValue, [CallerMemberName] string? propertyName = null) + protected bool SetPropertyAndNotifyOnCompletion([NotNull] ref TaskNotifier? taskNotifier, Task? newValue, [CallerMemberName] string? propertyName = null) { // We invoke the overload with a callback here to avoid code duplication, and simply pass an empty callback. // The lambda expression here is transformed by the C# compiler into an empty closure class with a @@ -368,7 +369,7 @@ namespace Microsoft.Toolkit.Mvvm.ComponentModel /// The and events are not raised /// if the current and new value for the target property are the same. /// - protected bool SetPropertyAndNotifyOnCompletion(ref TaskNotifier? taskNotifier, Task? newValue, Action callback, [CallerMemberName] string? propertyName = null) + protected bool SetPropertyAndNotifyOnCompletion([NotNull] ref TaskNotifier? taskNotifier, Task? newValue, Action callback, [CallerMemberName] string? propertyName = null) { return SetPropertyAndNotifyOnCompletion(taskNotifier ??= new(), newValue, callback, propertyName); } @@ -407,7 +408,7 @@ namespace Microsoft.Toolkit.Mvvm.ComponentModel /// indicates that the new value being assigned to is different than the previous one, /// and it does not mean the new instance passed as argument is in any particular state. /// - protected bool SetPropertyAndNotifyOnCompletion(ref TaskNotifier? taskNotifier, Task? newValue, [CallerMemberName] string? propertyName = null) + protected bool SetPropertyAndNotifyOnCompletion([NotNull] ref TaskNotifier? taskNotifier, Task? newValue, [CallerMemberName] string? propertyName = null) { return SetPropertyAndNotifyOnCompletion(taskNotifier ??= new(), newValue, static _ => { }, propertyName); } @@ -430,7 +431,7 @@ namespace Microsoft.Toolkit.Mvvm.ComponentModel /// The and events are not raised /// if the current and new value for the target property are the same. /// - protected bool SetPropertyAndNotifyOnCompletion(ref TaskNotifier? taskNotifier, Task? newValue, Action?> callback, [CallerMemberName] string? propertyName = null) + protected bool SetPropertyAndNotifyOnCompletion([NotNull] ref TaskNotifier? taskNotifier, Task? newValue, Action?> callback, [CallerMemberName] string? propertyName = null) { return SetPropertyAndNotifyOnCompletion(taskNotifier ??= new(), newValue, callback, propertyName); } diff --git a/Microsoft.Toolkit.Mvvm/ComponentModel/ObservableRecipient.cs b/Microsoft.Toolkit.Mvvm/ComponentModel/ObservableRecipient.cs index cbff751fe..23e0d0bb6 100644 --- a/Microsoft.Toolkit.Mvvm/ComponentModel/ObservableRecipient.cs +++ b/Microsoft.Toolkit.Mvvm/ComponentModel/ObservableRecipient.cs @@ -7,15 +7,9 @@ // This file is inspired from the MvvmLight library (lbugnion/MvvmLight), // more info in ThirdPartyNotices.txt in the root of the project. -// ================================= NOTE ================================= -// This file is mirrored in the ObservableRecipient annotated copy -// (for debugging info) in the Mvvm.SourceGenerators project. -// If any changes are made to this file, they should also be appropriately -// ported to that file as well to keep the behavior consistent. -// ======================================================================== - using System; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; using Microsoft.Toolkit.Mvvm.Messaging; using Microsoft.Toolkit.Mvvm.Messaging.Messages; @@ -145,7 +139,7 @@ namespace Microsoft.Toolkit.Mvvm.ComponentModel /// the and events /// are not raised if the current and new value for the target property are the same. /// - protected bool SetProperty(ref T field, T newValue, bool broadcast, [CallerMemberName] string? propertyName = null) + protected bool SetProperty([NotNullIfNotNull("newValue")] ref T field, T newValue, bool broadcast, [CallerMemberName] string? propertyName = null) { T oldValue = field; @@ -174,7 +168,7 @@ namespace Microsoft.Toolkit.Mvvm.ComponentModel /// If , will also be invoked. /// (optional) The name of the property that changed. /// if the property was changed, otherwise. - protected bool SetProperty(ref T field, T newValue, IEqualityComparer comparer, bool broadcast, [CallerMemberName] string? propertyName = null) + protected bool SetProperty([NotNullIfNotNull("newValue")] ref T field, T newValue, IEqualityComparer comparer, bool broadcast, [CallerMemberName] string? propertyName = null) { T oldValue = field; diff --git a/Microsoft.Toolkit.Mvvm/ComponentModel/ObservableValidator.cs b/Microsoft.Toolkit.Mvvm/ComponentModel/ObservableValidator.cs index 4e2537606..a21f36e3d 100644 --- a/Microsoft.Toolkit.Mvvm/ComponentModel/ObservableValidator.cs +++ b/Microsoft.Toolkit.Mvvm/ComponentModel/ObservableValidator.cs @@ -7,6 +7,7 @@ using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.DataAnnotations; +using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; using System.Linq; using System.Linq.Expressions; @@ -137,7 +138,7 @@ namespace Microsoft.Toolkit.Mvvm.ComponentModel /// the and events /// are not raised if the current and new value for the target property are the same. /// - protected bool SetProperty(ref T field, T newValue, bool validate, [CallerMemberName] string? propertyName = null) + protected bool SetProperty([NotNullIfNotNull("newValue")] ref T field, T newValue, bool validate, [CallerMemberName] string? propertyName = null) { bool propertyChanged = SetProperty(ref field, newValue, propertyName); @@ -162,7 +163,7 @@ namespace Microsoft.Toolkit.Mvvm.ComponentModel /// If , will also be validated. /// (optional) The name of the property that changed. /// if the property was changed, otherwise. - protected bool SetProperty(ref T field, T newValue, IEqualityComparer comparer, bool validate, [CallerMemberName] string? propertyName = null) + protected bool SetProperty([NotNullIfNotNull("newValue")] ref T field, T newValue, IEqualityComparer comparer, bool validate, [CallerMemberName] string? propertyName = null) { bool propertyChanged = SetProperty(ref field, newValue, comparer, propertyName); diff --git a/Microsoft.Toolkit.Uwp.Connectivity/Network/ConnectionInformation.cs b/Microsoft.Toolkit.Uwp.Connectivity/Network/ConnectionInformation.cs index aca168b6a..2e89c4654 100644 --- a/Microsoft.Toolkit.Uwp.Connectivity/Network/ConnectionInformation.cs +++ b/Microsoft.Toolkit.Uwp.Connectivity/Network/ConnectionInformation.cs @@ -135,9 +135,9 @@ namespace Microsoft.Toolkit.Uwp.Connectivity public byte? SignalStrength { get; private set; } /// - /// Gets signal strength for the current Internet Connection Profile. + /// Gets the network names associated with the current Internet Connection Profile. /// - /// value of + /// value of public IReadOnlyList NetworkNames { get @@ -146,4 +146,4 @@ namespace Microsoft.Toolkit.Uwp.Connectivity } } } -} \ No newline at end of file +} diff --git a/Microsoft.Toolkit.Uwp.DeveloperTools/VisualStudioToolsManifest.xml b/Microsoft.Toolkit.Uwp.DeveloperTools/VisualStudioToolsManifest.xml index 2c51528df..5b0b01591 100644 --- a/Microsoft.Toolkit.Uwp.DeveloperTools/VisualStudioToolsManifest.xml +++ b/Microsoft.Toolkit.Uwp.DeveloperTools/VisualStudioToolsManifest.xml @@ -1,6 +1,8 @@ - + diff --git a/Microsoft.Toolkit.Uwp.SampleApp/Assets/Samples/RangeSelector.png b/Microsoft.Toolkit.Uwp.SampleApp/Assets/Samples/RangeSelector.png deleted file mode 100644 index 6a95090eb..000000000 Binary files a/Microsoft.Toolkit.Uwp.SampleApp/Assets/Samples/RangeSelector.png and /dev/null differ diff --git a/Microsoft.Toolkit.Uwp.SampleApp/Assets/checker.png b/Microsoft.Toolkit.Uwp.SampleApp/Assets/checker.png new file mode 100644 index 000000000..739d14008 Binary files /dev/null and b/Microsoft.Toolkit.Uwp.SampleApp/Assets/checker.png differ diff --git a/Microsoft.Toolkit.Uwp.SampleApp/Assets/pixel.png b/Microsoft.Toolkit.Uwp.SampleApp/Assets/pixel.png deleted file mode 100644 index bf1b3a6bb..000000000 Binary files a/Microsoft.Toolkit.Uwp.SampleApp/Assets/pixel.png and /dev/null differ diff --git a/Microsoft.Toolkit.Uwp.SampleApp/Common/Vector3Converter.cs b/Microsoft.Toolkit.Uwp.SampleApp/Common/Vector3Converter.cs new file mode 100644 index 000000000..2aecfcbba --- /dev/null +++ b/Microsoft.Toolkit.Uwp.SampleApp/Common/Vector3Converter.cs @@ -0,0 +1,57 @@ +// 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.Linq; +using System.Numerics; +using Windows.UI.Xaml; +using Windows.UI.Xaml.Data; + +namespace Microsoft.Toolkit.Uwp.SampleApp.Common +{ + public class Vector3Converter : IValueConverter + { + public object Convert(object value, Type targetType, object parameter, string language) + { + if (value is string) + { + return value; + } + + var thickness = (Vector3)value; + + return thickness.ToString().TrimStart('<').Replace(" ", string.Empty).TrimEnd('>'); + } + + public object ConvertBack(object value, Type targetType, object parameter, string language) + { + if (value is string vectorString) + { + var vectorTokens = vectorString.Split(',') + .Where(tkn => !string.IsNullOrWhiteSpace(tkn)) + .ToArray(); + switch (vectorTokens.Length) + { + case 1: + var vectorValue = float.Parse(vectorString); + return new Vector3(vectorValue); + case 2: + var xValue = float.Parse(vectorTokens[0]); + var yValue = float.Parse(vectorTokens[1]); + + return new Vector3(xValue, yValue, 0); + case 3: + return new Vector3( + float.Parse(vectorTokens[0]), + float.Parse(vectorTokens[1]), + float.Parse(vectorTokens[2])); + default: + return default(Vector3); + } + } + + return value.ToString(); + } + } +} \ No newline at end of file diff --git a/Microsoft.Toolkit.Uwp.SampleApp/Controls/PropertyControl.xaml.cs b/Microsoft.Toolkit.Uwp.SampleApp/Controls/PropertyControl.xaml.cs index 51526c861..e992f5616 100644 --- a/Microsoft.Toolkit.Uwp.SampleApp/Controls/PropertyControl.xaml.cs +++ b/Microsoft.Toolkit.Uwp.SampleApp/Controls/PropertyControl.xaml.cs @@ -179,6 +179,14 @@ namespace Microsoft.Toolkit.Uwp.SampleApp.Controls converter = new ThicknessConverter(); break; + case PropertyKind.Vector3: + var vectorTextBox = new TextBox { Text = (propertyDict[option.Name] as ValueHolder).Value.ToString() }; + + controlToAdd = vectorTextBox; + dependencyProperty = TextBox.TextProperty; + converter = new Vector3Converter(); + break; + default: var textBox = new TextBox { Text = (propertyDict[option.Name] as ValueHolder).Value.ToString() }; diff --git a/Microsoft.Toolkit.Uwp.SampleApp/Controls/SampleAppMarkdownRenderer.cs b/Microsoft.Toolkit.Uwp.SampleApp/Controls/SampleAppMarkdownRenderer.cs index dc8271a7a..de1fd087f 100644 --- a/Microsoft.Toolkit.Uwp.SampleApp/Controls/SampleAppMarkdownRenderer.cs +++ b/Microsoft.Toolkit.Uwp.SampleApp/Controls/SampleAppMarkdownRenderer.cs @@ -5,6 +5,7 @@ using System; using System.Collections.Generic; using System.Linq; +using Microsoft.Toolkit.Helpers; using Microsoft.Toolkit.Parsers.Markdown; using Microsoft.Toolkit.Parsers.Markdown.Blocks; using Microsoft.Toolkit.Parsers.Markdown.Inlines; @@ -407,19 +408,19 @@ namespace Microsoft.Toolkit.Uwp.SampleApp.Controls { get { - return storage.Read(DesiredLangKey); + return settingsStorage.Read(DesiredLangKey); } set { - storage.Save(DesiredLangKey, value); + settingsStorage.Save(DesiredLangKey, value); } } /// - /// The Local Storage Helper. + /// The local app data storage helper for storing settings. /// - private LocalObjectStorageHelper storage = new LocalObjectStorageHelper(new SystemSerializer()); + private readonly ApplicationDataStorageHelper settingsStorage = ApplicationDataStorageHelper.GetCurrent(); /// /// DocFX note types and styling info, keyed by identifier. diff --git a/Microsoft.Toolkit.Uwp.SampleApp/Microsoft.Toolkit.Uwp.SampleApp.csproj b/Microsoft.Toolkit.Uwp.SampleApp/Microsoft.Toolkit.Uwp.SampleApp.csproj index 458053823..d48bda9a5 100644 --- a/Microsoft.Toolkit.Uwp.SampleApp/Microsoft.Toolkit.Uwp.SampleApp.csproj +++ b/Microsoft.Toolkit.Uwp.SampleApp/Microsoft.Toolkit.Uwp.SampleApp.csproj @@ -1,4 +1,4 @@ - +ο»Ώ Debug @@ -111,7 +111,7 @@ --> - 2.6.1 + 2.6.2 0.7.0-alpha @@ -130,6 +130,7 @@ + @@ -271,7 +272,9 @@ + + @@ -313,10 +316,10 @@ - + - - + + @@ -395,7 +398,7 @@ - + @@ -486,6 +489,7 @@ + AutoFocusBehaviorPage.xaml @@ -504,6 +508,13 @@ MetadataControlPage.xaml + + AttachedDropShadowPage.xaml + + + RichSuggestBoxPage.xaml + + TilesBrushPage.xaml @@ -621,6 +632,14 @@ + + Designer + + + + + + @@ -657,7 +676,6 @@ UniformGridPage.xaml - SampleController.xaml @@ -803,9 +821,6 @@ DispatcherQueueHelperPage.xaml - - DropShadowPanelPage.xaml - ExpanderPage.xaml @@ -980,6 +995,18 @@ Designer + + MSBuild:Compile + Designer + + + Designer + MSBuild:Compile + + + Designer + MSBuild:Compile + MSBuild:Compile Designer @@ -1073,6 +1100,10 @@ Designer MSBuild:Compile + + Designer + MSBuild:Compile + MSBuild:Compile Designer @@ -1263,10 +1294,6 @@ MSBuild:Compile Designer - - Designer - MSBuild:Compile - Designer MSBuild:Compile @@ -1470,6 +1497,7 @@ Visual C++ 2015 Runtime for Universal Windows Platform Apps + 14.0 @@ -1534,4 +1562,4 @@ - \ No newline at end of file + diff --git a/Microsoft.Toolkit.Uwp.SampleApp/Models/PropertyDescriptor/PropertyKind.cs b/Microsoft.Toolkit.Uwp.SampleApp/Models/PropertyDescriptor/PropertyKind.cs index fcb070359..f45876a6a 100644 --- a/Microsoft.Toolkit.Uwp.SampleApp/Models/PropertyDescriptor/PropertyKind.cs +++ b/Microsoft.Toolkit.Uwp.SampleApp/Models/PropertyDescriptor/PropertyKind.cs @@ -13,6 +13,7 @@ namespace Microsoft.Toolkit.Uwp.SampleApp.Models Bool, Brush, TimeSpan, - Thickness + Thickness, + Vector3, } } \ No newline at end of file diff --git a/Microsoft.Toolkit.Uwp.SampleApp/Models/Sample.cs b/Microsoft.Toolkit.Uwp.SampleApp/Models/Sample.cs index 9a55745ea..e26a50768 100644 --- a/Microsoft.Toolkit.Uwp.SampleApp/Models/Sample.cs +++ b/Microsoft.Toolkit.Uwp.SampleApp/Models/Sample.cs @@ -20,6 +20,7 @@ using System.Threading.Tasks; // TODO Reintroduce graph controls // using Microsoft.Toolkit.Graph.Converters; // using Microsoft.Toolkit.Graph.Providers; +using Microsoft.Toolkit.Helpers; using Microsoft.Toolkit.Uwp.Helpers; using Microsoft.Toolkit.Uwp.Input.GazeInteraction; using Microsoft.Toolkit.Uwp.SampleApp.Models; @@ -45,7 +46,7 @@ namespace Microsoft.Toolkit.Uwp.SampleApp public static async void EnsureCacheLatest() { - var settingsStorage = new LocalObjectStorageHelper(new SystemSerializer()); + var settingsStorage = ApplicationDataStorageHelper.GetCurrent(); var onlineDocsSHA = await GetDocsSHA(); var cacheSHA = settingsStorage.Read(_cacheSHAKey); @@ -417,8 +418,12 @@ namespace Microsoft.Toolkit.Uwp.SampleApp { if (proxy[option.Name] is ValueHolder value) { - var newString = value.Value is Windows.UI.Xaml.Media.SolidColorBrush brush ? - brush.Color.ToString() : value.Value.ToString(); + var newString = value.Value switch + { + Windows.UI.Xaml.Media.SolidColorBrush brush => brush.Color.ToString(), + System.Numerics.Vector3 vector => vector.ToString().TrimStart('<').Replace(" ", string.Empty).TrimEnd('>'), + _ => value.Value.ToString() + }; result = result.Replace(option.OriginalString, newString); result = result.Replace("@[" + option.Label + "]@", newString); @@ -629,12 +634,27 @@ namespace Microsoft.Toolkit.Uwp.SampleApp case PropertyKind.Thickness: try { - var thicknessOptions = new ThicknessPropertyOptions { DefaultValue = value }; + var thicknessOptions = new PropertyOptions { DefaultValue = value }; options = thicknessOptions; } catch (Exception ex) { - Debug.WriteLine($"Unable to extract slider info from {value}({ex.Message})"); + Debug.WriteLine($"Unable to extract thickness info from {value}({ex.Message})"); + TrackingManager.TrackException(ex); + continue; + } + + break; + + case PropertyKind.Vector3: + try + { + var vector3Options = new PropertyOptions { DefaultValue = value }; + options = vector3Options; + } + catch (Exception ex) + { + Debug.WriteLine($"Unable to extract vector3 info from {value}({ex.Message})"); TrackingManager.TrackException(ex); continue; } diff --git a/Microsoft.Toolkit.Uwp.SampleApp/Models/Samples.cs b/Microsoft.Toolkit.Uwp.SampleApp/Models/Samples.cs index 8105e859b..8170fb9f2 100644 --- a/Microsoft.Toolkit.Uwp.SampleApp/Models/Samples.cs +++ b/Microsoft.Toolkit.Uwp.SampleApp/Models/Samples.cs @@ -9,6 +9,7 @@ using System.Linq; using System.Text.Json; using System.Threading; using System.Threading.Tasks; +using Microsoft.Toolkit.Helpers; using Microsoft.Toolkit.Uwp.Helpers; namespace Microsoft.Toolkit.Uwp.SampleApp @@ -21,7 +22,7 @@ namespace Microsoft.Toolkit.Uwp.SampleApp private static SemaphoreSlim _semaphore = new SemaphoreSlim(1); private static LinkedList _recentSamples; - private static LocalObjectStorageHelper _localObjectStorageHelper = new LocalObjectStorageHelper(new SystemSerializer()); + private static ApplicationDataStorageHelper _settingsStorage = ApplicationDataStorageHelper.GetCurrent(); public static async Task GetCategoryBySample(Sample sample) { @@ -59,7 +60,8 @@ namespace Microsoft.Toolkit.Uwp.SampleApp { allCategories = await JsonSerializer.DeserializeAsync>(jsonStream.AsStream(), new JsonSerializerOptions { - ReadCommentHandling = JsonCommentHandling.Skip + ReadCommentHandling = JsonCommentHandling.Skip, + AllowTrailingCommas = true, }); } @@ -98,7 +100,7 @@ namespace Microsoft.Toolkit.Uwp.SampleApp if (_recentSamples == null) { _recentSamples = new LinkedList(); - var savedSamples = _localObjectStorageHelper.Read(_recentSamplesStorageKey); + var savedSamples = _settingsStorage.Read(_recentSamplesStorageKey); if (savedSamples != null) { @@ -144,7 +146,7 @@ namespace Microsoft.Toolkit.Uwp.SampleApp } var str = string.Join(";", _recentSamples.Take(10).Select(s => s.Name).ToArray()); - _localObjectStorageHelper.Save(_recentSamplesStorageKey, str); + _settingsStorage.Save(_recentSamplesStorageKey, str); } } } \ No newline at end of file diff --git a/Microsoft.Toolkit.Uwp.SampleApp/ReadMe.md b/Microsoft.Toolkit.Uwp.SampleApp/ReadMe.md index 6a059b6c6..98554a7f7 100644 --- a/Microsoft.Toolkit.Uwp.SampleApp/ReadMe.md +++ b/Microsoft.Toolkit.Uwp.SampleApp/ReadMe.md @@ -1,100 +1,110 @@ +# Sample Application + For the latest info, [visit the wiki article here](https://github.com/CommunityToolkit/WindowsCommunityToolkit/wiki/Sample-Development). -# How to add new samples +## How to add new samples This document describes how to add a new sample page for a new control you want to add to the toolkit. -*DropShadowPanel*, *ImageEx*, and *ImageCache* are good examples of most of the features mentioned below. +*`DropShadowPanel`*, *`ImageEx`*, and *`ImageCache`* are good examples of most of the features mentioned below. +### 1. Add Sample page and `.bind` template -## 1. Add Sample page and .bind template -First you need to create a Xaml page in the folder /SamplePages/YourControl. This will be the logical page used to by the app to navigate to the sample and contains code. +First you need to create a XAML page in the folder `/SamplePages/YourControl`. This will be the logical page used to by the app to navigate to the sample and contains code. -If providing 'live' XAML, a .bind file is loaded and dynamically fed to the XamlReader.Load method to convert into actual controls. This changes a few things about how samples need to be written (detailed below), but allows developers to actually change the sample and see the results live. +If providing 'live' XAML, a `.bind` file is loaded and dynamically fed to the `XamlReader.Load` method to convert into actual controls. This changes a few things about how samples need to be written (detailed below), but allows developers to actually change the sample and see the results live. This not only gives us a killer sample app, but it also means that all our samples are also self-validating. There can't be a typo in the sample text given in the sample app anymore, as otherwise the sample won't work and should be caught during testing of said sample. +### 2. Binding text -## 2. Binding text -The .bind files are templates which use @[Property Name:Type:DefaultValue:Options] syntax to allow for customized options to be presented to the user in the sample app. The user can play with the values in the property page and see results change instantly. This is accomplished by using {Binding} syntax when on the property page, but switches to the raw value when the developer goes to the XAML page. +The `.bind` files are templates which use `@[Property Name:Type:DefaultValue:Options]` syntax to allow for customized options to be presented to the user in the sample app. The user can play with the values in the property page and see results change instantly. This is accomplished by using {Binding} syntax when on the property page, but switches to the raw value when the developer goes to the XAML page. This makes it easy for a developer to test out values for a control and then copy the XAML needed for that exact result into their app. -In order to provide a property UI and associated code, you have to define a the .bind XAML file associated with your page. +In order to provide a property UI and associated code, you have to define a `.bind` XAML file associated with your page. Here is an example: -```xaml +```xml - - + + - + Foreground="Black" + Text="@[Text:String:Hey!]" + FontSize="@[FontSize:Slider:12:10-30]" + VerticalAlignment="@[Vertical Alignment:Enum:VerticalAlignment.Center]"> + ``` -You can define "interactive" values in this file. The value types can be: -* String: You want the user to provide a text. The string is built like this @[Name:**String**:Default value] -* Slider: You want the user to provide a double value. The string is built like this @[Name:**Slider**:Default value:min-max] -* DoubleSlider: Same as slider but with double values (0.01 precision) -* TimeSpan: You want the user to provide a duration. The string is built like this (all values in milliseconds) @[Name:**TimeSpan**:DefaultValue:min-max] -* Enum: You want the user to provide a enum value. The string is built like this @[Name:**Enum**:EnumType.DefaultValue] -* Brush: You want the user to select a color from a list. The string is built like this @[Name:**Brush**:Black] -* Bool: You want the user to enable or disable a property. The string is built like this @[Name:**Bool**:True] -* Thickness: You want the user to provide a Thickness. The string is built like this @[Name:**Thickness**:0,20,10,0] +You can define β€œinteractive” values in this file. The value types can be: + +* `String`: You want the user to provide a text. An equivalent syntax is `@[Name:String:Default Value]` +* `Slider`: You want the user to provide a double value. An equivalent syntax is `@[Name:Slider:DefaultValue:Min-Max]` +* `DoubleSlider`: Same as slider but with double values (0.01 precision) +* `TimeSpan`: You want the user to provide a duration. An equivalent syntax is (all values in milliseconds) `@[Name:TimeSpan:DefaultValue:Min-Max]` +* `Enum`: You want the user to provide an enum value. An equivalent syntax is `@[Name:Enum:EnumType.DefaultValue]` +* `Brush`: You want the user to select a color from a list. An equivalent syntax is `@[Name:Brush:Black]` +* `Bool`: You want the user to enable or disable a property. An equivalent syntax is `@[Name:Bool:True]` +* `Thickness`: You want the user to provide a Thickness. An equivalent syntax is `@[Name:Thickness:0,20,10,0]` The `Property Name` can also contain spaces, but these will be removed from the property name used for accessing the value in the property bag for any binding/access, see below. -The name and options will be translated **automatically** to the following syntax when your .bind template is being used on the property page: +The name and options will be translated **automatically** to the following syntax when your `.bind` template is being used on the property page: -```xaml +```xml - - + + - + + ``` When the developer switches to the XAML tab, they'll automatically see the selected values instead: -```xaml +```xml - - + + - + + ``` You can also reuse a `@[Property Name]` reference by itself again later to use the same binding/value again in the same template. This will automatically get mapped to the right place without the need to specify all the types/options again. Just set those options on your first usage. -If you happen to need a two-way binding for the generated XAML, then add an extra '@' after the property definition in the template: +If you happen to need a two-way binding for the generated XAML, then add an extra '**@**' after the property definition in the template: -```xaml -Value="@[Value:Slider:0:0-180]@" +```xml + ``` -## 3. Have a *'Shallow Copy'* of your example in the sample page -Even though the sample page content is ignored and the dynamic template injected, for the XamlReader to access some classes, a reference to the item is sometimes needed in the hosting app for it to be accessible. (I assume it's an optimization thing.) +### 3. Have a '*Shallow Copy*' of your example in the sample page -Therefore, for any new control/extension, you should still have a simplified snippet of it contained in the sample page compiled/loaded by the app. You should remove names, events, and properties (unless extensions) from these so the namespace isn't accidentally polluted. If you re-use the same control, you don't have to include it twice. +Even though the sample page content is ignored and the dynamic template injected, for the `XamlReader` to access some classes, a reference to the item is sometimes needed in the hosting app for it to be accessible. (I assume it's an optimization thing.) +Therefore, for any new control/extension, you should still have a simplified snippet of it contained in the sample page compiled/loaded by the app. You should remove names, events, and properties (unless extensions) from these, so the namespace isn't accidentally polluted. If you re-use the same control, you don't have to include it twice. -## 4. For Events/Resource Templates: Have your sample page implement the **IXamlRendererListener** interface -This gets called whenever the template gets parsed (due to loading or user modification). Here you can use the [LogicalTree](https://github.com/CommunityToolkit/WindowsCommunityToolkit/blob/main/Microsoft.Toolkit.Uwp.UI/Extensions/Tree/LogicalTree.cs) extensions to grab named controls in the template and register their events. **Check for null first** as the developer may have removed the name from the element. +### 4. For Events/Resource Templates: Have your sample page implement the **`IXamlRendererListener`** interface -```csharp +This gets called whenever the template gets parsed (due to loading or user modification). Here you can use the [`LogicalTree`](https://github.com/CommunityToolkit/WindowsCommunityToolkit/blob/main/Microsoft.Toolkit.Uwp.UI/Extensions/FrameworkElement/FrameworkElementExtensions.LogicalTree.cs) extensions to grab named controls in the template and register their events. **Check for null first** as the developer may have removed the name from the element. + +```cs var markdownText = control.FindChild("MarkdownText") as MarkdownTextBlock; if (markdownText != null) { @@ -102,13 +112,13 @@ if (markdownText != null) } ``` -You'll have to register all events and grab **control.Resources** for templates from this method as the regular sample page XAML isn't used and you can't hook in an event from the dynamic XAML, it must be done via code by finding the element here. +You'll have to register all events and grab **`control.Resources`** for templates from this method as the regular sample page XAML isn't used, and you can't hook in an event from the dynamic XAML, it must be done via code by finding the element here. +### 5. For Interactive Buttons: Use **`SampleController.Current.RegisterNewCommand`** -## 5. For Interactive Buttons: Use **SampleController.Current.RegisterNewCommand** -Buttons can be added through this command and are accessible in the main panel so they can be clicked when changing properties or editing XAML. It's important instead of using buttons in your sample (as events can't be directly used, see above) to register these commands. +Buttons can be added through this command and are accessible in the main panel, so they can be clicked when changing properties or editing XAML. It's important instead of using buttons in your sample (as events can't be directly used, see above) to register these commands. -```csharp +```cs protected override async void OnNavigatedTo(NavigationEventArgs e) { base.OnNavigatedTo(e); @@ -117,26 +127,30 @@ protected override async void OnNavigatedTo(NavigationEventArgs e) { AddImage(false, true); }); + + // β€’β€’β€’ +} ``` -If your command adds content dynamically, try and use a style template in the .bind XAML that the user can modify. Then grab `resources = control.Resources;` in the *OnXamlRendered* event and set the element style from it: +If your command adds content dynamically, try and use a style template in the `.bind` XAML that the user can modify. Then grab `resources = control.Resources;` in the *`OnXamlRendered`* event and set the element style from it: -```csharp +```cs if (resources?.ContainsKey("ThingStyle") == true) { newThing.Style = resources["ThingStyle"] as Style; } ``` -## 6. *Optional:* If you need *extra stuff* around the sample -Now, the sample page content in the app is ignored, but you can override that behavior by adding a `` element to the page. If this element is found, it will serve as the host to the dynamic .bind content instead. In this manner you can have a status/warning message outside of the control of the developer in the XAML sample tab. +### 6. *Optional:* If you need *extra stuff* around the sample +Now, the sample page content in the app is ignored, but you can override that behavior by adding a `` element to the page. If this element is found, it will serve as the host to the dynamic `.bind` content instead. In this manner you can have a status/warning message outside the control of the developer in the XAML sample tab. -# Update Samples.json -After creating your page and the binding text, you just need to reference it in the /SamplePages/samples.json file. +## Update `Samples.json` + +After creating your page and the binding text, you just need to reference it in the `/SamplePages/samples.json` file. Select the category where you want your page to be listed and add the following information: -## Basic Structure +### Basic Structure ```json [ @@ -148,7 +162,7 @@ Select the category where you want your page to be listed and add the following "Name": "AdaptiveGridView", "Type": "AdaptiveGridViewPage", "About": "The AdaptiveGridView control allows to present information within a Grid View perfectly adjusting the total display available space. It reacts to changes in the layout as well as the content so it can adapt to different form factors automatically. The number and the width of items are calculated based on the screen resolution in order to fully leverage the available screen space. The property ItemsHeight define the items fixed height and the property DesiredWidth sets the minimum width for the elements to add a new column.", - "CodeUrl": "https://github.com/CommunityToolkit/WindowsCommunityToolkit/tree/main/Microsoft.Toolkit.Uwp.UI.Controls/TextToolbar", + "CodeUrl": "https://github.com/CommunityToolkit/WindowsCommunityToolkit/tree/main/Microsoft.Toolkit.Uwp.UI.Controls.Core/TextToolbar", "XamlCodeFile": "AdaptiveGridViewCode.bind", "DocumentationUrl": "https://raw.githubusercontent.com/CommunityToolkit/WindowsCommunityToolkit/main/docs/controls/AdaptiveGridView.md" } @@ -157,48 +171,51 @@ Select the category where you want your page to be listed and add the following ] ``` -## Thumbnail Images +### Thumbnail Images -> NOTE: If creating a new icon, follow the [Thumbnail Style Guide and templates](https://github.com/CommunityToolkit/WindowsCommunityToolkit-design-assets) +For creating new icons, please follow the [Thumbnail Style Guide and templates](https://github.com/CommunityToolkit/WindowsCommunityToolkit-design-assets) -## Restricting Samples to Specific API Sets +### Restricting Samples to Specific API Sets Some features used by samples aren't available on all the OS versions that the Sample App runs on. In order to make sure a sample is valid for the host OS, add the `ApiCheck` key/value in your JSON definition. -The value is a string which is the fully-qualified typename to check for the presence of. You can also accompany this with the `BadgeUpdateVersionRequred` which uses the string provided to show a short message on the sample information so up level implementors know the minimum version required. +The value is a string which is the fully-qualified type-name to check for the presence of. You can also accompany this with the `BadgeUpdateVersionRequired` which uses the string provided to show a short message on the sample information so up level implementer know the minimum version required. ```json { - //... + // β€’β€’β€’ "About": "MySample needs 10.0.18362 or higher to work.", "ApiCheck": "Windows.UI.Xaml.Controls.NavigationView", "BadgeUpdateVersionRequired": "Fall Creators Update required", - //... + // β€’β€’β€’ } ``` -If the specified type is not found on the system running the sample app the sample will not appear in the sample list. +If the specified type is not found on the system running the sample app, the sample will not appear in the sample list. +#### Adding documentation -### Adding documentation +Every API must be accompanied by Markdown doc in the [documentation](https://github.com/CommunityToolkit/WindowsCommunityToolkit/blob/main/Contributing.md#docs) [repository](https://github.com/MicrosoftDocs/WindowsCommunityToolkitDocs). -Every API must be accompanied by Markdown documentation in the [documentation repository](..\contributing.md#docs). - -Use the DocumentationUrl property to add a link to the raw documentation in *samples.json*. Please follow the following pattern: +Use the `DocumentationUrl` property to add a link to the raw documentation in *`samples.json`*. Please follow the following pattern: `https://raw.githubusercontent.com/MicrosoftDocs/WindowsCommunityToolkitDocs/{branch}/docs/{folder/file.md}` -> NOTE: When building and running the app in release mode, the branch will automatically be changed to **main** before loading. +##### NOTES -> NOTE: The documentation is also packaged with the sample app. If there is no network connection, or the documentation is not yet on GitHub, the sample app will use the packaged version +* When building and running the app in release mode, the branch will automatically be changed to **main** before loading. +* The documentation is also packaged with the sample app. If there is no network connection, or the documentation is not yet on GitHub, the sample app will use the packaged version. +* To test your documentation in the sample app while running in debug mode, the Docs repository will need to be cloned in the same folder as this repository and named **`WindowsCommunityToolkitDocs`**. For -> NOTE: To test your documentation in the sample app while running in debug mode, the docs repository will need to be cloned in the same folder as this repository and named **WindowsCommunityToolkitDocs**. For example, this folder structure works best: -> ``` -> repositories -> β”œβ”€β”€ WindowsCommunityToolkit -> β”œβ”€β”€ WindowsCommunityToolkitDocs -> ``` +Example, this folder structure works best: -### CodeUrl +```txt +Repos +β”œβ”€β”€ WindowsCommunityToolkit +β”œβ”€β”€ WindowsCommunityToolkitDocs +└── Others +``` -The value of CodeUrl is modified when the app is built in release mode. The branch is automatically changed to **main**. This allows you to test the link in debug while pointing to dev. +#### Using `CodeUrl` + +The value of `CodeUrl` is modified when the app is built in release mode. The branch is automatically changed to **main**. This allows you to test the link in debug while pointing to dev. diff --git a/Microsoft.Toolkit.Uwp.SampleApp/SamplePages/Animations/Effects/FadeBehaviorXaml.bind b/Microsoft.Toolkit.Uwp.SampleApp/SamplePages/Animations/Effects/FadeBehaviorXaml.bind index 1a0f0eb90..faa191462 100644 --- a/Microsoft.Toolkit.Uwp.SampleApp/SamplePages/Animations/Effects/FadeBehaviorXaml.bind +++ b/Microsoft.Toolkit.Uwp.SampleApp/SamplePages/Animations/Effects/FadeBehaviorXaml.bind @@ -7,7 +7,6 @@ xmlns:interactions="using:Microsoft.Xaml.Interactions.Core" xmlns:ani="using:Microsoft.Toolkit.Uwp.UI.Animations" xmlns:behaviors="using:Microsoft.Toolkit.Uwp.UI.Behaviors" - xmlns:core="using:Microsoft.Xaml.Interactions.Core" mc:Ignorable="d"> + + diff --git a/Microsoft.Toolkit.Uwp.SampleApp/SamplePages/DropShadowPanel/DropShadowPanelPage.xaml b/Microsoft.Toolkit.Uwp.SampleApp/SamplePages/DropShadowPanel/DropShadowPanelPage.xaml deleted file mode 100644 index 10d089fe6..000000000 --- a/Microsoft.Toolkit.Uwp.SampleApp/SamplePages/DropShadowPanel/DropShadowPanelPage.xaml +++ /dev/null @@ -1,26 +0,0 @@ - - - - - - - - - \ No newline at end of file diff --git a/Microsoft.Toolkit.Uwp.SampleApp/SamplePages/DropShadowPanel/DropShadowPanelPage.xaml.cs b/Microsoft.Toolkit.Uwp.SampleApp/SamplePages/DropShadowPanel/DropShadowPanelPage.xaml.cs deleted file mode 100644 index 0c6c06a95..000000000 --- a/Microsoft.Toolkit.Uwp.SampleApp/SamplePages/DropShadowPanel/DropShadowPanelPage.xaml.cs +++ /dev/null @@ -1,22 +0,0 @@ -// 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 Windows.UI.Xaml.Controls; - -namespace Microsoft.Toolkit.Uwp.SampleApp.SamplePages -{ - /// - /// A page that shows how to use the DropShadowPanel control. - /// - public sealed partial class DropShadowPanelPage : Page - { - /// - /// Initializes a new instance of the class. - /// - public DropShadowPanelPage() - { - InitializeComponent(); - } - } -} \ No newline at end of file diff --git a/Microsoft.Toolkit.Uwp.SampleApp/SamplePages/KeyDownTriggerBehavior/KeyDownTriggerBehaviorXaml.bind b/Microsoft.Toolkit.Uwp.SampleApp/SamplePages/KeyDownTriggerBehavior/KeyDownTriggerBehaviorXaml.bind new file mode 100644 index 000000000..25535c043 --- /dev/null +++ b/Microsoft.Toolkit.Uwp.SampleApp/SamplePages/KeyDownTriggerBehavior/KeyDownTriggerBehaviorXaml.bind @@ -0,0 +1,59 @@ + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Microsoft.Toolkit.Uwp.SampleApp/SamplePages/ListDetailsView/ListDetailsView.bind b/Microsoft.Toolkit.Uwp.SampleApp/SamplePages/ListDetailsView/ListDetailsView.bind index af80e92f2..b0a200550 100644 --- a/Microsoft.Toolkit.Uwp.SampleApp/SamplePages/ListDetailsView/ListDetailsView.bind +++ b/Microsoft.Toolkit.Uwp.SampleApp/SamplePages/ListDetailsView/ListDetailsView.bind @@ -74,19 +74,20 @@ + - - - - - - - - + + + + + + + + diff --git a/Microsoft.Toolkit.Uwp.SampleApp/SamplePages/ListViewExtensions/ListViewExtensionsPage.xaml b/Microsoft.Toolkit.Uwp.SampleApp/SamplePages/ListViewExtensions/ListViewExtensionsPage.xaml index 625285f44..bb50bbcf3 100644 --- a/Microsoft.Toolkit.Uwp.SampleApp/SamplePages/ListViewExtensions/ListViewExtensionsPage.xaml +++ b/Microsoft.Toolkit.Uwp.SampleApp/SamplePages/ListViewExtensions/ListViewExtensionsPage.xaml @@ -35,14 +35,16 @@ - + + Text="100" + Margin="0,10,0,0" /> + SelectedIndex="0" + Margin="0,10,0,0" > Default Left Top @@ -52,18 +54,25 @@ + IsChecked="False" + Margin="0,10,0,0" /> + Text="0" + Margin="0,10,0,0" /> + Text="0" + Margin="0,10,0,0" /> + + + + - \ No newline at end of file + diff --git a/Microsoft.Toolkit.Uwp.SampleApp/SamplePages/ListViewExtensions/ListViewExtensionsPage.xaml.cs b/Microsoft.Toolkit.Uwp.SampleApp/SamplePages/ListViewExtensions/ListViewExtensionsPage.xaml.cs index b79849ef1..cd547d2bd 100644 --- a/Microsoft.Toolkit.Uwp.SampleApp/SamplePages/ListViewExtensions/ListViewExtensionsPage.xaml.cs +++ b/Microsoft.Toolkit.Uwp.SampleApp/SamplePages/ListViewExtensions/ListViewExtensionsPage.xaml.cs @@ -6,9 +6,11 @@ using System; using System.Collections.ObjectModel; using System.Windows.Input; using Microsoft.Toolkit.Uwp.UI; +using Windows.UI; using Windows.UI.Popups; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; +using Windows.UI.Xaml.Media; namespace Microsoft.Toolkit.Uwp.SampleApp.SamplePages { @@ -37,7 +39,7 @@ namespace Microsoft.Toolkit.Uwp.SampleApp.SamplePages private void Load() { - SampleController.Current.RegisterNewCommand("Start Smooth Scroll", (sender, args) => + SampleController.Current.RegisterNewCommand("Start Smooth Scroll", async (sender, args) => { var index = int.TryParse(IndexInput.Text, out var i) ? i : 0; var itemPlacement = ItemPlacementInput.SelectedItem switch @@ -55,7 +57,9 @@ namespace Microsoft.Toolkit.Uwp.SampleApp.SamplePages var scrollIfVisibile = ScrollIfVisibileInput.IsChecked ?? true; var additionalHorizontalOffset = int.TryParse(AdditionalHorizontalOffsetInput.Text, out var ho) ? ho : 0; var additionalVerticalOffset = int.TryParse(AdditionalVerticalOffsetInput.Text, out var vo) ? vo : 0; - sampleListView.SmoothScrollIntoViewWithIndexAsync(index, itemPlacement, disableAnimation, scrollIfVisibile, additionalHorizontalOffset, additionalVerticalOffset); + UpdateScrollIndicator(true); + await sampleListView.SmoothScrollIntoViewWithIndexAsync(index, itemPlacement, disableAnimation, scrollIfVisibile, additionalHorizontalOffset, additionalVerticalOffset); + UpdateScrollIndicator(false); }); if (sampleListView != null) @@ -64,6 +68,20 @@ namespace Microsoft.Toolkit.Uwp.SampleApp.SamplePages } } + private void UpdateScrollIndicator(bool isScrolling) + { + if (isScrolling) + { + ScrollIndicatorTest.Text = "Scrolling"; + ScrollIndicator.Fill = new SolidColorBrush(Colors.Green); + } + else + { + ScrollIndicator.Fill = new SolidColorBrush(Colors.Red); + ScrollIndicatorTest.Text = "Not Scolling"; + } + } + private ObservableCollection GetOddEvenSource(int count) { var oddEvenSource = new ObservableCollection(); @@ -103,4 +121,4 @@ namespace Microsoft.Toolkit.Uwp.SampleApp.SamplePages await new MessageDialog($"You clicked {item} via the 'ListViewExtensions.Command' binding", "Item Clicked").ShowAsync(); } } -} \ No newline at end of file +} diff --git a/Microsoft.Toolkit.Uwp.SampleApp/SamplePages/Object Storage/ObjectStorageCode.bind b/Microsoft.Toolkit.Uwp.SampleApp/SamplePages/Object Storage/ObjectStorageCode.bind index 50d77bc5e..0b0c4d926 100644 --- a/Microsoft.Toolkit.Uwp.SampleApp/SamplePages/Object Storage/ObjectStorageCode.bind +++ b/Microsoft.Toolkit.Uwp.SampleApp/SamplePages/Object Storage/ObjectStorageCode.bind @@ -1,25 +1,24 @@ -var localObjectStorageHelper = new LocalObjectStorageHelper(); -var roamingObjectStorageHelper = new RoamingObjectStorageHelper(); +ApplicationDataStorageHelper appDataStorageHelper = ApplicationDataStorageHelper.GetCurrent(new Toolkit.Helpers.SystemSerializer()); // Read and Save with simple objects string keySimpleObject = "simple"; -string result = localObjectStorageHelper.Read(keySimpleObject); -localObjectStorageHelper.Save(keySimpleObject, 47); +string result = appDataStorageHelper.Read(keySimpleObject); +appDataStorageHelper.Save(keySimpleObject, 47); // Read and Save with complex/large objects -string keyLargeObject = "large"; -var result = localObjectStorageHelper.ReadFileAsync(keyLargeObject); +string complexObjectKey = "complexObject"; +var complexObject = await appDataStorageHelper.ReadFileAsync(complexObjectKey); -var o = new MyLargeObject +var myComplexObject = new MyComplexObject() { ... }; -localObjectStorageHelper.SaveFileAsync(keySimpleObject, o); +await appDataStorageHelper.SaveFileAsync(complexObjectKey, myComplexObject); // Complex object -public class MyLargeObject +public class MyComplexObject { public string MyContent { get; set; } public List MyContents { get; set; } - public List MyObjects { get; set; } + public List MyObjects { get; set; } } \ No newline at end of file diff --git a/Microsoft.Toolkit.Uwp.SampleApp/SamplePages/Object Storage/ObjectStoragePage.xaml.cs b/Microsoft.Toolkit.Uwp.SampleApp/SamplePages/Object Storage/ObjectStoragePage.xaml.cs index e2da83f53..9bc0b00df 100644 --- a/Microsoft.Toolkit.Uwp.SampleApp/SamplePages/Object Storage/ObjectStoragePage.xaml.cs +++ b/Microsoft.Toolkit.Uwp.SampleApp/SamplePages/Object Storage/ObjectStoragePage.xaml.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +using Microsoft.Toolkit.Helpers; using Microsoft.Toolkit.Uwp.Helpers; using Windows.UI.Xaml; @@ -9,7 +10,7 @@ namespace Microsoft.Toolkit.Uwp.SampleApp.SamplePages { public sealed partial class ObjectStoragePage { - private readonly IObjectStorageHelper localStorageHelper = new LocalObjectStorageHelper(new SystemSerializer()); + private readonly ApplicationDataStorageHelper _settingsStorage = ApplicationDataStorageHelper.GetCurrent(); public ObjectStoragePage() { @@ -24,9 +25,9 @@ namespace Microsoft.Toolkit.Uwp.SampleApp.SamplePages } // Read from local storage - if (localStorageHelper.KeyExists(KeyTextBox.Text)) + if (_settingsStorage.KeyExists(KeyTextBox.Text)) { - ContentTextBox.Text = localStorageHelper.Read(KeyTextBox.Text); + ContentTextBox.Text = _settingsStorage.Read(KeyTextBox.Text); } } @@ -43,7 +44,7 @@ namespace Microsoft.Toolkit.Uwp.SampleApp.SamplePages } // Save into local storage - localStorageHelper.Save(KeyTextBox.Text, ContentTextBox.Text); + _settingsStorage.Save(KeyTextBox.Text, ContentTextBox.Text); } } } \ No newline at end of file diff --git a/Microsoft.Toolkit.Uwp.SampleApp/SamplePages/Primitives/ConstrainedBox.bind b/Microsoft.Toolkit.Uwp.SampleApp/SamplePages/Primitives/ConstrainedBox.bind new file mode 100644 index 000000000..3976530dc --- /dev/null +++ b/Microsoft.Toolkit.Uwp.SampleApp/SamplePages/Primitives/ConstrainedBox.bind @@ -0,0 +1,28 @@ + + + + + + + + + + + + + + diff --git a/Microsoft.Toolkit.Uwp.SampleApp/SamplePages/Primitives/ConstrainedBox.png b/Microsoft.Toolkit.Uwp.SampleApp/SamplePages/Primitives/ConstrainedBox.png new file mode 100644 index 000000000..ca0f21f55 Binary files /dev/null and b/Microsoft.Toolkit.Uwp.SampleApp/SamplePages/Primitives/ConstrainedBox.png differ diff --git a/Microsoft.Toolkit.Uwp.SampleApp/SamplePages/RichSuggestBox/RichSuggestBox.png b/Microsoft.Toolkit.Uwp.SampleApp/SamplePages/RichSuggestBox/RichSuggestBox.png new file mode 100644 index 000000000..47e34d69c Binary files /dev/null and b/Microsoft.Toolkit.Uwp.SampleApp/SamplePages/RichSuggestBox/RichSuggestBox.png differ diff --git a/Microsoft.Toolkit.Uwp.SampleApp/SamplePages/RichSuggestBox/RichSuggestBoxCode.bind b/Microsoft.Toolkit.Uwp.SampleApp/SamplePages/RichSuggestBox/RichSuggestBoxCode.bind new file mode 100644 index 000000000..0c4e59518 --- /dev/null +++ b/Microsoft.Toolkit.Uwp.SampleApp/SamplePages/RichSuggestBox/RichSuggestBoxCode.bind @@ -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)); + } +} diff --git a/Microsoft.Toolkit.Uwp.SampleApp/SamplePages/RichSuggestBox/RichSuggestBoxPage.xaml b/Microsoft.Toolkit.Uwp.SampleApp/SamplePages/RichSuggestBox/RichSuggestBoxPage.xaml new file mode 100644 index 000000000..a57d44b95 --- /dev/null +++ b/Microsoft.Toolkit.Uwp.SampleApp/SamplePages/RichSuggestBox/RichSuggestBoxPage.xaml @@ -0,0 +1,20 @@ +ο»Ώ + + + + + + + + + + + + diff --git a/Microsoft.Toolkit.Uwp.SampleApp/SamplePages/RichSuggestBox/RichSuggestBoxPage.xaml.cs b/Microsoft.Toolkit.Uwp.SampleApp/SamplePages/RichSuggestBox/RichSuggestBoxPage.xaml.cs new file mode 100644 index 000000000..20251c74c --- /dev/null +++ b/Microsoft.Toolkit.Uwp.SampleApp/SamplePages/RichSuggestBox/RichSuggestBoxPage.xaml.cs @@ -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 +{ + /// + /// An empty page that can be used on its own or navigated to within a Frame. + /// + public sealed partial class RichSuggestBoxPage : Page, IXamlRenderListener + { + private readonly List _emailSamples = new List() + { + 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 _samples = new List() + { + 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)); + } + } + } +} diff --git a/Microsoft.Toolkit.Uwp.SampleApp/SamplePages/RichSuggestBox/RichSuggestBoxXaml.bind b/Microsoft.Toolkit.Uwp.SampleApp/SamplePages/RichSuggestBox/RichSuggestBoxXaml.bind new file mode 100644 index 000000000..e5325501d --- /dev/null +++ b/Microsoft.Toolkit.Uwp.SampleApp/SamplePages/RichSuggestBox/RichSuggestBoxXaml.bind @@ -0,0 +1,97 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + Text: + + Position: + + Id: + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Microsoft.Toolkit.Uwp.SampleApp/SamplePages/RichSuggestBox/SuggestionTemplateSelector.cs b/Microsoft.Toolkit.Uwp.SampleApp/SamplePages/RichSuggestBox/SuggestionTemplateSelector.cs new file mode 100644 index 000000000..863a9c627 --- /dev/null +++ b/Microsoft.Toolkit.Uwp.SampleApp/SamplePages/RichSuggestBox/SuggestionTemplateSelector.cs @@ -0,0 +1,21 @@ +// 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 Windows.UI.Xaml; +using Windows.UI.Xaml.Controls; + +namespace Microsoft.Toolkit.Uwp.SampleApp.SamplePages +{ + public class SuggestionTemplateSelector : DataTemplateSelector + { + public DataTemplate Person { get; set; } + + public DataTemplate Data { get; set; } + + protected override DataTemplate SelectTemplateCore(object item) + { + return item is SampleEmailDataType ? this.Person : this.Data; + } + } +} diff --git a/Microsoft.Toolkit.Uwp.SampleApp/SamplePages/Shadows/AttachedDropShadowPage.xaml b/Microsoft.Toolkit.Uwp.SampleApp/SamplePages/Shadows/AttachedDropShadowPage.xaml new file mode 100644 index 000000000..95866761d --- /dev/null +++ b/Microsoft.Toolkit.Uwp.SampleApp/SamplePages/Shadows/AttachedDropShadowPage.xaml @@ -0,0 +1,9 @@ + + + + \ No newline at end of file diff --git a/Microsoft.Toolkit.Uwp.SampleApp/SamplePages/Shadows/AttachedDropShadowPage.xaml.cs b/Microsoft.Toolkit.Uwp.SampleApp/SamplePages/Shadows/AttachedDropShadowPage.xaml.cs new file mode 100644 index 000000000..d750e12f3 --- /dev/null +++ b/Microsoft.Toolkit.Uwp.SampleApp/SamplePages/Shadows/AttachedDropShadowPage.xaml.cs @@ -0,0 +1,30 @@ +// 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 Microsoft.Toolkit.Uwp.UI; +using Windows.UI.Xaml; + +namespace Microsoft.Toolkit.Uwp.SampleApp.SamplePages +{ + public sealed partial class AttachedDropShadowPage : IXamlRenderListener + { + public AttachedDropShadowPage() + { + InitializeComponent(); + } + + public void OnXamlRendered(FrameworkElement control) + { + // This is done as we don't have x:Bind in live xaml, so we find and attach after. + var castToTarget = control.FindChild("ShadowTarget"); + if (castToTarget != null) + { + if (control.Resources.TryGetValue("CommonShadow", out var resource) && resource is AttachedDropShadow shadow) + { + shadow.CastTo = castToTarget; + } + } + } + } +} \ No newline at end of file diff --git a/Microsoft.Toolkit.Uwp.SampleApp/SamplePages/Shadows/AttachedShadowCompositionXaml.bind b/Microsoft.Toolkit.Uwp.SampleApp/SamplePages/Shadows/AttachedShadowCompositionXaml.bind new file mode 100644 index 000000000..b594d2509 --- /dev/null +++ b/Microsoft.Toolkit.Uwp.SampleApp/SamplePages/Shadows/AttachedShadowCompositionXaml.bind @@ -0,0 +1,85 @@ + + + + + + + + + + + + + + + protected object Image { get; private set; } + /// + public bool WaitUntilLoaded => true; + /// /// Initializes a new instance of the class. /// diff --git a/Microsoft.Toolkit.Uwp.UI.Controls.Core/TabbedCommandBar/TabbedCommandBar.cs b/Microsoft.Toolkit.Uwp.UI.Controls.Core/TabbedCommandBar/TabbedCommandBar.cs index d569f476c..beb71b3a6 100644 --- a/Microsoft.Toolkit.Uwp.UI.Controls.Core/TabbedCommandBar/TabbedCommandBar.cs +++ b/Microsoft.Toolkit.Uwp.UI.Controls.Core/TabbedCommandBar/TabbedCommandBar.cs @@ -6,8 +6,9 @@ using System.Linq; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Markup; -using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Media.Animation; +using NavigationView = Microsoft.UI.Xaml.Controls.NavigationView; +using NavigationViewSelectionChangedEventArgs = Microsoft.UI.Xaml.Controls.NavigationViewSelectionChangedEventArgs; namespace Microsoft.Toolkit.Uwp.UI.Controls { @@ -36,8 +37,10 @@ namespace Microsoft.Toolkit.Uwp.UI.Controls public TabbedCommandBar() { DefaultStyleKey = typeof(TabbedCommandBar); + DefaultStyleResourceUri = new System.Uri("ms-appx:///Microsoft.Toolkit.Uwp.UI.Controls.Core/Themes/Generic.xaml"); SelectionChanged += SelectedItemChanged; + Loaded += TabbedCommandBar_Loaded; } /// @@ -55,6 +58,15 @@ namespace Microsoft.Toolkit.Uwp.UI.Controls _tabbedCommandBarContentBorder = GetTemplateChild("PART_TabbedCommandBarContentBorder") as Border; _tabChangedStoryboard = GetTemplateChild("TabChangedStoryboard") as Storyboard; + // TODO: We could maybe optimize and use a lower-level Loaded event for what's hosting the MenuItems + // to set SelectedItem, but then we may have to pull in another template part, so think we're OK + // to do the Loaded event at the top level. + } + + private void TabbedCommandBar_Loaded(object sender, RoutedEventArgs e) + { + // We need to select the item after the template is realized, otherwise the SelectedItem's + // DataTemplate bindings don't properly navigate the visual tree. SelectedItem = MenuItems.FirstOrDefault(); } diff --git a/Microsoft.Toolkit.Uwp.UI.Controls.Core/TabbedCommandBar/TabbedCommandBar.xaml b/Microsoft.Toolkit.Uwp.UI.Controls.Core/TabbedCommandBar/TabbedCommandBar.xaml index 2bbfdf236..f3c2e59ee 100644 --- a/Microsoft.Toolkit.Uwp.UI.Controls.Core/TabbedCommandBar/TabbedCommandBar.xaml +++ b/Microsoft.Toolkit.Uwp.UI.Controls.Core/TabbedCommandBar/TabbedCommandBar.xaml @@ -1,7 +1,8 @@ + xmlns:muxc="using:Microsoft.UI.Xaml.Controls"> @@ -16,239 +17,265 @@ + + - + - + + + + + + + + + + + + + + + + + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - \ No newline at end of file + diff --git a/Microsoft.Toolkit.Uwp.UI.Controls.Core/TabbedCommandBar/TabbedCommandBarItem.xaml b/Microsoft.Toolkit.Uwp.UI.Controls.Core/TabbedCommandBar/TabbedCommandBarItem.xaml index 52e480179..6a43a028c 100644 --- a/Microsoft.Toolkit.Uwp.UI.Controls.Core/TabbedCommandBar/TabbedCommandBarItem.xaml +++ b/Microsoft.Toolkit.Uwp.UI.Controls.Core/TabbedCommandBar/TabbedCommandBarItem.xaml @@ -1,15 +1,34 @@ + xmlns:controls="using:Microsoft.Toolkit.Uwp.UI.Controls" + xmlns:muxc="using:Microsoft.UI.Xaml.Controls"> + + + + + + + + + + + + - - - + + - - - + - - - - - - - + + + + + + + - + - - + + - - + + + + + + - + - - - - - + + + + + - - - - - + + + + + - - - - + + + + - - - - + + + + - - - - + + + + - - - - + + + + - - - - - + + + + + - - - - - + + + + + - - - - - + + + + + - - - - - - + + + + + + - - - - - - + + + + + + - - - - - - + + + + + + - - - - - - + + + + + + - + - - + + - - - - - - + Background="{TemplateBinding Background}" /> + Grid.Column="2" + Background="{TemplateBinding Background}" /> + CornerRadius="{TemplateBinding CornerRadius}" /> diff --git a/Microsoft.Toolkit.Uwp.UI.Controls.Core/VisualStudioToolsManifest.xml b/Microsoft.Toolkit.Uwp.UI.Controls.Core/VisualStudioToolsManifest.xml index 161131ea6..031faeee5 100644 --- a/Microsoft.Toolkit.Uwp.UI.Controls.Core/VisualStudioToolsManifest.xml +++ b/Microsoft.Toolkit.Uwp.UI.Controls.Core/VisualStudioToolsManifest.xml @@ -1,6 +1,8 @@ - + @@ -13,6 +15,7 @@ + diff --git a/Microsoft.Toolkit.Uwp.UI.Controls.DataGrid/DataGrid/DataGrid.xaml b/Microsoft.Toolkit.Uwp.UI.Controls.DataGrid/DataGrid/DataGrid.xaml index b16f85834..b6365ae54 100644 --- a/Microsoft.Toolkit.Uwp.UI.Controls.DataGrid/DataGrid/DataGrid.xaml +++ b/Microsoft.Toolkit.Uwp.UI.Controls.DataGrid/DataGrid/DataGrid.xaml @@ -28,6 +28,10 @@ + + + + @@ -41,6 +45,10 @@ + + + + @@ -54,6 +62,10 @@ + + + + @@ -89,13 +101,9 @@ - - - - @@ -967,4 +975,4 @@ - \ No newline at end of file + diff --git a/Microsoft.Toolkit.Uwp.UI.Controls.DataGrid/DataGrid/DataGridRow.cs b/Microsoft.Toolkit.Uwp.UI.Controls.DataGrid/DataGrid/DataGridRow.cs index 86840408c..c721cf7ef 100644 --- a/Microsoft.Toolkit.Uwp.UI.Controls.DataGrid/DataGrid/DataGridRow.cs +++ b/Microsoft.Toolkit.Uwp.UI.Controls.DataGrid/DataGrid/DataGridRow.cs @@ -1122,40 +1122,11 @@ namespace Microsoft.Toolkit.Uwp.UI.Controls { DiagnosticsDebug.Assert(this.Index != -1, "Expected Index other than -1."); - PropertyMetadata metadataInfo = DataGridRow.ForegroundProperty.GetMetadata(typeof(DataGridRow)); - Brush defaultForeground = metadataInfo == null ? null : metadataInfo.DefaultValue as Brush; - Brush newForeground = null; + var newForeground = this.Index % 2 == 0 || this.OwningGrid.AlternatingRowForeground == null + ? this.OwningGrid.RowForeground + : this.OwningGrid.AlternatingRowForeground; - if (this.Foreground.Equals(defaultForeground)) - { - if (this.Index % 2 == 0 || this.OwningGrid.AlternatingRowForeground == null) - { - // Use OwningGrid.RowForeground if the index is even or if the OwningGrid.AlternatingRowForeground is null - if (this.OwningGrid.RowForeground != null) - { - newForeground = this.OwningGrid.RowForeground; - } - } - else - { - // Alternate row - if (this.OwningGrid.AlternatingRowForeground != null) - { - newForeground = this.OwningGrid.AlternatingRowForeground; - } - } - - if (newForeground == null) - { - newForeground = this.Foreground; - } - } - else - { - newForeground = this.Foreground; - } - - this.ComputedForeground = newForeground; + this.ComputedForeground = newForeground ?? this.Foreground; } else { diff --git a/Microsoft.Toolkit.Uwp.UI.Controls.DataGrid/VisualStudioToolsManifest.xml b/Microsoft.Toolkit.Uwp.UI.Controls.DataGrid/VisualStudioToolsManifest.xml index 761934998..0eef95ce9 100644 --- a/Microsoft.Toolkit.Uwp.UI.Controls.DataGrid/VisualStudioToolsManifest.xml +++ b/Microsoft.Toolkit.Uwp.UI.Controls.DataGrid/VisualStudioToolsManifest.xml @@ -1,7 +1,26 @@ - + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Microsoft.Toolkit.Uwp.UI.Controls.Input/RichSuggestBox/RichSuggestBox.Events.cs b/Microsoft.Toolkit.Uwp.UI.Controls.Input/RichSuggestBox/RichSuggestBox.Events.cs new file mode 100644 index 000000000..c57bfd7b6 --- /dev/null +++ b/Microsoft.Toolkit.Uwp.UI.Controls.Input/RichSuggestBox/RichSuggestBox.Events.cs @@ -0,0 +1,52 @@ +// 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 Windows.Foundation; +using Windows.UI.Xaml; +using Windows.UI.Xaml.Controls; + +namespace Microsoft.Toolkit.Uwp.UI.Controls +{ + /// + /// The RichSuggestBox control extends control that suggests and embeds custom data in a rich document. + /// + public partial class RichSuggestBox + { + /// + /// Event raised when the control needs to show suggestions. + /// + public event TypedEventHandler SuggestionRequested; + + /// + /// Event raised when user click on a suggestion. + /// This event lets you customize the token appearance in the document. + /// + public event TypedEventHandler SuggestionChosen; + + /// + /// Event raised when a token is fully highlighted. + /// + public event TypedEventHandler TokenSelected; + + /// + /// Event raised when a pointer is hovering over a token. + /// + public event TypedEventHandler TokenPointerOver; + + /// + /// Event raised when text is changed, either by user or by internal formatting. + /// + public event TypedEventHandler TextChanged; + + /// + /// Event raised when the text selection has changed. + /// + public event TypedEventHandler SelectionChanged; + + /// + /// Event raised when text is pasted into the control. + /// + public event TypedEventHandler Paste; + } +} diff --git a/Microsoft.Toolkit.Uwp.UI.Controls.Input/RichSuggestBox/RichSuggestBox.Helpers.cs b/Microsoft.Toolkit.Uwp.UI.Controls.Input/RichSuggestBox/RichSuggestBox.Helpers.cs new file mode 100644 index 000000000..0357e261b --- /dev/null +++ b/Microsoft.Toolkit.Uwp.UI.Controls.Input/RichSuggestBox/RichSuggestBox.Helpers.cs @@ -0,0 +1,140 @@ +// 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.Linq; +using Windows.Foundation; +using Windows.Graphics.Display; +using Windows.UI.Core; +using Windows.UI.Text; +using Windows.UI.ViewManagement; +using Windows.UI.Xaml; +using Windows.UI.Xaml.Controls; + +namespace Microsoft.Toolkit.Uwp.UI.Controls +{ + /// + /// The RichSuggestBox control extends control that suggests and embeds custom data in a rich document. + /// + public partial class RichSuggestBox + { + private static bool IsElementOnScreen(FrameworkElement element, double offsetX = 0, double offsetY = 0) + { + // DisplayInformation only works in UWP. No alternative to get DisplayInformation.ScreenHeightInRawPixels + // Or Window position in Window.Current.Bounds + // Tracking issues: + // https://github.com/microsoft/WindowsAppSDK/issues/114 + // https://github.com/microsoft/microsoft-ui-xaml/issues/4228 + // TODO: Remove when DisplayInformation.ScreenHeightInRawPixels alternative is available + if (CoreWindow.GetForCurrentThread() == null) + { + return true; + } + + // Get bounds of element from root of tree + var elementBounds = element.CoordinatesFrom(null).ToRect(element.ActualWidth, element.ActualHeight); + + // Apply offset + elementBounds.X += offsetX; + elementBounds.Y += offsetY; + + // Get Window position + var windowBounds = Window.Current.Bounds; + + // Offset Element within Window on Screen + elementBounds.X += windowBounds.X; + elementBounds.Y += windowBounds.Y; + + // Get Screen DPI info + var displayInfo = DisplayInformation.GetForCurrentView(); + var scaleFactor = displayInfo.RawPixelsPerViewPixel; + var displayHeight = displayInfo.ScreenHeightInRawPixels; + + // Check if top/bottom are within confines of screen + return elementBounds.Top * scaleFactor >= 0 && elementBounds.Bottom * scaleFactor <= displayHeight; + } + + private static bool IsElementInsideWindow(FrameworkElement element, double offsetX = 0, double offsetY = 0) + { + // Get bounds of element from root of tree + var elementBounds = element.CoordinatesFrom(null).ToRect(element.ActualWidth, element.ActualHeight); + + // Apply offset + elementBounds.X += offsetX; + elementBounds.Y += offsetY; + + // Get size of window itself + var windowBounds = ControlHelpers.IsXamlRootAvailable && element.XamlRoot != null + ? element.XamlRoot.Size.ToRect() + : ApplicationView.GetForCurrentView().VisibleBounds.ToSize().ToRect(); // Normalize + + // Calculate if there's an intersection + elementBounds.Intersect(windowBounds); + + // See if we are still fully visible within the Window + return elementBounds.Height >= element.ActualHeight; + } + + private static string EnforcePrefixesRequirements(string value) + { + return string.IsNullOrEmpty(value) ? string.Empty : string.Concat(value.Where(char.IsPunctuation)); + } + + /// + /// Pad range with Zero-Width-Spaces. + /// + /// Range to pad. + /// Character format to apply to the padding. + private static void PadRange(ITextRange range, ITextCharacterFormat format) + { + var startPosition = range.StartPosition; + var endPosition = range.EndPosition + 1; + var clone = range.GetClone(); + clone.Collapse(true); + clone.SetText(TextSetOptions.Unhide, "\u200B"); + clone.CharacterFormat.SetClone(format); + clone.SetRange(endPosition, endPosition); + clone.SetText(TextSetOptions.Unhide, "\u200B"); + clone.CharacterFormat.SetClone(format); + range.SetRange(startPosition, endPosition + 1); + } + + private static void ForEachLinkInDocument(ITextDocument document, Action action) + { + var range = document.GetRange(0, 0); + range.SetIndex(TextRangeUnit.Character, -1, false); + + // Handle link at the very end of the document where GetIndex fails to detect + range.Expand(TextRangeUnit.Link); + if (!string.IsNullOrEmpty(range.Link)) + { + action?.Invoke(range); + } + + var nextIndex = range.GetIndex(TextRangeUnit.Link); + while (nextIndex != 0 && nextIndex != 1) + { + range.Move(TextRangeUnit.Link, -1); + + var linkRange = range.GetClone(); + linkRange.Expand(TextRangeUnit.Link); + + // Adjacent links have the same index. Manually check each link with Collapse and Expand. + var previousStart = linkRange.StartPosition; + var hasAdjacentToken = true; + while (hasAdjacentToken) + { + action?.Invoke(linkRange); + + linkRange.Collapse(false); + linkRange.Expand(TextRangeUnit.Link); + hasAdjacentToken = !string.IsNullOrEmpty(linkRange.Link) && linkRange.StartPosition != previousStart; + previousStart = linkRange.StartPosition; + } + + nextIndex = range.GetIndex(TextRangeUnit.Link); + } + } + } +} diff --git a/Microsoft.Toolkit.Uwp.UI.Controls.Input/RichSuggestBox/RichSuggestBox.Properties.cs b/Microsoft.Toolkit.Uwp.UI.Controls.Input/RichSuggestBox/RichSuggestBox.Properties.cs new file mode 100644 index 000000000..dbaf4ca58 --- /dev/null +++ b/Microsoft.Toolkit.Uwp.UI.Controls.Input/RichSuggestBox/RichSuggestBox.Properties.cs @@ -0,0 +1,372 @@ +// 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.Collections.ObjectModel; +using Windows.UI.Text; +using Windows.UI.Xaml; +using Windows.UI.Xaml.Controls; +using Windows.UI.Xaml.Media; + +namespace Microsoft.Toolkit.Uwp.UI.Controls +{ + /// + /// The RichSuggestBox control extends control that suggests and embeds custom data in a rich document. + /// + public partial class RichSuggestBox + { + /// + /// Identifies the dependency property. + /// + public static readonly DependencyProperty PlaceholderTextProperty = + DependencyProperty.Register( + nameof(PlaceholderText), + typeof(string), + typeof(RichSuggestBox), + new PropertyMetadata(string.Empty)); + + /// + /// Identifies the dependency property. + /// + public static readonly DependencyProperty RichEditBoxStyleProperty = + DependencyProperty.Register( + nameof(RichEditBoxStyle), + typeof(Style), + typeof(RichSuggestBox), + new PropertyMetadata(null)); + + /// + /// Identifies the dependency property. + /// + public static readonly DependencyProperty HeaderProperty = + DependencyProperty.Register( + nameof(Header), + typeof(object), + typeof(RichSuggestBox), + new PropertyMetadata(null, OnHeaderChanged)); + + /// + /// Identifies the dependency property. + /// + public static readonly DependencyProperty HeaderTemplateProperty = + DependencyProperty.Register( + nameof(HeaderTemplate), + typeof(DataTemplate), + typeof(RichSuggestBox), + new PropertyMetadata(null)); + + /// + /// Identifies the dependency property. + /// + public static readonly DependencyProperty DescriptionProperty = + DependencyProperty.Register( + nameof(Description), + typeof(object), + typeof(RichSuggestBox), + new PropertyMetadata(null, OnDescriptionChanged)); + + /// + /// Identifies the dependency property. + /// + public static readonly DependencyProperty PopupPlacementProperty = + DependencyProperty.Register( + nameof(PopupPlacement), + typeof(SuggestionPopupPlacementMode), + typeof(RichSuggestBox), + new PropertyMetadata(SuggestionPopupPlacementMode.Floating, OnSuggestionPopupPlacementChanged)); + + /// + /// Identifies the dependency property. + /// + public static readonly DependencyProperty PopupCornerRadiusProperty = + DependencyProperty.Register( + nameof(PopupCornerRadius), + typeof(CornerRadius), + typeof(RichSuggestBox), + new PropertyMetadata(default(CornerRadius))); + + /// + /// Identifies the dependency property. + /// + public static readonly DependencyProperty PopupHeaderProperty = + DependencyProperty.Register( + nameof(PopupHeader), + typeof(object), + typeof(RichSuggestBox), + new PropertyMetadata(null)); + + /// + /// Identifies the dependency property. + /// + public static readonly DependencyProperty PopupHeaderTemplateProperty = + DependencyProperty.Register( + nameof(PopupHeaderTemplate), + typeof(DataTemplate), + typeof(RichSuggestBox), + new PropertyMetadata(null)); + + /// + /// Identifies the dependency property. + /// + public static readonly DependencyProperty PopupFooterProperty = + DependencyProperty.Register( + nameof(PopupFooter), + typeof(object), + typeof(RichSuggestBox), + new PropertyMetadata(null)); + + /// + /// Identifies the dependency property. + /// + public static readonly DependencyProperty PopupFooterTemplateProperty = + DependencyProperty.Register( + nameof(PopupFooterTemplate), + typeof(DataTemplate), + typeof(RichSuggestBox), + new PropertyMetadata(null)); + + /// + /// Identifies the dependency property. + /// + public static readonly DependencyProperty TokenBackgroundProperty = + DependencyProperty.Register( + nameof(TokenBackground), + typeof(SolidColorBrush), + typeof(RichSuggestBox), + new PropertyMetadata(null)); + + /// + /// Identifies the dependency property. + /// + public static readonly DependencyProperty TokenForegroundProperty = + DependencyProperty.Register( + nameof(TokenForeground), + typeof(SolidColorBrush), + typeof(RichSuggestBox), + new PropertyMetadata(null)); + + /// + /// Identifies the dependency property. + /// + public static readonly DependencyProperty PrefixesProperty = + DependencyProperty.Register( + nameof(Prefixes), + typeof(string), + typeof(RichSuggestBox), + new PropertyMetadata(string.Empty, OnPrefixesChanged)); + + /// + /// Identifies the dependency property. + /// + public static readonly DependencyProperty ClipboardPasteFormatProperty = + DependencyProperty.Register( + nameof(ClipboardPasteFormat), + typeof(RichEditClipboardFormat), + typeof(RichSuggestBox), + new PropertyMetadata(RichEditClipboardFormat.AllFormats)); + + /// + /// Identifies the dependency property. + /// + public static readonly DependencyProperty ClipboardCopyFormatProperty = + DependencyProperty.Register( + nameof(ClipboardCopyFormat), + typeof(RichEditClipboardFormat), + typeof(RichSuggestBox), + new PropertyMetadata(RichEditClipboardFormat.AllFormats)); + + /// + /// Identifies the dependency property. + /// + public static readonly DependencyProperty DisabledFormattingAcceleratorsProperty = + DependencyProperty.Register( + nameof(DisabledFormattingAccelerators), + typeof(DisabledFormattingAccelerators), + typeof(RichSuggestBox), + new PropertyMetadata(DisabledFormattingAccelerators.None)); + + /// + /// Gets or sets the text that is displayed in the control until the value is changed by a user action or some other operation. + /// + public string PlaceholderText + { + get => (string)GetValue(PlaceholderTextProperty); + set => SetValue(PlaceholderTextProperty, value); + } + + /// + /// Gets or sets the style of the underlying . + /// + public Style RichEditBoxStyle + { + get => (Style)GetValue(RichEditBoxStyleProperty); + set => SetValue(RichEditBoxStyleProperty, value); + } + + /// + /// Gets or sets the content for the control's header. + /// + /// + /// Suggestion popup relies on the actual size of the text control to calculate its placement on the screen. + /// It is recommended to set the header using this property instead of using . + /// + public object Header + { + get => GetValue(HeaderProperty); + set => SetValue(HeaderProperty, value); + } + + /// + /// Gets or sets the used to display the content of the control's header. + /// + public DataTemplate HeaderTemplate + { + get => (DataTemplate)GetValue(HeaderTemplateProperty); + set => SetValue(HeaderTemplateProperty, value); + } + + /// + /// Gets or sets content that is shown below the control. The content should provide guidance about the input expected by the control. + /// + /// + /// Suggestion popup relies on the actual size of the text control to calculate its placement on the screen. + /// It is recommended to set the description using this property instead of using . + /// + public object Description + { + get => GetValue(DescriptionProperty); + set => SetValue(DescriptionProperty, value); + } + + /// + /// Gets or sets suggestion popup placement to either Floating or Attached to the text box. + /// + public SuggestionPopupPlacementMode PopupPlacement + { + get => (SuggestionPopupPlacementMode)GetValue(PopupPlacementProperty); + set => SetValue(PopupPlacementProperty, value); + } + + /// + /// Gets or sets the radius for the corners of the popup control's border. + /// + public CornerRadius PopupCornerRadius + { + get => (CornerRadius)GetValue(PopupCornerRadiusProperty); + set => SetValue(PopupCornerRadiusProperty, value); + } + + /// + /// Gets or sets the content for the suggestion popup control's header. + /// + public object PopupHeader + { + get => GetValue(PopupHeaderProperty); + set => SetValue(PopupHeaderProperty, value); + } + + /// + /// Gets or sets the used to display the content of the suggestion popup control's header. + /// + public DataTemplate PopupHeaderTemplate + { + get => (DataTemplate)GetValue(PopupHeaderTemplateProperty); + set => SetValue(PopupHeaderTemplateProperty, value); + } + + /// + /// Gets or sets the content for the suggestion popup control's footer. + /// + public object PopupFooter + { + get => GetValue(PopupFooterProperty); + set => SetValue(PopupFooterProperty, value); + } + + /// + /// Gets or sets the used to display the content of the suggestion popup control's footer. + /// + public DataTemplate PopupFooterTemplate + { + get => (DataTemplate)GetValue(PopupFooterTemplateProperty); + set => SetValue(PopupFooterTemplateProperty, value); + } + + /// + /// Gets or sets the default brush used to color the suggestion token background. + /// + public SolidColorBrush TokenBackground + { + get => (SolidColorBrush)GetValue(TokenBackgroundProperty); + set => SetValue(TokenBackgroundProperty, value); + } + + /// + /// Gets or sets the default brush used to color the suggestion token foreground. + /// + public SolidColorBrush TokenForeground + { + get => (SolidColorBrush)GetValue(TokenForegroundProperty); + set => SetValue(TokenForegroundProperty, value); + } + + /// + /// Gets or sets prefix characters to start a query. + /// + /// + /// Prefix characters must be punctuations (must satisfy method). + /// + public string Prefixes + { + get => (string)GetValue(PrefixesProperty); + set => SetValue(PrefixesProperty, value); + } + + /// + /// Gets or sets a value that specifies whether pasted text preserves all formats, or as plain text only. + /// + public RichEditClipboardFormat ClipboardPasteFormat + { + get => (RichEditClipboardFormat)GetValue(ClipboardPasteFormatProperty); + set => SetValue(ClipboardPasteFormatProperty, value); + } + + /// + /// Gets or sets a value that specifies whether text is copied with all formats, or as plain text only. + /// + public RichEditClipboardFormat ClipboardCopyFormat + { + get => (RichEditClipboardFormat)GetValue(ClipboardCopyFormatProperty); + set => SetValue(ClipboardCopyFormatProperty, value); + } + + /// + /// Gets or sets a value that indicates which keyboard shortcuts for formatting are disabled. + /// + public DisabledFormattingAccelerators DisabledFormattingAccelerators + { + get => (DisabledFormattingAccelerators)GetValue(DisabledFormattingAcceleratorsProperty); + set => SetValue(DisabledFormattingAcceleratorsProperty, value); + } + + /// + /// Gets an object that enables access to the text object model for the text contained in a . + /// + public RichEditTextDocument TextDocument => _richEditBox?.TextDocument; + + /// + /// Gets the distance the content has been scrolled horizontally from the underlying . + /// + public double HorizontalOffset => this._scrollViewer?.HorizontalOffset ?? 0; + + /// + /// Gets the distance the content has been scrolled vertically from the underlying . + /// + public double VerticalOffset => this._scrollViewer?.VerticalOffset ?? 0; + + /// + /// Gets a collection of suggestion tokens that are present in the document. + /// + public ReadOnlyObservableCollection Tokens { get; } + } +} diff --git a/Microsoft.Toolkit.Uwp.UI.Controls.Input/RichSuggestBox/RichSuggestBox.cs b/Microsoft.Toolkit.Uwp.UI.Controls.Input/RichSuggestBox/RichSuggestBox.cs new file mode 100644 index 000000000..bb1e1ee00 --- /dev/null +++ b/Microsoft.Toolkit.Uwp.UI.Controls.Input/RichSuggestBox/RichSuggestBox.cs @@ -0,0 +1,993 @@ +// 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.Collections.ObjectModel; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.Toolkit.Uwp.Deferred; +using Windows.ApplicationModel.DataTransfer; +using Windows.Foundation; +using Windows.Foundation.Metadata; +using Windows.System; +using Windows.UI.Input; +using Windows.UI.Text; +using Windows.UI.Xaml; +using Windows.UI.Xaml.Controls; +using Windows.UI.Xaml.Controls.Primitives; +using Windows.UI.Xaml.Input; + +namespace Microsoft.Toolkit.Uwp.UI.Controls +{ + /// + /// The RichSuggestBox control extends control that suggests and embeds custom data in a rich document. + /// + [TemplatePart(Name = PartRichEditBox, Type = typeof(RichEditBox))] + [TemplatePart(Name = PartSuggestionsPopup, Type = typeof(Popup))] + [TemplatePart(Name = PartSuggestionsList, Type = typeof(ListViewBase))] + [TemplatePart(Name = PartSuggestionsContainer, Type = typeof(Border))] + [TemplatePart(Name = PartHeaderContentPresenter, Type = typeof(ContentPresenter))] + [TemplatePart(Name = PartDescriptionPresenter, Type = typeof(ContentPresenter))] + public partial class RichSuggestBox : ItemsControl + { + private const string PartRichEditBox = "RichEditBox"; + private const string PartSuggestionsPopup = "SuggestionsPopup"; + private const string PartSuggestionsList = "SuggestionsList"; + private const string PartSuggestionsContainer = "SuggestionsContainer"; + private const string PartHeaderContentPresenter = "HeaderContentPresenter"; + private const string PartDescriptionPresenter = "DescriptionPresenter"; + + private readonly object _tokensLock; + private readonly Dictionary _tokens; + private readonly ObservableCollection _visibleTokens; + + private Popup _suggestionPopup; + private RichEditBox _richEditBox; + private ScrollViewer _scrollViewer; + private ListViewBase _suggestionsList; + private Border _suggestionsContainer; + + private int _suggestionChoice; + private bool _ignoreChange; + private bool _popupOpenDown; + private bool _textCompositionActive; + private RichSuggestQuery _currentQuery; + + /// + /// Initializes a new instance of the class. + /// + public RichSuggestBox() + { + _tokensLock = new object(); + _tokens = new Dictionary(); + _visibleTokens = new ObservableCollection(); + Tokens = new ReadOnlyObservableCollection(_visibleTokens); + + DefaultStyleKey = typeof(RichSuggestBox); + + RegisterPropertyChangedCallback(CornerRadiusProperty, OnCornerRadiusChanged); + RegisterPropertyChangedCallback(PopupCornerRadiusProperty, OnCornerRadiusChanged); + LostFocus += OnLostFocus; + Loaded += OnLoaded; + } + + /// + /// Clear unused tokens and undo/redo history. + /// + public void ClearUndoRedoSuggestionHistory() + { + TextDocument.ClearUndoRedoHistory(); + lock (_tokensLock) + { + if (_tokens.Count == 0) + { + return; + } + + var keysToDelete = _tokens.Where(pair => !pair.Value.Active).Select(pair => pair.Key).ToArray(); + foreach (var key in keysToDelete) + { + _tokens.Remove(key); + } + } + } + + /// + /// Clear the document and token list. This will also clear the undo/redo history. + /// + public void Clear() + { + lock (_tokensLock) + { + _tokens.Clear(); + _visibleTokens.Clear(); + TextDocument.Selection.Expand(TextRangeUnit.Story); + TextDocument.Selection.Delete(TextRangeUnit.Story, 0); + TextDocument.ClearUndoRedoHistory(); + } + } + + /// + /// Add tokens to be tracked against the document. Duplicate tokens will not be updated. + /// + /// The collection of tokens to be tracked. + public void AddTokens(IEnumerable tokens) + { + lock (_tokensLock) + { + foreach (var token in tokens) + { + _tokens.TryAdd($"\"{token.Id}\"", token); + } + } + } + + /// + /// Populate the with an existing Rich Text Format (RTF) document and a collection of tokens. + /// + /// The Rich Text Format (RTF) text to be imported. + /// The collection of tokens embedded in the document. + public void Load(string rtf, IEnumerable tokens) + { + Clear(); + AddTokens(tokens); + TextDocument.SetText(TextSetOptions.FormatRtf, rtf); + } + + /// + /// Try getting the token associated with a text range. + /// + /// The range of the token to get. + /// When this method returns, contains the token associated with the specified range; otherwise, it is null. + /// true if there is a token associated with the text range; otherwise false. + public bool TryGetTokenFromRange(ITextRange range, out RichSuggestToken token) + { + token = null; + range = range.GetClone(); + if (range != null && !string.IsNullOrEmpty(range.Link)) + { + lock (_tokensLock) + { + return _tokens.TryGetValue(range.Link, out token); + } + } + + return false; + } + + /// + /// Retrieves the bounding rectangle that encompasses the text range + /// with position measured from the top left of the control. + /// + /// Text range to retrieve the bounding box from. + /// The bounding rectangle. + public Rect GetRectFromRange(ITextRange range) + { + var padding = _richEditBox.Padding; + range.GetRect(PointOptions.None, out var rect, out var hit); + rect.X += padding.Left - HorizontalOffset; + rect.Y += padding.Top - VerticalOffset; + var transform = _richEditBox.TransformToVisual(this); + return transform.TransformBounds(rect); + } + + /// + protected override void OnApplyTemplate() + { + base.OnApplyTemplate(); + PointerEventHandler pointerPressedHandler = RichEditBox_OnPointerPressed; + PointerEventHandler pointerMovedHandler = RichEditBox_OnPointerMoved; + + _suggestionPopup = (Popup)GetTemplateChild(PartSuggestionsPopup); + _richEditBox = (RichEditBox)GetTemplateChild(PartRichEditBox); + _suggestionsList = (ListViewBase)GetTemplateChild(PartSuggestionsList); + _suggestionsContainer = (Border)GetTemplateChild(PartSuggestionsContainer); + ConditionallyLoadElement(Header, PartHeaderContentPresenter); + ConditionallyLoadElement(Description, PartDescriptionPresenter); + + if (_richEditBox != null) + { + _richEditBox.SizeChanged -= RichEditBox_SizeChanged; + _richEditBox.TextChanging -= RichEditBox_TextChanging; + _richEditBox.TextChanged -= RichEditBox_TextChanged; + _richEditBox.TextCompositionStarted -= RichEditBox_TextCompositionStarted; + _richEditBox.TextCompositionChanged -= RichEditBox_TextCompositionChanged; + _richEditBox.TextCompositionEnded -= RichEditBox_TextCompositionEnded; + _richEditBox.SelectionChanging -= RichEditBox_SelectionChanging; + _richEditBox.SelectionChanged -= RichEditBox_SelectionChanged; + _richEditBox.Paste -= RichEditBox_Paste; + _richEditBox.PreviewKeyDown -= RichEditBox_PreviewKeyDown; + _richEditBox.RemoveHandler(PointerMovedEvent, pointerMovedHandler); + _richEditBox.RemoveHandler(PointerPressedEvent, pointerPressedHandler); + _richEditBox.ProcessKeyboardAccelerators -= RichEditBox_ProcessKeyboardAccelerators; + + _richEditBox.SizeChanged += RichEditBox_SizeChanged; + _richEditBox.TextChanging += RichEditBox_TextChanging; + _richEditBox.TextChanged += RichEditBox_TextChanged; + _richEditBox.TextCompositionStarted += RichEditBox_TextCompositionStarted; + _richEditBox.TextCompositionChanged += RichEditBox_TextCompositionChanged; + _richEditBox.TextCompositionEnded += RichEditBox_TextCompositionEnded; + _richEditBox.SelectionChanging += RichEditBox_SelectionChanging; + _richEditBox.SelectionChanged += RichEditBox_SelectionChanged; + _richEditBox.Paste += RichEditBox_Paste; + _richEditBox.PreviewKeyDown += RichEditBox_PreviewKeyDown; + _richEditBox.AddHandler(PointerMovedEvent, pointerMovedHandler, true); + _richEditBox.AddHandler(PointerPressedEvent, pointerPressedHandler, true); + _richEditBox.ProcessKeyboardAccelerators += RichEditBox_ProcessKeyboardAccelerators; + } + + if (_suggestionsList != null) + { + _suggestionsList.ItemClick -= SuggestionsList_ItemClick; + _suggestionsList.SizeChanged -= SuggestionsList_SizeChanged; + _suggestionsList.GotFocus -= SuggestionList_GotFocus; + + _suggestionsList.ItemClick += SuggestionsList_ItemClick; + _suggestionsList.SizeChanged += SuggestionsList_SizeChanged; + _suggestionsList.GotFocus += SuggestionList_GotFocus; + } + } + + private static void OnHeaderChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) + { + var view = (RichSuggestBox)d; + view.ConditionallyLoadElement(e.NewValue, PartHeaderContentPresenter); + } + + private static void OnDescriptionChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) + { + var view = (RichSuggestBox)d; + view.ConditionallyLoadElement(e.NewValue, PartDescriptionPresenter); + } + + private static void OnSuggestionPopupPlacementChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) + { + var view = (RichSuggestBox)d; + view.UpdatePopupWidth(); + } + + private static void OnPrefixesChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) + { + var view = (RichSuggestBox)d; + + var newValue = (string)e.NewValue; + var prefixes = EnforcePrefixesRequirements(newValue); + + if (newValue != prefixes) + { + view.SetValue(PrefixesProperty, prefixes); + } + } + + private void OnCornerRadiusChanged(DependencyObject sender, DependencyProperty dp) + { + UpdateCornerRadii(); + } + + private void OnLoaded(object sender, RoutedEventArgs e) + { + _scrollViewer = _richEditBox?.FindDescendant(); + } + + private void OnLostFocus(object sender, RoutedEventArgs e) + { + ShowSuggestionsPopup(false); + } + + private void SuggestionsList_SizeChanged(object sender, SizeChangedEventArgs e) + { + if (this._suggestionPopup.IsOpen) + { + this.UpdatePopupOffset(); + } + } + + private void SuggestionList_GotFocus(object sender, RoutedEventArgs e) + { + if (_richEditBox != null) + { + _richEditBox.Focus(FocusState.Programmatic); + } + } + + private void RichEditBox_OnPointerMoved(object sender, PointerRoutedEventArgs e) + { + var pointer = e.GetCurrentPoint(this); + if (this.TokenPointerOver != null) + { + this.InvokeTokenPointerOver(pointer); + } + } + + private void RichEditBox_SelectionChanging(RichEditBox sender, RichEditBoxSelectionChangingEventArgs args) + { + var selection = TextDocument.Selection; + + if (selection.Type != SelectionType.InsertionPoint && selection.Type != SelectionType.Normal) + { + return; + } + + var range = selection.GetClone(); + range.Expand(TextRangeUnit.Link); + lock (_tokensLock) + { + if (!_tokens.ContainsKey(range.Link)) + { + return; + } + } + + ExpandSelectionOnPartialTokenSelect(selection, range); + } + + private async void RichEditBox_SelectionChanged(object sender, RoutedEventArgs e) + { + SelectionChanged?.Invoke(this, e); + + // During text composition changing (e.g. user typing with an IME), + // SelectionChanged event is fired multiple times with each keystroke. + // To reduce the number of suggestion requests, the request is made + // in TextCompositionChanged handler instead. + if (_textCompositionActive) + { + return; + } + + await RequestSuggestionsAsync(); + } + + private void RichEditBox_OnPointerPressed(object sender, PointerRoutedEventArgs e) + { + ShowSuggestionsPopup(false); + } + + private async void RichEditBox_ProcessKeyboardAccelerators(UIElement sender, ProcessKeyboardAcceleratorEventArgs args) + { + var itemsList = _suggestionsList.Items; + if (!_suggestionPopup.IsOpen || itemsList == null || itemsList.Count == 0) + { + return; + } + + var key = args.Key; + switch (key) + { + case VirtualKey.Up when itemsList.Count == 1: + case VirtualKey.Down when itemsList.Count == 1: + args.Handled = true; + UpdateSuggestionsListSelectedItem(1); + break; + + case VirtualKey.Up: + args.Handled = true; + _suggestionChoice = _suggestionChoice <= 0 ? itemsList.Count : _suggestionChoice - 1; + UpdateSuggestionsListSelectedItem(this._suggestionChoice); + break; + + case VirtualKey.Down: + args.Handled = true; + _suggestionChoice = _suggestionChoice >= itemsList.Count ? 0 : _suggestionChoice + 1; + UpdateSuggestionsListSelectedItem(this._suggestionChoice); + break; + + case VirtualKey.Enter when _suggestionsList.SelectedItem != null: + args.Handled = true; + await CommitSuggestionAsync(_suggestionsList.SelectedItem); + break; + + case VirtualKey.Escape: + args.Handled = true; + ShowSuggestionsPopup(false); + break; + } + } + + private async void RichEditBox_PreviewKeyDown(object sender, KeyRoutedEventArgs e) + { + if (e.Key == VirtualKey.Tab && _suggestionPopup.IsOpen && _suggestionsList.SelectedItem != null) + { + e.Handled = true; + await CommitSuggestionAsync(_suggestionsList.SelectedItem); + } + } + + private async void SuggestionsList_ItemClick(object sender, ItemClickEventArgs e) + { + var selectedItem = e.ClickedItem; + await CommitSuggestionAsync(selectedItem); + } + + private void RichEditBox_TextChanging(RichEditBox sender, RichEditBoxTextChangingEventArgs args) + { + if (_ignoreChange || !args.IsContentChanging) + { + return; + } + + _ignoreChange = true; + ValidateTokensInDocument(); + TextDocument.EndUndoGroup(); + TextDocument.BeginUndoGroup(); + _ignoreChange = false; + } + + private void RichEditBox_TextChanged(object sender, RoutedEventArgs e) + { + UpdateVisibleTokenList(); + TextChanged?.Invoke(this, e); + } + + private void RichEditBox_TextCompositionStarted(RichEditBox sender, TextCompositionStartedEventArgs args) + { + _textCompositionActive = true; + } + + private async void RichEditBox_TextCompositionChanged(RichEditBox sender, TextCompositionChangedEventArgs args) + { + var range = TextDocument.GetRange(args.StartIndex == 0 ? 0 : args.StartIndex - 1, args.StartIndex + args.Length); + await RequestSuggestionsAsync(range); + } + + private void RichEditBox_TextCompositionEnded(RichEditBox sender, TextCompositionEndedEventArgs args) + { + _textCompositionActive = false; + } + + private void RichEditBox_SizeChanged(object sender, SizeChangedEventArgs e) + { + this.UpdatePopupWidth(); + this.UpdatePopupOffset(); + } + + private async void RichEditBox_Paste(object sender, TextControlPasteEventArgs e) + { + Paste?.Invoke(this, e); + + if (e.Handled || TextDocument == null || ClipboardPasteFormat != RichEditClipboardFormat.PlainText) + { + return; + } + + e.Handled = true; + var dataPackageView = Clipboard.GetContent(); + if (dataPackageView.Contains(StandardDataFormats.Text)) + { + var text = await dataPackageView.GetTextAsync(); + TextDocument.Selection.SetText(TextSetOptions.Unhide, text); + TextDocument.Selection.Collapse(false); + } + } + + private void ExpandSelectionOnPartialTokenSelect(ITextSelection selection, ITextRange tokenRange) + { + switch (selection.Type) + { + case SelectionType.InsertionPoint: + // Snap selection to token on click + if (tokenRange.StartPosition < selection.StartPosition && selection.EndPosition < tokenRange.EndPosition) + { + selection.Expand(TextRangeUnit.Link); + InvokeTokenSelected(selection); + } + + break; + + case SelectionType.Normal: + // We do not want user to partially select a token since pasting to a partial token can break + // the token tracking system, which can result in unwanted character formatting issues. + if ((tokenRange.StartPosition <= selection.StartPosition && selection.EndPosition < tokenRange.EndPosition) || + (tokenRange.StartPosition < selection.StartPosition && selection.EndPosition <= tokenRange.EndPosition)) + { + // TODO: Figure out how to expand selection without breaking selection flow (with Shift select or pointer sweep select) + selection.Expand(TextRangeUnit.Link); + InvokeTokenSelected(selection); + } + + break; + } + } + + private void InvokeTokenSelected(ITextSelection selection) + { + if (TokenSelected == null || !TryGetTokenFromRange(selection, out var token) || token.RangeEnd != selection.EndPosition) + { + return; + } + + TokenSelected.Invoke(this, new RichSuggestTokenSelectedEventArgs + { + Token = token, + Range = selection.GetClone() + }); + } + + private void InvokeTokenPointerOver(PointerPoint pointer) + { + var pointerPosition = TransformToVisual(_richEditBox).TransformPoint(pointer.Position); + var padding = _richEditBox.Padding; + pointerPosition.X += HorizontalOffset - padding.Left; + pointerPosition.Y += VerticalOffset - padding.Top; + var range = TextDocument.GetRangeFromPoint(pointerPosition, PointOptions.ClientCoordinates); + var linkRange = range.GetClone(); + range.Expand(TextRangeUnit.Character); + range.GetRect(PointOptions.None, out var hitTestRect, out _); + hitTestRect.X -= hitTestRect.Width; + hitTestRect.Width *= 2; + if (hitTestRect.Contains(pointerPosition) && linkRange.Expand(TextRangeUnit.Link) > 0 && + TryGetTokenFromRange(linkRange, out var token)) + { + this.TokenPointerOver.Invoke(this, new RichSuggestTokenPointerOverEventArgs + { + Token = token, + Range = linkRange, + CurrentPoint = pointer + }); + } + } + + private async Task RequestSuggestionsAsync(ITextRange range = null) + { + string prefix; + string query; + var currentQuery = _currentQuery; + var queryFound = range == null + ? TryExtractQueryFromSelection(out prefix, out query, out range) + : TryExtractQueryFromRange(range, out prefix, out query); + + if (queryFound && prefix == currentQuery?.Prefix && query == currentQuery?.QueryText && + range.EndPosition == currentQuery?.Range.EndPosition && _suggestionPopup.IsOpen) + { + return; + } + + var previousTokenSource = currentQuery?.CancellationTokenSource; + if (!(previousTokenSource?.IsCancellationRequested ?? true)) + { + previousTokenSource.Cancel(); + } + + if (queryFound) + { + using var tokenSource = new CancellationTokenSource(); + _currentQuery = new RichSuggestQuery + { + Prefix = prefix, + QueryText = query, + Range = range, + CancellationTokenSource = tokenSource + }; + + var cancellationToken = tokenSource.Token; + var eventArgs = new SuggestionRequestedEventArgs { QueryText = query, Prefix = prefix }; + if (SuggestionRequested != null) + { + try + { + await SuggestionRequested.InvokeAsync(this, eventArgs, cancellationToken); + } + catch (OperationCanceledException) + { + return; + } + } + + if (!eventArgs.Cancel) + { + _suggestionChoice = 0; + ShowSuggestionsPopup(_suggestionsList?.Items?.Count > 0); + } + + tokenSource.Cancel(); + } + else + { + ShowSuggestionsPopup(false); + } + } + + internal async Task CommitSuggestionAsync(object selectedItem) + { + var currentQuery = _currentQuery; + var range = currentQuery?.Range.GetClone(); + var id = Guid.NewGuid(); + var prefix = currentQuery?.Prefix; + var query = currentQuery?.QueryText; + + // range has length of 0 at the end of the commit. + // Checking length == 0 to avoid committing twice. + if (prefix == null || query == null || range == null || range.Length == 0) + { + return; + } + + var textBefore = range.Text; + var format = CreateTokenFormat(range); + var eventArgs = new SuggestionChosenEventArgs + { + Id = id, + Prefix = prefix, + QueryText = query, + SelectedItem = selectedItem, + DisplayText = query, + Format = format + }; + + if (SuggestionChosen != null) + { + await SuggestionChosen.InvokeAsync(this, eventArgs); + } + + var text = eventArgs.DisplayText; + + // Since this operation is async, the document may have changed at this point. + // Double check if the range still has the expected query. + if (string.IsNullOrEmpty(text) || textBefore != range.Text || + !TryExtractQueryFromRange(range, out var testPrefix, out var testQuery) || + testPrefix != prefix || testQuery != query) + { + return; + } + + lock (_tokensLock) + { + var displayText = prefix + text; + + _ignoreChange = true; + var committed = TryCommitSuggestionIntoDocument(range, displayText, id, eventArgs.Format ?? format); + TextDocument.EndUndoGroup(); + TextDocument.BeginUndoGroup(); + _ignoreChange = false; + + if (committed) + { + var token = new RichSuggestToken(id, displayText) { Active = true, Item = selectedItem }; + token.UpdateTextRange(range); + _tokens.TryAdd(range.Link, token); + } + } + } + + private bool TryCommitSuggestionIntoDocument(ITextRange range, string displayText, Guid id, ITextCharacterFormat format, bool addTrailingSpace = true) + { + // We don't want to set text when the display text doesn't change since it may lead to unexpected caret move. + range.GetText(TextGetOptions.NoHidden, out var existingText); + if (existingText != displayText) + { + range.SetText(TextSetOptions.Unhide, displayText); + } + + var formatBefore = range.CharacterFormat.GetClone(); + range.CharacterFormat.SetClone(format); + PadRange(range, formatBefore); + range.Link = $"\"{id}\""; + + // In some rare case, setting Link can fail. Only observed when interacting with Undo/Redo feature. + if (range.Link != $"\"{id}\"") + { + range.Delete(TextRangeUnit.Story, -1); + return false; + } + + if (addTrailingSpace) + { + var clone = range.GetClone(); + clone.Collapse(false); + clone.SetText(TextSetOptions.Unhide, " "); + clone.Collapse(false); + TextDocument.Selection.SetRange(clone.EndPosition, clone.EndPosition); + } + + return true; + } + + private void ValidateTokensInDocument() + { + lock (_tokensLock) + { + foreach (var (_, token) in _tokens) + { + token.Active = false; + } + } + + ForEachLinkInDocument(TextDocument, ValidateTokenFromRange); + } + + private void ValidateTokenFromRange(ITextRange range) + { + if (range.Length == 0 || !TryGetTokenFromRange(range, out var token)) + { + return; + } + + // Check for duplicate tokens. This can happen if the user copies and pastes the token multiple times. + if (token.Active && token.RangeStart != range.StartPosition && token.RangeEnd != range.EndPosition) + { + lock (_tokensLock) + { + var guid = Guid.NewGuid(); + if (TryCommitSuggestionIntoDocument(range, token.DisplayText, guid, CreateTokenFormat(range), false)) + { + token = new RichSuggestToken(guid, token.DisplayText) { Active = true, Item = token.Item }; + token.UpdateTextRange(range); + _tokens.Add(range.Link, token); + } + + return; + } + } + + if (token.ToString() != range.Text) + { + range.Delete(TextRangeUnit.Story, 0); + token.Active = false; + return; + } + + token.UpdateTextRange(range); + token.Active = true; + } + + private void ConditionallyLoadElement(object property, string elementName) + { + if (property != null && GetTemplateChild(elementName) is UIElement presenter) + { + presenter.Visibility = Visibility.Visible; + } + } + + private void UpdateSuggestionsListSelectedItem(int choice) + { + var itemsList = _suggestionsList.Items; + if (itemsList == null) + { + return; + } + + _suggestionsList.SelectedItem = choice == 0 ? null : itemsList[choice - 1]; + _suggestionsList.ScrollIntoView(_suggestionsList.SelectedItem); + } + + private void ShowSuggestionsPopup(bool show) + { + if (_suggestionPopup == null) + { + return; + } + + this._suggestionPopup.IsOpen = show; + if (!show) + { + this._suggestionChoice = 0; + this._suggestionPopup.VerticalOffset = 0; + this._suggestionPopup.HorizontalOffset = 0; + this._suggestionsList.SelectedItem = null; + this._suggestionsList.ScrollIntoView(this._suggestionsList.Items?.FirstOrDefault()); + UpdateCornerRadii(); + } + } + + private void UpdatePopupWidth() + { + if (this._suggestionsContainer == null) + { + return; + } + + if (this.PopupPlacement == SuggestionPopupPlacementMode.Attached) + { + this._suggestionsContainer.MaxWidth = double.PositiveInfinity; + this._suggestionsContainer.Width = this._richEditBox.ActualWidth; + } + else + { + this._suggestionsContainer.MaxWidth = this._richEditBox.ActualWidth; + this._suggestionsContainer.Width = double.NaN; + } + } + + /// + /// Calculate whether to open the suggestion list up or down depends on how much screen space is available + /// + private void UpdatePopupOffset() + { + if (this._suggestionsContainer == null || this._suggestionPopup == null || this._richEditBox == null) + { + return; + } + + this._richEditBox.TextDocument.Selection.GetRect(PointOptions.None, out var selectionRect, out _); + Thickness padding = this._richEditBox.Padding; + selectionRect.X -= HorizontalOffset; + selectionRect.Y -= VerticalOffset; + + // Update horizontal offset + if (this.PopupPlacement == SuggestionPopupPlacementMode.Attached) + { + this._suggestionPopup.HorizontalOffset = 0; + } + else + { + double editBoxWidth = this._richEditBox.ActualWidth - padding.Left - padding.Right; + if (this._suggestionPopup.HorizontalOffset == 0 && editBoxWidth > 0) + { + var normalizedX = selectionRect.X / editBoxWidth; + this._suggestionPopup.HorizontalOffset = + (this._richEditBox.ActualWidth - this._suggestionsContainer.ActualWidth) * normalizedX; + } + } + + // Update vertical offset + double downOffset = this._richEditBox.ActualHeight; + double upOffset = -this._suggestionsContainer.ActualHeight; + if (this.PopupPlacement == SuggestionPopupPlacementMode.Floating) + { + downOffset = selectionRect.Bottom + padding.Top + padding.Bottom; + upOffset += selectionRect.Top; + } + + if (this._suggestionPopup.VerticalOffset == 0) + { + if (IsElementOnScreen(this._suggestionsContainer, offsetY: downOffset) && + (IsElementInsideWindow(this._suggestionsContainer, offsetY: downOffset) || + !IsElementInsideWindow(this._suggestionsContainer, offsetY: upOffset) || + !IsElementOnScreen(this._suggestionsContainer, offsetY: upOffset))) + { + this._suggestionPopup.VerticalOffset = downOffset; + this._popupOpenDown = true; + } + else + { + this._suggestionPopup.VerticalOffset = upOffset; + this._popupOpenDown = false; + } + + UpdateCornerRadii(); + } + else + { + this._suggestionPopup.VerticalOffset = this._popupOpenDown ? downOffset : upOffset; + } + } + + /// + /// Set corner radii so that inner corners, where suggestion list and text box connect, are square. + /// This only applies when is set to . + /// + /// https://docs.microsoft.com/en-us/windows/apps/design/style/rounded-corner#when-not-to-round + private void UpdateCornerRadii() + { + if (this._richEditBox == null || this._suggestionsContainer == null || + !ApiInformation.IsApiContractPresent("Windows.Foundation.UniversalApiContract", 7)) + { + return; + } + + this._richEditBox.CornerRadius = CornerRadius; + this._suggestionsContainer.CornerRadius = PopupCornerRadius; + + if (this._suggestionPopup.IsOpen && PopupPlacement == SuggestionPopupPlacementMode.Attached) + { + if (this._popupOpenDown) + { + var cornerRadius = new CornerRadius(CornerRadius.TopLeft, CornerRadius.TopRight, 0, 0); + this._richEditBox.CornerRadius = cornerRadius; + var popupCornerRadius = + new CornerRadius(0, 0, PopupCornerRadius.BottomRight, PopupCornerRadius.BottomLeft); + this._suggestionsContainer.CornerRadius = popupCornerRadius; + } + else + { + var cornerRadius = new CornerRadius(0, 0, CornerRadius.BottomRight, CornerRadius.BottomLeft); + this._richEditBox.CornerRadius = cornerRadius; + var popupCornerRadius = + new CornerRadius(PopupCornerRadius.TopLeft, PopupCornerRadius.TopRight, 0, 0); + this._suggestionsContainer.CornerRadius = popupCornerRadius; + } + } + } + + private bool TryExtractQueryFromSelection(out string prefix, out string query, out ITextRange range) + { + prefix = string.Empty; + query = string.Empty; + range = null; + if (TextDocument.Selection.Type != SelectionType.InsertionPoint) + { + return false; + } + + // Check if selection is on existing link (suggestion) + var expandCount = TextDocument.Selection.GetClone().Expand(TextRangeUnit.Link); + if (expandCount != 0) + { + return false; + } + + var selection = TextDocument.Selection.GetClone(); + selection.MoveStart(TextRangeUnit.Word, -1); + if (selection.Length == 0) + { + return false; + } + + range = selection; + if (TryExtractQueryFromRange(selection, out prefix, out query)) + { + return true; + } + + selection.MoveStart(TextRangeUnit.Word, -1); + if (TryExtractQueryFromRange(selection, out prefix, out query)) + { + return true; + } + + range = null; + return false; + } + + private bool TryExtractQueryFromRange(ITextRange range, out string prefix, out string query) + { + prefix = string.Empty; + query = string.Empty; + range.GetText(TextGetOptions.NoHidden, out var possibleQuery); + if (possibleQuery.Length > 0 && Prefixes.Contains(possibleQuery[0]) && + !possibleQuery.Any(char.IsWhiteSpace) && string.IsNullOrEmpty(range.Link)) + { + if (possibleQuery.Length == 1) + { + prefix = possibleQuery; + return true; + } + + prefix = possibleQuery[0].ToString(); + query = possibleQuery.Substring(1); + return true; + } + + return false; + } + + private ITextCharacterFormat CreateTokenFormat(ITextRange range) + { + var format = range.CharacterFormat.GetClone(); + if (this.TokenBackground != null) + { + format.BackgroundColor = this.TokenBackground.Color; + } + + if (this.TokenForeground != null) + { + format.ForegroundColor = this.TokenForeground.Color; + } + + return format; + } + + private void UpdateVisibleTokenList() + { + lock (_tokensLock) + { + var toBeRemoved = _visibleTokens.Where(x => !x.Active || !_tokens.ContainsKey($"\"{x.Id}\"")).ToArray(); + + foreach (var elem in toBeRemoved) + { + _visibleTokens.Remove(elem); + } + + var toBeAdded = _tokens.Where(pair => pair.Value.Active && !_visibleTokens.Contains(pair.Value)) + .Select(pair => pair.Value).ToArray(); + + foreach (var elem in toBeAdded) + { + _visibleTokens.Add(elem); + } + } + } + } +} diff --git a/Microsoft.Toolkit.Uwp.UI.Controls.Input/RichSuggestBox/RichSuggestBox.xaml b/Microsoft.Toolkit.Uwp.UI.Controls.Input/RichSuggestBox/RichSuggestBox.xaml new file mode 100644 index 000000000..aeeb2e851 --- /dev/null +++ b/Microsoft.Toolkit.Uwp.UI.Controls.Input/RichSuggestBox/RichSuggestBox.xaml @@ -0,0 +1,122 @@ + + + + + diff --git a/Microsoft.Toolkit.Uwp.UI.Controls.Input/RichSuggestBox/RichSuggestQuery.cs b/Microsoft.Toolkit.Uwp.UI.Controls.Input/RichSuggestBox/RichSuggestQuery.cs new file mode 100644 index 000000000..892fd2753 --- /dev/null +++ b/Microsoft.Toolkit.Uwp.UI.Controls.Input/RichSuggestBox/RichSuggestQuery.cs @@ -0,0 +1,23 @@ +// 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.Threading; +using Windows.UI.Text; + +namespace Microsoft.Toolkit.Uwp.UI.Controls +{ + /// + /// A structure for to keep track of the current query internally. + /// + internal class RichSuggestQuery + { + public string Prefix { get; set; } + + public string QueryText { get; set; } + + public ITextRange Range { get; set; } + + public CancellationTokenSource CancellationTokenSource { get; set; } + } +} diff --git a/Microsoft.Toolkit.Uwp.UI.Controls.Input/RichSuggestBox/RichSuggestToken.cs b/Microsoft.Toolkit.Uwp.UI.Controls.Input/RichSuggestBox/RichSuggestToken.cs new file mode 100644 index 000000000..1cd40a22d --- /dev/null +++ b/Microsoft.Toolkit.Uwp.UI.Controls.Input/RichSuggestBox/RichSuggestToken.cs @@ -0,0 +1,95 @@ +// 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.ComponentModel; +using Windows.UI.Text; + +namespace Microsoft.Toolkit.Uwp.UI.Controls +{ + /// + /// RichSuggestToken describes a suggestion token in the document. + /// + public class RichSuggestToken : INotifyPropertyChanged + { + /// + public event PropertyChangedEventHandler PropertyChanged; + + /// + /// Gets the token ID. + /// + public Guid Id { get; } + + /// + /// Gets the text displayed in the document. + /// + public string DisplayText { get; } + + /// + /// Gets or sets the suggested item associated with this token. + /// + public object Item { get; set; } + + /// + /// Gets the start position of the text range. + /// + public int RangeStart { get; private set; } + + /// + /// Gets the end position of the text range. + /// + public int RangeEnd { get; private set; } + + /// + /// Gets the start position of the token in number of characters. + /// + public int Position => _range?.GetIndex(TextRangeUnit.Character) - 1 ?? 0; + + internal bool Active { get; set; } + + private ITextRange _range; + + /// + /// Initializes a new instance of the class. + /// + /// Token ID + /// Text in the document + public RichSuggestToken(Guid id, string displayText) + { + Id = id; + DisplayText = displayText; + } + + internal void UpdateTextRange(ITextRange range) + { + bool rangeStartChanged = RangeStart != range.StartPosition; + bool rangeEndChanged = RangeEnd != range.EndPosition; + bool positionChanged = _range == null || rangeStartChanged; + _range = range.GetClone(); + RangeStart = _range.StartPosition; + RangeEnd = _range.EndPosition; + + if (rangeStartChanged) + { + PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(RangeStart))); + } + + if (rangeEndChanged) + { + PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(RangeEnd))); + } + + if (positionChanged) + { + PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Position))); + } + } + + /// + public override string ToString() + { + return $"HYPERLINK \"{Id}\"\u200B{DisplayText}\u200B"; + } + } +} diff --git a/Microsoft.Toolkit.Uwp.UI.Controls.Input/RichSuggestBox/RichSuggestTokenPointerOverEventArgs.cs b/Microsoft.Toolkit.Uwp.UI.Controls.Input/RichSuggestBox/RichSuggestTokenPointerOverEventArgs.cs new file mode 100644 index 000000000..d784abe83 --- /dev/null +++ b/Microsoft.Toolkit.Uwp.UI.Controls.Input/RichSuggestBox/RichSuggestTokenPointerOverEventArgs.cs @@ -0,0 +1,31 @@ +// 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 Windows.UI.Input; +using Windows.UI.Text; + +namespace Microsoft.Toolkit.Uwp.UI.Controls +{ + /// + /// Provides data for event. + /// + public class RichSuggestTokenPointerOverEventArgs : EventArgs + { + /// + /// Gets or sets the selected token. + /// + public RichSuggestToken Token { get; set; } + + /// + /// Gets or sets the range associated with the token. + /// + public ITextRange Range { get; set; } + + /// + /// Gets or sets a PointerPoint object relative to the control. + /// + public PointerPoint CurrentPoint { get; set; } + } +} diff --git a/Microsoft.Toolkit.Uwp.UI.Controls.Input/RichSuggestBox/RichSuggestTokenSelectedEventArgs.cs b/Microsoft.Toolkit.Uwp.UI.Controls.Input/RichSuggestBox/RichSuggestTokenSelectedEventArgs.cs new file mode 100644 index 000000000..9711eb617 --- /dev/null +++ b/Microsoft.Toolkit.Uwp.UI.Controls.Input/RichSuggestBox/RichSuggestTokenSelectedEventArgs.cs @@ -0,0 +1,25 @@ +// 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 Windows.UI.Text; + +namespace Microsoft.Toolkit.Uwp.UI.Controls +{ + /// + /// Provides data for event. + /// + public class RichSuggestTokenSelectedEventArgs : EventArgs + { + /// + /// Gets or sets the selected token. + /// + public RichSuggestToken Token { get; set; } + + /// + /// Gets or sets the range associated with the token. + /// + public ITextRange Range { get; set; } + } +} diff --git a/Microsoft.Toolkit.Uwp.UI.Controls.Input/RichSuggestBox/SuggestionChosenEventArgs.cs b/Microsoft.Toolkit.Uwp.UI.Controls.Input/RichSuggestBox/SuggestionChosenEventArgs.cs new file mode 100644 index 000000000..b465e3ed5 --- /dev/null +++ b/Microsoft.Toolkit.Uwp.UI.Controls.Input/RichSuggestBox/SuggestionChosenEventArgs.cs @@ -0,0 +1,46 @@ +// 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 Microsoft.Toolkit.Deferred; +using Windows.UI.Text; + +namespace Microsoft.Toolkit.Uwp.UI.Controls +{ + /// + /// Provides data for the event. + /// + public class SuggestionChosenEventArgs : DeferredEventArgs + { + /// + /// Gets the query used for this token. + /// + public string QueryText { get; internal set; } + + /// + /// Gets the prefix character used for this token. + /// + public string Prefix { get; internal set; } + + /// + /// Gets or sets the display text. + /// + public string DisplayText { get; set; } + + /// + /// Gets the suggestion item associated with this token. + /// + public object SelectedItem { get; internal set; } + + /// + /// Gets token ID. + /// + public Guid Id { get; internal set; } + + /// + /// Gets or sets the object used to format the display text for this token. + /// + public ITextCharacterFormat Format { get; set; } + } +} diff --git a/Microsoft.Toolkit.Uwp.UI.Controls.Input/RichSuggestBox/SuggestionPopupPlacementMode.cs b/Microsoft.Toolkit.Uwp.UI.Controls.Input/RichSuggestBox/SuggestionPopupPlacementMode.cs new file mode 100644 index 000000000..b446b45b9 --- /dev/null +++ b/Microsoft.Toolkit.Uwp.UI.Controls.Input/RichSuggestBox/SuggestionPopupPlacementMode.cs @@ -0,0 +1,28 @@ +// 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 Windows.UI.Xaml.Controls; + +namespace Microsoft.Toolkit.Uwp.UI.Controls +{ + /// + /// Placement modes for the suggestion popup in . + /// + public enum SuggestionPopupPlacementMode + { + /// + /// Suggestion popup floats above or below the typing caret. + /// + Floating, + + /// + /// Suggestion popup is attached to either the top edge or the bottom edge of the text box. + /// + /// + /// In this mode, popup width will be text box's width and the interior corners that connect the text box and the popup are square. + /// This is the same behavior as in . + /// + Attached + } +} diff --git a/Microsoft.Toolkit.Uwp.UI.Controls.Input/RichSuggestBox/SuggestionRequestedEventArgs.cs b/Microsoft.Toolkit.Uwp.UI.Controls.Input/RichSuggestBox/SuggestionRequestedEventArgs.cs new file mode 100644 index 000000000..21c8655bb --- /dev/null +++ b/Microsoft.Toolkit.Uwp.UI.Controls.Input/RichSuggestBox/SuggestionRequestedEventArgs.cs @@ -0,0 +1,24 @@ +// 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 Microsoft.Toolkit.Deferred; + +namespace Microsoft.Toolkit.Uwp.UI.Controls +{ + /// + /// Provide data for event. + /// + public class SuggestionRequestedEventArgs : DeferredCancelEventArgs + { + /// + /// Gets or sets the prefix character used for the query. + /// + public string Prefix { get; set; } + + /// + /// Gets or sets the query for suggestions. + /// + public string QueryText { get; set; } + } +} diff --git a/Microsoft.Toolkit.Uwp.UI.Controls.Input/Themes/Generic.xaml b/Microsoft.Toolkit.Uwp.UI.Controls.Input/Themes/Generic.xaml index 85a16de6c..761bf93fb 100644 --- a/Microsoft.Toolkit.Uwp.UI.Controls.Input/Themes/Generic.xaml +++ b/Microsoft.Toolkit.Uwp.UI.Controls.Input/Themes/Generic.xaml @@ -8,5 +8,6 @@ + \ No newline at end of file diff --git a/Microsoft.Toolkit.Uwp.UI.Controls.Input/TokenizingTextBox/TokenizingTextBox.Properties.cs b/Microsoft.Toolkit.Uwp.UI.Controls.Input/TokenizingTextBox/TokenizingTextBox.Properties.cs index d6099b859..1a5a1e36b 100644 --- a/Microsoft.Toolkit.Uwp.UI.Controls.Input/TokenizingTextBox/TokenizingTextBox.Properties.cs +++ b/Microsoft.Toolkit.Uwp.UI.Controls.Input/TokenizingTextBox/TokenizingTextBox.Properties.cs @@ -157,6 +157,37 @@ namespace Microsoft.Toolkit.Uwp.UI.Controls typeof(TokenizingTextBox), new PropertyMetadata(false)); + /// + /// Identifies the property. + /// + public static readonly DependencyProperty MaximumTokensProperty = DependencyProperty.Register( + nameof(MaximumTokens), + typeof(int), + typeof(TokenizingTextBox), + new PropertyMetadata(null, OnMaximumTokensChanged)); + + private static void OnMaximumTokensChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) + { + if (d is TokenizingTextBox ttb && ttb.ReadLocalValue(MaximumTokensProperty) != DependencyProperty.UnsetValue && e.NewValue is int newMaxTokens) + { + var tokenCount = ttb._innerItemsSource.ItemsSource.Count; + if (tokenCount > 0 && tokenCount > newMaxTokens) + { + int tokensToRemove = tokenCount - Math.Max(newMaxTokens, 0); + + // Start at the end, remove any extra tokens. + for (var i = tokenCount; i > tokenCount - tokensToRemove; --i) + { + var token = ttb._innerItemsSource.ItemsSource[i - 1]; + + // Force remove the items. No warning and no option to cancel. + ttb._innerItemsSource.Remove(token); + ttb.TokenItemRemoved?.Invoke(ttb, token); + } + } + } + } + /// /// Gets or sets the Style for the contained AutoSuggestBox template part. /// @@ -303,5 +334,14 @@ namespace Microsoft.Toolkit.Uwp.UI.Controls return PrepareSelectionForClipboard(); } } + + /// + /// Gets or sets the maximum number of token results allowed at a time. + /// + public int MaximumTokens + { + get => (int)GetValue(MaximumTokensProperty); + set => SetValue(MaximumTokensProperty, value); + } } -} \ No newline at end of file +} diff --git a/Microsoft.Toolkit.Uwp.UI.Controls.Input/TokenizingTextBox/TokenizingTextBox.cs b/Microsoft.Toolkit.Uwp.UI.Controls.Input/TokenizingTextBox/TokenizingTextBox.cs index 89474a89f..3ddc77835 100644 --- a/Microsoft.Toolkit.Uwp.UI.Controls.Input/TokenizingTextBox/TokenizingTextBox.cs +++ b/Microsoft.Toolkit.Uwp.UI.Controls.Input/TokenizingTextBox/TokenizingTextBox.cs @@ -2,15 +2,16 @@ // 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.ObjectModel; using System.Linq; using System.Threading.Tasks; using Microsoft.Toolkit.Uwp.Deferred; +using Microsoft.Toolkit.Uwp.UI.Automation.Peers; using Microsoft.Toolkit.Uwp.UI.Helpers; using Windows.System; using Windows.UI.Core; using Windows.UI.Xaml; +using Windows.UI.Xaml.Automation.Peers; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Input; @@ -77,6 +78,17 @@ namespace Microsoft.Toolkit.Uwp.UI.Controls if (ItemsSource != null && ItemsSource.GetType() != typeof(InterspersedObservableCollection)) { _innerItemsSource = new InterspersedObservableCollection(ItemsSource); + + if (ReadLocalValue(MaximumTokensProperty) != DependencyProperty.UnsetValue && _innerItemsSource.ItemsSource.Count >= MaximumTokens) + { + // Reduce down to below the max as necessary. + var endCount = MaximumTokens > 0 ? MaximumTokens : 0; + for (var i = _innerItemsSource.ItemsSource.Count - 1; i >= endCount; --i) + { + _innerItemsSource.Remove(_innerItemsSource[i]); + } + } + _currentTextEdit = _lastTextEdit = new PretokenStringContainer(true); _innerItemsSource.Insert(_innerItemsSource.Count, _currentTextEdit); ItemsSource = _innerItemsSource; @@ -278,18 +290,16 @@ namespace Microsoft.Toolkit.Uwp.UI.Controls } else { - // TODO: It looks like we're setting selection and focus together on items? Not sure if that's what we want... - // If that's the case, don't think this code will ever be called? - - //// TODO: Behavior question: if no items selected (just focus) does it just go to our last active textbox? - //// Community voted that typing in the end box made sense - + // If no items are selected, send input to the last active string container. + // This code is only fires during an edgecase where an item is in the process of being deleted and the user inputs a character before the focus has been redirected to a string container. if (_innerItemsSource[_innerItemsSource.Count - 1] is ITokenStringContainer textToken) { var last = ContainerFromIndex(Items.Count - 1) as TokenizingTextBoxItem; // Should be our last text box - var position = last._autoSuggestTextBox.SelectionStart; - textToken.Text = last._autoSuggestTextBox.Text.Substring(0, position) + args.Character + - last._autoSuggestTextBox.Text.Substring(position); + var text = last._autoSuggestTextBox.Text; + var selectionStart = last._autoSuggestTextBox.SelectionStart; + var position = selectionStart > text.Length ? text.Length : selectionStart; + textToken.Text = text.Substring(0, position) + args.Character + + text.Substring(position); last._autoSuggestTextBox.SelectionStart = position + 1; // Set position to after our new character inserted @@ -432,6 +442,12 @@ namespace Microsoft.Toolkit.Uwp.UI.Controls internal async Task AddTokenAsync(object data, bool? atEnd = null) { + if (ReadLocalValue(MaximumTokensProperty) != DependencyProperty.UnsetValue && (MaximumTokens <= 0 || MaximumTokens <= _innerItemsSource.ItemsSource.Count)) + { + // No tokens for you + return; + } + if (data is string str && TokenItemAdding != null) { var tiaea = new TokenItemAddingEventArgs(str); @@ -486,6 +502,15 @@ namespace Microsoft.Toolkit.Uwp.UI.Controls Text = edit.Text; // Update our text property. } + /// + /// Creates AutomationPeer () + /// + /// An automation peer for this . + protected override AutomationPeer OnCreateAutomationPeer() + { + return new TokenizingTextBoxAutomationPeer(this); + } + /// /// Remove the specified token from the list. /// diff --git a/Microsoft.Toolkit.Uwp.UI.Controls.Input/TokenizingTextBox/TokenizingTextBoxAutomationPeer.cs b/Microsoft.Toolkit.Uwp.UI.Controls.Input/TokenizingTextBox/TokenizingTextBoxAutomationPeer.cs new file mode 100644 index 000000000..5f049a801 --- /dev/null +++ b/Microsoft.Toolkit.Uwp.UI.Controls.Input/TokenizingTextBox/TokenizingTextBoxAutomationPeer.cs @@ -0,0 +1,131 @@ +ο»Ώ// 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.Collections.Generic; +using Microsoft.Toolkit.Uwp.UI.Controls; +using Windows.UI.Xaml.Automation; +using Windows.UI.Xaml.Automation.Peers; +using Windows.UI.Xaml.Automation.Provider; +using Windows.UI.Xaml.Controls; + +namespace Microsoft.Toolkit.Uwp.UI.Automation.Peers +{ + /// + /// Defines a framework element automation peer for the control. + /// + public class TokenizingTextBoxAutomationPeer : ListViewBaseAutomationPeer, IValueProvider + { + /// + /// Initializes a new instance of the class. + /// + /// + /// The that is associated with this . + /// + public TokenizingTextBoxAutomationPeer(TokenizingTextBox owner) + : base(owner) + { + } + + /// Gets a value indicating whether the value of a control is read-only. + /// **true** if the value is read-only; **false** if it can be modified. + public bool IsReadOnly => !this.OwningTokenizingTextBox.IsEnabled; + + /// Gets the value of the control. + /// The value of the control. + public string Value => this.OwningTokenizingTextBox.Text; + + private TokenizingTextBox OwningTokenizingTextBox + { + get + { + return Owner as TokenizingTextBox; + } + } + + /// Sets the value of a control. + /// The value to set. The provider is responsible for converting the value to the appropriate data type. + /// Thrown if the control is in a read-only state. + public void SetValue(string value) + { + if (IsReadOnly) + { + throw new ElementNotEnabledException($"Could not set the value of the {nameof(TokenizingTextBox)} "); + } + + this.OwningTokenizingTextBox.Text = value; + } + + /// + /// Called by GetClassName that gets a human readable name that, in addition to AutomationControlType, + /// differentiates the control represented by this AutomationPeer. + /// + /// The string that contains the name. + protected override string GetClassNameCore() + { + return Owner.GetType().Name; + } + + /// + /// Called by GetName. + /// + /// + /// Returns the first of these that is not null or empty: + /// - Value returned by the base implementation + /// - Name of the owning TokenizingTextBox + /// - TokenizingTextBox class name + /// + protected override string GetNameCore() + { + string name = this.OwningTokenizingTextBox.Name; + if (!string.IsNullOrWhiteSpace(name)) + { + return name; + } + + name = AutomationProperties.GetName(this.OwningTokenizingTextBox); + return !string.IsNullOrWhiteSpace(name) ? name : base.GetNameCore(); + } + + /// + /// Gets the control pattern that is associated with the specified Windows.UI.Xaml.Automation.Peers.PatternInterface. + /// + /// A value from the Windows.UI.Xaml.Automation.Peers.PatternInterface enumeration. + /// The object that supports the specified pattern, or null if unsupported. + protected override object GetPatternCore(PatternInterface patternInterface) + { + return patternInterface switch + { + PatternInterface.Value => this, + _ => base.GetPatternCore(patternInterface) + }; + } + + /// + /// Gets the collection of elements that are represented in the UI Automation tree as immediate + /// child elements of the automation peer. + /// + /// The children elements. + protected override IList GetChildrenCore() + { + TokenizingTextBox owner = this.OwningTokenizingTextBox; + + ItemCollection items = owner.Items; + if (items.Count <= 0) + { + return null; + } + + List peers = new List(items.Count); + for (int i = 0; i < items.Count; i++) + { + if (owner.ContainerFromIndex(i) is TokenizingTextBoxItem element) + { + peers.Add(FromElement(element) ?? CreatePeerForElement(element)); + } + } + + return peers; + } + } +} diff --git a/Microsoft.Toolkit.Uwp.UI.Controls.Input/TokenizingTextBox/TokenizingTextBoxItem.AutoSuggestBox.cs b/Microsoft.Toolkit.Uwp.UI.Controls.Input/TokenizingTextBox/TokenizingTextBoxItem.AutoSuggestBox.cs index ebd64de25..5a95f5b4b 100644 --- a/Microsoft.Toolkit.Uwp.UI.Controls.Input/TokenizingTextBox/TokenizingTextBoxItem.AutoSuggestBox.cs +++ b/Microsoft.Toolkit.Uwp.UI.Controls.Input/TokenizingTextBox/TokenizingTextBoxItem.AutoSuggestBox.cs @@ -4,10 +4,12 @@ using Windows.Foundation; using Windows.System; +using Windows.UI; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Data; using Windows.UI.Xaml.Input; +using Windows.UI.Xaml.Media; namespace Microsoft.Toolkit.Uwp.UI.Controls { @@ -16,9 +18,11 @@ namespace Microsoft.Toolkit.Uwp.UI.Controls /// [System.Diagnostics.CodeAnalysis.SuppressMessage("StyleCop.CSharp.ReadabilityRules", "SA1124:Do not use regions", Justification = "Organization")] [TemplatePart(Name = PART_AutoSuggestBox, Type = typeof(AutoSuggestBox))] //// String case + [TemplatePart(Name = PART_TokensCounter, Type = typeof(TextBlock))] public partial class TokenizingTextBoxItem { private const string PART_AutoSuggestBox = "PART_AutoSuggestBox"; + private const string PART_TokensCounter = "PART_TokensCounter"; private AutoSuggestBox _autoSuggestBox; @@ -231,6 +235,8 @@ namespace Microsoft.Toolkit.Uwp.UI.Controls #region Inner TextBox private void OnASBLoaded(object sender, RoutedEventArgs e) { + UpdateTokensCounter(this); + // Local function for Selection changed void AutoSuggestTextBox_SelectionChanged(object box, RoutedEventArgs args) { @@ -329,6 +335,44 @@ namespace Microsoft.Toolkit.Uwp.UI.Controls Owner.SelectAllTokensAndText(); } } + + private void UpdateTokensCounter(TokenizingTextBoxItem ttbi) + { + var maxTokensCounter = (TextBlock)_autoSuggestBox?.FindDescendant(PART_TokensCounter); + if (maxTokensCounter == null) + { + return; + } + + void OnTokenCountChanged(TokenizingTextBox ttb, object value = null) + { + var itemsSource = ttb.ItemsSource as InterspersedObservableCollection; + var currentTokens = itemsSource.ItemsSource.Count; + var maxTokens = ttb.MaximumTokens; + + maxTokensCounter.Text = $"{currentTokens}/{maxTokens}"; + maxTokensCounter.Visibility = Visibility.Visible; + + maxTokensCounter.Foreground = (currentTokens >= maxTokens) + ? new SolidColorBrush(Colors.Red) + : _autoSuggestBox.Foreground; + } + + ttbi.Owner.TokenItemAdded -= OnTokenCountChanged; + ttbi.Owner.TokenItemRemoved -= OnTokenCountChanged; + + if (Content is ITokenStringContainer str && str.IsLast && ttbi?.Owner != null && ttbi.Owner.ReadLocalValue(TokenizingTextBox.MaximumTokensProperty) != DependencyProperty.UnsetValue) + { + ttbi.Owner.TokenItemAdded += OnTokenCountChanged; + ttbi.Owner.TokenItemRemoved += OnTokenCountChanged; + OnTokenCountChanged(ttbi.Owner); + } + else + { + maxTokensCounter.Visibility = Visibility.Collapsed; + maxTokensCounter.Text = string.Empty; + } + } #endregion } } \ No newline at end of file diff --git a/Microsoft.Toolkit.Uwp.UI.Controls.Input/TokenizingTextBox/TokenizingTextBoxItem.AutoSuggestBox.xaml b/Microsoft.Toolkit.Uwp.UI.Controls.Input/TokenizingTextBox/TokenizingTextBoxItem.AutoSuggestBox.xaml index e0b972549..26dd6f698 100644 --- a/Microsoft.Toolkit.Uwp.UI.Controls.Input/TokenizingTextBox/TokenizingTextBoxItem.AutoSuggestBox.xaml +++ b/Microsoft.Toolkit.Uwp.UI.Controls.Input/TokenizingTextBox/TokenizingTextBoxItem.AutoSuggestBox.xaml @@ -137,6 +137,7 @@ + @@ -176,7 +177,7 @@ ZoomMode="Disabled" /> + + +