Skip to content

Commit

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

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


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

Adds a control to display metadata separated by bullets like done in Groove Music or the Store. 
The metadata list can contain actionable links.

**Groove**
![groove](https://user-images.githubusercontent.com/20152272/105519998-66aa6100-5cda-11eb-891a-4598ad5becf4.png)

**Store**
![store](https://user-images.githubusercontent.com/20152272/105520090-817cd580-5cda-11eb-8bf1-36afbc2fe435.png)

## PR Type
What kind of change does this PR introduce?
- Feature

## What is the new behavior?
I've added `MetadataControl`. It aggregates strings and commands separated by bullets ("•" / U+2022) in a `TextBlock`.
The commands are represented using `Hyperlink` items. 
It receives the items to display as `MetadataUnit`s through its `MetadataControl.MetadataUnits` property.

## PR Checklist

Please check if your PR fulfills the following requirements:

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

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


## Other information
![image](https://user-images.githubusercontent.com/20152272/105520377-f0f2c500-5cda-11eb-9116-8447969d1cdd.png)
  • Loading branch information
msftbot[bot] authored Jun 16, 2021
2 parents 6c63d55 + e6d3c3b commit ff21a8a
Show file tree
Hide file tree
Showing 10 changed files with 396 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -281,6 +281,7 @@
<Content Include="SamplePages\TabbedCommandBar\TabbedCommandBar.png" />
<Content Include="SamplePages\Animations\Effects\FadeBehavior.png" />
<Content Include="SamplePages\ColorPicker\ColorPicker.png" />
<Content Include="SamplePages\MetadataControl\MetadataControl.png" />
<Content Include="SamplePages\TilesBrush\TilesBrush.png" />
<Content Include="SamplePages\Eyedropper\Eyedropper.png" />
<Content Include="SamplePages\OnDevice\OnDevice.png" />
Expand Down Expand Up @@ -506,6 +507,9 @@
<Compile Include="SamplePages\FocusBehavior\FocusBehaviorPage.xaml.cs">
<DependentUpon>FocusBehaviorPage.xaml</DependentUpon>
</Compile>
<Compile Include="SamplePages\MetadataControl\MetadataControlPage.xaml.cs">
<DependentUpon>MetadataControlPage.xaml</DependentUpon>
</Compile>
<Compile Include="SamplePages\TilesBrush\TilesBrushPage.xaml.cs">
<DependentUpon>TilesBrushPage.xaml</DependentUpon>
</Compile>
Expand Down Expand Up @@ -966,6 +970,13 @@
<Content Include="SamplePages\TabbedCommandBar\TabbedCommandBar.bind">
<SubType>Designer</SubType>
</Content>
<Content Include="SamplePages\MetadataControl\MetadataControlCode.bind">
<SubType>Designer</SubType>
</Content>
<Page Include="SamplePages\MetadataControl\MetadataControlPage.xaml">
<SubType>Designer</SubType>
<Generator>MSBuild:Compile</Generator>
</Page>
<Page Include="SamplePages\CanvasPathGeometry\CanvasPathGeometryPage.xaml">
<SubType>Designer</SubType>
<Generator>MSBuild:Compile</Generator>
Expand Down
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<Page
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:controls="using:Microsoft.Toolkit.Uwp.UI.Controls"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">

<StackPanel Padding="12">
<controls:MetadataControl
x:Name="metadataControl"
Separator="@[Separator:String: • ]"
AccessibleSeparator="@[AccessibleSeparator:String:, ]"/>
</StackPanel>
</Page>
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<Page x:Class="Microsoft.Toolkit.Uwp.SampleApp.SamplePages.MetadataControlPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:controls="using:Microsoft.Toolkit.Uwp.UI.Controls"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">

<StackPanel Padding="12">
<controls:MetadataControl x:Name="metadataControl" />
</StackPanel>
</Page>
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
// 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.ObjectModel;
using Microsoft.Toolkit.Uwp.SampleApp.Common;
using Microsoft.Toolkit.Uwp.UI;
using Microsoft.Toolkit.Uwp.UI.Controls;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;

namespace Microsoft.Toolkit.Uwp.SampleApp.SamplePages
{
/// <summary>
/// A page that shows how to use the MetadataControl
/// </summary>
public sealed partial class MetadataControlPage : Page, IXamlRenderListener
{
private static readonly string[] Labels = "Lorem ipsum dolor sit amet consectetur adipiscing elit".Split(" ");

private readonly Random _random;
private readonly ObservableCollection<MetadataItem> _units;
private readonly DelegateCommand<object> _command;
private MetadataControl _metadataControl;

public MetadataControlPage()
{
_random = new Random();
_units = new ObservableCollection<MetadataItem>();
_command = new DelegateCommand<object>(OnExecuteCommand);
InitializeComponent();
Setup();
}

public void OnXamlRendered(FrameworkElement control)
{
_metadataControl = control.FindChild("metadataControl") as MetadataControl;
if (_metadataControl != null)
{
_metadataControl.Items = _units;
}
}

private void Setup()
{
SampleController.Current.RegisterNewCommand("Add label", (sender, args) =>
{
_units.Add(new MetadataItem { Label = GetRandomLabel() });
});

SampleController.Current.RegisterNewCommand("Add command", (sender, args) =>
{
var label = GetRandomLabel();
_units.Add(new MetadataItem
{
Label = label,
Command = _command,
CommandParameter = label,
});
});

SampleController.Current.RegisterNewCommand("Clear", (sender, args) =>
{
_units.Clear();
});
}

private string GetRandomLabel() => Labels[_random.Next(Labels.Length)];

private async void OnExecuteCommand(object obj)
{
var dialog = new ContentDialog
{
Title = "Command invoked",
Content = $"Command parameter: {obj}",
CloseButtonText = "OK"
};

await dialog.ShowAsync();
}
}
}
10 changes: 10 additions & 0 deletions Microsoft.Toolkit.Uwp.SampleApp/SamplePages/samples.json
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,16 @@
"Icon": "/SamplePages/RadialProgressBar/RadialProgressBar.png",
"DocumentationUrl": "https://raw.githubusercontent.com/MicrosoftDocs/WindowsCommunityToolkitDocs/master/docs/controls/RadialProgressBar.md"
},
{
"Name": "MetadataControl",
"Type": "MetadataControlPage",
"Subcategory": "Status and Info",
"About": "The control displays a list of metadata separated by bullets. The entries can either be strings or commands.",
"CodeUrl": "https://github.com/windows-toolkit/WindowsCommunityToolkit/tree/master/Microsoft.Toolkit.Uwp.UI.Controls/MetadataControl",
"XamlCodeFile": "MetadataControlCode.bind",
"Icon": "/SamplePages/MetadataControl/MetadataControl.png",
"DocumentationUrl": "https://raw.githubusercontent.com/MicrosoftDocs/WindowsCommunityToolkitDocs/master/docs/controls/MetadataControl.md"
},
{
"Name": "RotatorTile",
"Type": "RotatorTilePage",
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,212 @@
// 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 System.Collections.Specialized;
using System.Text;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Automation;
using Windows.UI.Xaml.Automation.Peers;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Documents;

namespace Microsoft.Toolkit.Uwp.UI.Controls
{
/// <summary>
/// Display <see cref="MetadataItem"/>s separated by bullets.
/// </summary>
[TemplatePart(Name = TextContainerPart, Type = typeof(TextBlock))]
public sealed class MetadataControl : Control
{
/// <summary>
/// The DP to store the <see cref="Separator"/> property value.
/// </summary>
public static readonly DependencyProperty SeparatorProperty = DependencyProperty.Register(
nameof(Separator),
typeof(string),
typeof(MetadataControl),
new PropertyMetadata("", OnPropertyChanged));

/// <summary>
/// The DP to store the <see cref="AccessibleSeparator"/> property value.
/// </summary>
public static readonly DependencyProperty AccessibleSeparatorProperty = DependencyProperty.Register(
nameof(AccessibleSeparator),
typeof(string),
typeof(MetadataControl),
new PropertyMetadata(", ", OnPropertyChanged));

/// <summary>
/// The DP to store the <see cref="Items"/> property value.
/// </summary>
public static readonly DependencyProperty ItemsProperty = DependencyProperty.Register(
nameof(Items),
typeof(IEnumerable<MetadataItem>),
typeof(MetadataControl),
new PropertyMetadata(null, OnMetadataItemsChanged));

/// <summary>
/// The DP to store the TextBlockStyle value.
/// </summary>
public static readonly DependencyProperty TextBlockStyleProperty = DependencyProperty.Register(
nameof(TextBlockStyle),
typeof(Style),
typeof(MetadataControl),
new PropertyMetadata(null));

private const string TextContainerPart = "TextContainer";

private TextBlock _textContainer;

/// <summary>
/// Initializes a new instance of the <see cref="MetadataControl"/> class.
/// </summary>
public MetadataControl()
{
DefaultStyleKey = typeof(MetadataControl);
ActualThemeChanged += OnActualThemeChanged;
}

/// <summary>
/// Gets or sets the separator to display between the <see cref="MetadataItem"/>.
/// </summary>
public string Separator
{
get => (string)GetValue(SeparatorProperty);
set => SetValue(SeparatorProperty, value);
}

/// <summary>
/// Gets or sets the separator that will be used to generate the accessible string representing the control content.
/// </summary>
public string AccessibleSeparator
{
get => (string)GetValue(AccessibleSeparatorProperty);
set => SetValue(AccessibleSeparatorProperty, value);
}

/// <summary>
/// Gets or sets the <see cref="MetadataItem"/> to display in the control.
/// If it implements <see cref="INotifyCollectionChanged"/>, the control will automatically update itself.
/// </summary>
public IEnumerable<MetadataItem> Items
{
get => (IEnumerable<MetadataItem>)GetValue(ItemsProperty);
set => SetValue(ItemsProperty, value);
}

/// <summary>
/// Gets or sets the <see cref="Style"/> to use on the inner <see cref="TextBlock"/> control.
/// </summary>
public Style TextBlockStyle
{
get => (Style)GetValue(TextBlockStyleProperty);
set => SetValue(TextBlockStyleProperty, value);
}

/// <inheritdoc/>
protected override void OnApplyTemplate()
{
_textContainer = GetTemplateChild(TextContainerPart) as TextBlock;
Update();
}

private static void OnMetadataItemsChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var control = (MetadataControl)d;
void OnCollectionChanged(object sender, NotifyCollectionChangedEventArgs args) => control.Update();

if (e.OldValue is INotifyCollectionChanged oldNcc)
{
oldNcc.CollectionChanged -= OnCollectionChanged;
}

if (e.NewValue is INotifyCollectionChanged newNcc)
{
newNcc.CollectionChanged += OnCollectionChanged;
}

control.Update();
}

private static void OnPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
=> ((MetadataControl)d).Update();

private void OnActualThemeChanged(FrameworkElement sender, object args) => Update();

private void Update()
{
if (_textContainer is null)
{
// The template is not ready yet.
return;
}

_textContainer.Inlines.Clear();

if (Items is null)
{
AutomationProperties.SetName(_textContainer, string.Empty);
NotifyLiveRegionChanged();
return;
}

Inline unitToAppend;
var accessibleString = new StringBuilder();
foreach (var unit in Items)
{
if (_textContainer.Inlines.Count > 0)
{
_textContainer.Inlines.Add(new Run { Text = Separator });
accessibleString.Append(AccessibleSeparator ?? Separator);
}

unitToAppend = new Run
{
Text = unit.Label,
};

if (unit.Command != null)
{
var hyperLink = new Hyperlink
{
UnderlineStyle = UnderlineStyle.None,
Foreground = _textContainer.Foreground,
};
hyperLink.Inlines.Add(unitToAppend);

void OnHyperlinkClicked(Hyperlink sender, HyperlinkClickEventArgs args)
{
if (unit.Command.CanExecute(unit.CommandParameter))
{
unit.Command.Execute(unit.CommandParameter);
}
}

hyperLink.Click += OnHyperlinkClicked;

unitToAppend = hyperLink;
}

var unitAccessibleLabel = unit.AccessibleLabel ?? unit.Label;
AutomationProperties.SetName(unitToAppend, unitAccessibleLabel);
accessibleString.Append(unitAccessibleLabel);

_textContainer.Inlines.Add(unitToAppend);
}

AutomationProperties.SetName(_textContainer, accessibleString.ToString());
NotifyLiveRegionChanged();
}

private void NotifyLiveRegionChanged()
{
if (AutomationPeer.ListenerExists(AutomationEvents.LiveRegionChanged))
{
var peer = FrameworkElementAutomationPeer.FromElement(this);
peer?.RaiseAutomationEvent(AutomationEvents.LiveRegionChanged);
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:controls="using:Microsoft.Toolkit.Uwp.UI.Controls">

<Style TargetType="controls:MetadataControl">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="controls:MetadataControl">
<TextBlock x:Name="TextContainer"
Style="{TemplateBinding TextBlockStyle}" />
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ResourceDictionary>
Loading

0 comments on commit ff21a8a

Please sign in to comment.