mirror of
https://jihulab.com/DGP-Studio/Snap.Hutao.git
synced 2025-11-19 21:02:53 +08:00
merge ttb into astb
This commit is contained in:
committed by
DismissedLight
parent
5c49818a2f
commit
9df46ad60e
@@ -12,6 +12,7 @@
|
||||
<ResourceDictionary Source="ms-appx:///UI/Xaml/Control/ItemIcon.xaml"/>
|
||||
<ResourceDictionary Source="ms-appx:///UI/Xaml/Control/Loading.xaml"/>
|
||||
<ResourceDictionary Source="ms-appx:///UI/Xaml/Control/StandardView.xaml"/>
|
||||
<ResourceDictionary Source="ms-appx:///UI/Xaml/Control/AutoSuggestBox/AutoSuggestTokenBox.xaml"/>
|
||||
<ResourceDictionary Source="ms-appx:///UI/Xaml/Control/Card/CardBlock.xaml"/>
|
||||
<ResourceDictionary Source="ms-appx:///UI/Xaml/Control/Card/CardProgressBar.xaml"/>
|
||||
<ResourceDictionary Source="ms-appx:///UI/Xaml/Control/Card/HorizontalCard.xaml"/>
|
||||
@@ -38,7 +39,6 @@
|
||||
<ResourceDictionary Source="ms-appx:///UI/Xaml/Control/Theme/TransitionCollection.xaml"/>
|
||||
<ResourceDictionary Source="ms-appx:///UI/Xaml/Control/Theme/Uri.xaml"/>
|
||||
<ResourceDictionary Source="ms-appx:///UI/Xaml/Control/Theme/WindowOverride.xaml"/>
|
||||
<ResourceDictionary Source="ms-appx:///UI/Xaml/Control/TokenizingTextBox/TokenizingTextBox.xaml"/>
|
||||
</ResourceDictionary.MergedDictionaries>
|
||||
|
||||
<Style
|
||||
|
||||
@@ -162,10 +162,10 @@
|
||||
<data name="ControlPanelPanelSelectorDropdownListName" xml:space="preserve">
|
||||
<value>列表</value>
|
||||
</data>
|
||||
<data name="ControlTokenizingTextBoxRemoveMenuItem" xml:space="preserve">
|
||||
<data name="ControlAutoSuggestTokenBoxRemoveMenuItem" xml:space="preserve">
|
||||
<value>删除</value>
|
||||
</data>
|
||||
<data name="ControlTokenizingTextBoxSelectAllMenuItem" xml:space="preserve">
|
||||
<data name="ControlAutoSuggestTokenBoxSelectAllMenuItem" xml:space="preserve">
|
||||
<value>选择全部</value>
|
||||
</data>
|
||||
<data name="CoreExceptionServiceDatabaseCorruptedMessage" xml:space="preserve">
|
||||
|
||||
@@ -90,6 +90,7 @@
|
||||
<None Remove="Control\Image\CachedImage.xaml" />
|
||||
<None Remove="Control\Loading.xaml" />
|
||||
<None Remove="Control\Panel\LayoutSwitch.xaml" />
|
||||
<None Remove="UI\Xaml\Control\AutoSuggestBox\AutoSuggestTokenBox.xaml" />
|
||||
<None Remove="UI\Xaml\Control\Card\CardBlock.xaml" />
|
||||
<None Remove="UI\Xaml\Control\Card\HorizontalCard.xaml" />
|
||||
<None Remove="UI\Xaml\Control\Card\VerticalCard.xaml" />
|
||||
@@ -115,7 +116,6 @@
|
||||
<None Remove="UI\Xaml\Control\Theme\TransitionCollection.xaml" />
|
||||
<None Remove="UI\Xaml\Control\Theme\Uri.xaml" />
|
||||
<None Remove="UI\Xaml\Control\Theme\WindowOverride.xaml" />
|
||||
<None Remove="UI\Xaml\Control\TokenizingTextBox\TokenizingTextBox.xaml" />
|
||||
<None Remove="GuideWindow.xaml" />
|
||||
<None Remove="IdentifyMonitorWindow.xaml" />
|
||||
<None Remove="IdentityStructs.json" />
|
||||
@@ -285,7 +285,6 @@
|
||||
<PackageReference Include="CommunityToolkit.WinUI.Controls.Primitives" Version="8.0.240109" />
|
||||
<PackageReference Include="CommunityToolkit.WinUI.Controls.Segmented" Version="8.0.240109" />
|
||||
<PackageReference Include="CommunityToolkit.WinUI.Controls.SettingsControls" Version="8.0.240109" />
|
||||
<PackageReference Include="CommunityToolkit.WinUI.Controls.TokenizingTextBox" Version="8.0.240109" />
|
||||
<PackageReference Include="CommunityToolkit.WinUI.Media" Version="8.0.240109" />
|
||||
<PackageReference Include="Google.OrTools" Version="9.10.4067" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="8.0.6" />
|
||||
@@ -423,7 +422,7 @@
|
||||
</Page>
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<Page Update="UI\Xaml\Control\TokenizingTextBox\TokenizingTextBox.xaml">
|
||||
<Page Update="UI\Xaml\Control\AutoSuggestBox\AutoSuggestTokenBox.xaml">
|
||||
<Generator>MSBuild:Compile</Generator>
|
||||
</Page>
|
||||
</ItemGroup>
|
||||
|
||||
@@ -1,22 +1,102 @@
|
||||
// Copyright (c) DGP Studio. All rights reserved.
|
||||
// Licensed under the MIT license.
|
||||
|
||||
using CommunityToolkit.WinUI;
|
||||
using CommunityToolkit.WinUI.Helpers;
|
||||
using Microsoft.UI.Dispatching;
|
||||
using Microsoft.UI.Input;
|
||||
using Microsoft.UI.Xaml;
|
||||
using Microsoft.UI.Xaml.Automation.Peers;
|
||||
using Microsoft.UI.Xaml.Controls;
|
||||
using Microsoft.UI.Xaml.Input;
|
||||
using Snap.Hutao.UI.Input;
|
||||
using Snap.Hutao.UI.Xaml.Control.TokenizingTextBox;
|
||||
using System.Collections;
|
||||
using Windows.ApplicationModel.DataTransfer;
|
||||
using Windows.Foundation.Metadata;
|
||||
using Windows.UI.Core;
|
||||
using VirtualKey = Windows.System.VirtualKey;
|
||||
|
||||
namespace Snap.Hutao.UI.Xaml.Control.AutoSuggestBox;
|
||||
|
||||
[DependencyProperty("AutoSuggestBoxStyle", typeof(Style))]
|
||||
[DependencyProperty("AutoSuggestBoxTextBoxStyle", typeof(Style))]
|
||||
[DependencyProperty("AvailableTokens", typeof(IReadOnlyDictionary<string, SearchToken>))]
|
||||
[DependencyProperty("FilterCommand", typeof(ICommand))]
|
||||
[DependencyProperty("FilterCommandParameter", typeof(object))]
|
||||
[DependencyProperty("AvailableTokens", typeof(IReadOnlyDictionary<string, SearchToken>))]
|
||||
internal sealed partial class AutoSuggestTokenBox : TokenizingTextBox.TokenizingTextBox
|
||||
[DependencyProperty("MaximumTokens", typeof(int), -1, nameof(OnMaximumTokensChanged))]
|
||||
[DependencyProperty("PlaceholderText", typeof(string))]
|
||||
[DependencyProperty("QueryIcon", typeof(IconSource))]
|
||||
[DependencyProperty("SuggestedItemsSource", typeof(object))]
|
||||
[DependencyProperty("SuggestedItemTemplate", typeof(DataTemplate))]
|
||||
[DependencyProperty("SuggestedItemTemplateSelector", typeof(DataTemplateSelector))]
|
||||
[DependencyProperty("SuggestedItemContainerStyle", typeof(Style))]
|
||||
[DependencyProperty("TabNavigateBackOnArrow", typeof(bool), false)]
|
||||
[DependencyProperty("Text", typeof(string), default, nameof(OnTextPropertyChanged))]
|
||||
[DependencyProperty("TextMemberPath", typeof(string))]
|
||||
[DependencyProperty("TokenItemTemplate", typeof(DataTemplate))]
|
||||
[DependencyProperty("TokenItemTemplateSelector", typeof(DataTemplateSelector))]
|
||||
[DependencyProperty("TokenDelimiter", typeof(string), " ")]
|
||||
[DependencyProperty("TokenSpacing", typeof(double))]
|
||||
[TemplatePart(Name = NormalState, Type = typeof(VisualState))]
|
||||
[TemplatePart(Name = PointerOverState, Type = typeof(VisualState))]
|
||||
[TemplatePart(Name = FocusedState, Type = typeof(VisualState))]
|
||||
[TemplatePart(Name = UnfocusedState, Type = typeof(VisualState))]
|
||||
[TemplatePart(Name = MaxReachedState, Type = typeof(VisualState))]
|
||||
[TemplatePart(Name = MaxUnreachedState, Type = typeof(VisualState))]
|
||||
internal sealed partial class AutoSuggestTokenBox : ListViewBase
|
||||
{
|
||||
public const string NormalState = "Normal";
|
||||
public const string PointerOverState = "PointerOver";
|
||||
public const string FocusedState = "Focused";
|
||||
public const string UnfocusedState = "Unfocused";
|
||||
public const string MaxReachedState = "MaxReached";
|
||||
public const string MaxUnreachedState = "MaxUnreached";
|
||||
|
||||
private InterspersedObservableCollection innerItemsSource;
|
||||
private ITokenStringContainer currentTextEdit; // Don't update this directly outside of initialization, use UpdateCurrentTextEdit Method
|
||||
private ITokenStringContainer lastTextEdit;
|
||||
|
||||
public AutoSuggestTokenBox()
|
||||
{
|
||||
DefaultStyleKey = typeof(TokenizingTextBox.TokenizingTextBox);
|
||||
innerItemsSource = [];
|
||||
currentTextEdit = lastTextEdit = new PretokenStringContainer(true);
|
||||
innerItemsSource.Insert(innerItemsSource.Count, currentTextEdit);
|
||||
ItemsSource = innerItemsSource;
|
||||
|
||||
DefaultStyleKey = typeof(AutoSuggestTokenBox);
|
||||
|
||||
RegisterPropertyChangedCallback(ItemsSourceProperty, OnItemsSourceChanged);
|
||||
PreviewKeyDown += OnPreviewKeyDown;
|
||||
PreviewKeyUp += OnPreviewKeyUp;
|
||||
CharacterReceived += OnCharacterReceived;
|
||||
ItemClick += OnItemClick;
|
||||
}
|
||||
|
||||
private enum MoveDirection
|
||||
{
|
||||
Next,
|
||||
Previous,
|
||||
}
|
||||
|
||||
public static bool IsControlPressed
|
||||
{
|
||||
get => InputKeyboardSource.GetKeyStateForCurrentThread(VirtualKey.Control).HasFlag(CoreVirtualKeyStates.Down);
|
||||
}
|
||||
|
||||
public static bool IsShiftPressed
|
||||
{
|
||||
get => InputKeyboardSource.GetKeyStateForCurrentThread(VirtualKey.Shift).HasFlag(CoreVirtualKeyStates.Down);
|
||||
}
|
||||
|
||||
public static bool IsXamlRootAvailable { get; } = ApiInformation.IsPropertyPresent("Windows.UI.Xaml.UIElement", "XamlRoot");
|
||||
|
||||
public bool IsClearingForClick { get; set; }
|
||||
|
||||
public bool PauseTokenClearOnFocus { get; set; }
|
||||
|
||||
public string SelectedTokenText
|
||||
{
|
||||
get => PrepareSelectionForClipboard();
|
||||
}
|
||||
|
||||
public IEnumerable<SearchToken> Tokens
|
||||
@@ -24,7 +104,114 @@ internal sealed partial class AutoSuggestTokenBox : TokenizingTextBox.Tokenizing
|
||||
get => ((IList)ItemsSource).OfType<SearchToken>();
|
||||
}
|
||||
|
||||
public override void OnTextChanged(Microsoft.UI.Xaml.Controls.AutoSuggestBox sender, AutoSuggestBoxTextChangedEventArgs args)
|
||||
public void AddToken(object data, bool atEnd = false)
|
||||
{
|
||||
if (MaximumTokens >= 0 && IsTokenLimitReached())
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (data is string str)
|
||||
{
|
||||
TokenItemAddingEventArgs tiaea = new(str);
|
||||
OnTokenItemAdding(this, tiaea);
|
||||
|
||||
if (tiaea.Cancel)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (tiaea.Item is not null)
|
||||
{
|
||||
data = tiaea.Item;
|
||||
}
|
||||
}
|
||||
|
||||
// Custom: Avoid add same token
|
||||
if (innerItemsSource.Contains(data))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// If we've been typing in the last box, just add this to the end of our collection
|
||||
if (atEnd || currentTextEdit == lastTextEdit)
|
||||
{
|
||||
innerItemsSource.InsertAt(innerItemsSource.Count - 1, data);
|
||||
}
|
||||
else
|
||||
{
|
||||
// Otherwise, we'll insert before our current box
|
||||
ITokenStringContainer edit = currentTextEdit;
|
||||
int index = innerItemsSource.IndexOf(edit);
|
||||
|
||||
// Insert our new data item at the location of our textbox
|
||||
innerItemsSource.InsertAt(index, data);
|
||||
|
||||
// Remove our textbox
|
||||
innerItemsSource.Remove(edit);
|
||||
}
|
||||
|
||||
AutoSuggestTokenBoxItem last = (AutoSuggestTokenBoxItem)ContainerFromItem(lastTextEdit);
|
||||
ArgumentNullException.ThrowIfNull(last.AutoSuggestTextBox);
|
||||
last.AutoSuggestTextBox.Focus(FocusState.Keyboard);
|
||||
|
||||
OnTokenItemAdded(this, data);
|
||||
UpdatePlaceholderVisibility();
|
||||
}
|
||||
|
||||
public void Clear()
|
||||
{
|
||||
while (innerItemsSource.Count > 1)
|
||||
{
|
||||
if (ContainerFromItem(innerItemsSource[0]) is AutoSuggestTokenBoxItem container)
|
||||
{
|
||||
if (!RemoveToken(container, innerItemsSource[0]))
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Text = string.Empty;
|
||||
}
|
||||
|
||||
public void DeselectAllTokensAndText(AutoSuggestTokenBoxItem? ignoreItem = default)
|
||||
{
|
||||
this.DeselectAll();
|
||||
ClearAllTextSelections(ignoreItem);
|
||||
}
|
||||
|
||||
public bool IsTokenLimitReached()
|
||||
{
|
||||
return innerItemsSource.ItemsSource.Count >= MaximumTokens;
|
||||
}
|
||||
|
||||
public void RefreshTokenCounter()
|
||||
{
|
||||
if (ContainerFromIndex(Items.Count - 1) is not AutoSuggestTokenBoxItem { AutoSuggestBox: { } autoSuggestBox, AutoSuggestTextBox: { } autoSuggestTextBox })
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (autoSuggestBox.FindDescendant("TextTokensCounter") is not Microsoft.UI.Xaml.Controls.TextBlock maxTokensCounter)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
int currentTokens = innerItemsSource.ItemsSource.Count;
|
||||
int maxTokens = MaximumTokens;
|
||||
|
||||
maxTokensCounter.Text = $"{currentTokens}/{maxTokens}";
|
||||
maxTokensCounter.Visibility = Visibility.Visible;
|
||||
|
||||
string targetState = IsTokenLimitReached()
|
||||
? MaxReachedState
|
||||
: MaxUnreachedState;
|
||||
|
||||
VisualStateManager.GoToState(autoSuggestTextBox, targetState, true);
|
||||
}
|
||||
|
||||
public void OnTextChanged(Microsoft.UI.Xaml.Controls.AutoSuggestBox sender, AutoSuggestBoxTextChangedEventArgs args)
|
||||
{
|
||||
if (IsTokenLimitReached())
|
||||
{
|
||||
@@ -52,7 +239,7 @@ internal sealed partial class AutoSuggestTokenBox : TokenizingTextBox.Tokenizing
|
||||
}
|
||||
}
|
||||
|
||||
public override void OnQuerySubmitted(Microsoft.UI.Xaml.Controls.AutoSuggestBox sender, AutoSuggestBoxQuerySubmittedEventArgs args)
|
||||
public void OnQuerySubmitted(Microsoft.UI.Xaml.Controls.AutoSuggestBox sender, AutoSuggestBoxQuerySubmittedEventArgs args)
|
||||
{
|
||||
if (args.ChosenSuggestion is not null)
|
||||
{
|
||||
@@ -62,7 +249,11 @@ internal sealed partial class AutoSuggestTokenBox : TokenizingTextBox.Tokenizing
|
||||
CommandInvocation.TryExecute(FilterCommand, FilterCommandParameter);
|
||||
}
|
||||
|
||||
public override void OnTokenItemAdding(TokenizingTextBox.TokenizingTextBox sender, TokenItemAddingEventArgs args)
|
||||
public void OnSuggestionsChosen(Microsoft.UI.Xaml.Controls.AutoSuggestBox sender, AutoSuggestBoxSuggestionChosenEventArgs args)
|
||||
{
|
||||
}
|
||||
|
||||
public void OnTokenItemAdding(AutoSuggestTokenBox sender, TokenItemAddingEventArgs args)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(args.TokenText))
|
||||
{
|
||||
@@ -79,21 +270,694 @@ internal sealed partial class AutoSuggestTokenBox : TokenizingTextBox.Tokenizing
|
||||
}
|
||||
}
|
||||
|
||||
public override void OnTokenItemAdded(TokenizingTextBox.TokenizingTextBox sender, object args)
|
||||
public void OnTokenItemAdded(AutoSuggestTokenBox sender, object args)
|
||||
{
|
||||
if (args is SearchToken { Kind: SearchTokenKind.None } token)
|
||||
{
|
||||
((IList)ItemsSource).Remove(token);
|
||||
}
|
||||
|
||||
base.OnTokenItemAdded(sender, args);
|
||||
RefreshTokenCounter();
|
||||
|
||||
FilterCommand.TryExecute(FilterCommandParameter);
|
||||
}
|
||||
|
||||
public override void OnTokenItemRemoved(TokenizingTextBox.TokenizingTextBox sender, object args)
|
||||
public void OnTokenItemRemoved(AutoSuggestTokenBox sender, object args)
|
||||
{
|
||||
base.OnTokenItemRemoved(sender, args);
|
||||
RefreshTokenCounter();
|
||||
FilterCommand.TryExecute(FilterCommandParameter);
|
||||
}
|
||||
|
||||
public void OnTokenItemRemoving(AutoSuggestTokenBox sender, TokenItemRemovingEventArgs args)
|
||||
{
|
||||
}
|
||||
|
||||
public void RemoveAllSelectedTokens()
|
||||
{
|
||||
while (SelectedItems.Count > 0)
|
||||
{
|
||||
if (ContainerFromItem(SelectedItems[0]) is AutoSuggestTokenBoxItem container)
|
||||
{
|
||||
if (IndexFromContainer(container) != Items.Count - 1)
|
||||
{
|
||||
// if its a text box, remove any selected text, and if its then empty remove the container, unless its focused
|
||||
if (SelectedItems[0] is ITokenStringContainer)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(container.AutoSuggestTextBox);
|
||||
TextBox astb = container.AutoSuggestTextBox;
|
||||
|
||||
// grab any selected text
|
||||
string tempStr = astb.SelectionStart is 0
|
||||
? string.Empty
|
||||
: astb.Text[..astb.SelectionStart];
|
||||
tempStr += astb.SelectionStart + astb.SelectionLength < astb.Text.Length
|
||||
? astb.Text[(astb.SelectionStart + astb.SelectionLength)..]
|
||||
: string.Empty;
|
||||
|
||||
if (tempStr.Length is 0)
|
||||
{
|
||||
RemoveToken(container);
|
||||
}
|
||||
else
|
||||
{
|
||||
astb.Text = tempStr;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
RemoveToken(container);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (SelectedItems.Count is 1)
|
||||
{
|
||||
// Only remains the default textbox.
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[Command("SelectAllTokensAndTextCommand")]
|
||||
public void SelectAllTokensAndText()
|
||||
{
|
||||
void SelectAllTokensAndTextCore()
|
||||
{
|
||||
this.SelectAllSafe();
|
||||
|
||||
// need to synchronize the select all and the focus behavior on the text box
|
||||
// because there is no way to identify that the focus has been set from this point
|
||||
// to avoid instantly clearing the selection of tokens
|
||||
PauseTokenClearOnFocus = true;
|
||||
|
||||
foreach (object? item in Items)
|
||||
{
|
||||
if (item is not ITokenStringContainer)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
// grab any selected text
|
||||
if (ContainerFromItem(item) is AutoSuggestTokenBoxItem pretoken)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(pretoken.AutoSuggestTextBox);
|
||||
pretoken.AutoSuggestTextBox.SelectionStart = 0;
|
||||
pretoken.AutoSuggestTextBox.SelectionLength = pretoken.AutoSuggestTextBox.Text.Length;
|
||||
}
|
||||
}
|
||||
|
||||
if (ContainerFromIndex(Items.Count - 1) is AutoSuggestTokenBoxItem container)
|
||||
{
|
||||
container.Focus(FocusState.Programmatic);
|
||||
}
|
||||
}
|
||||
|
||||
_ = DispatcherQueue.EnqueueAsync(SelectAllTokensAndTextCore, DispatcherQueuePriority.Normal);
|
||||
}
|
||||
|
||||
public bool SelectNextItem(AutoSuggestTokenBoxItem item)
|
||||
{
|
||||
return SelectNewItem(item, 1, i => i < Items.Count - 1);
|
||||
}
|
||||
|
||||
public bool SelectPreviousItem(AutoSuggestTokenBoxItem item)
|
||||
{
|
||||
return SelectNewItem(item, -1, i => i > 0);
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
protected override DependencyObject GetContainerForItemOverride()
|
||||
{
|
||||
return new AutoSuggestTokenBoxItem();
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
protected override bool IsItemItsOwnContainerOverride(object item)
|
||||
{
|
||||
return item is AutoSuggestTokenBoxItem;
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
protected override AutomationPeer OnCreateAutomationPeer()
|
||||
{
|
||||
return new AutoSuggestTokenBoxAutomationPeer(this);
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
protected override void PrepareContainerForItemOverride(DependencyObject element, object item)
|
||||
{
|
||||
base.PrepareContainerForItemOverride(element, item);
|
||||
|
||||
if (element is AutoSuggestTokenBoxItem tokenItem)
|
||||
{
|
||||
tokenItem.Owner = this;
|
||||
|
||||
tokenItem.ContentTemplateSelector = TokenItemTemplateSelector;
|
||||
tokenItem.ContentTemplate = TokenItemTemplate;
|
||||
|
||||
tokenItem.ClearAllAction -= OnItemClearAllAction;
|
||||
tokenItem.ClearAllAction += OnItemClearAllAction;
|
||||
|
||||
tokenItem.GotFocus -= OnItemGotFocus;
|
||||
tokenItem.GotFocus += OnItemGotFocus;
|
||||
|
||||
tokenItem.LostFocus -= OnItemLostFocus;
|
||||
tokenItem.LostFocus += OnItemLostFocus;
|
||||
}
|
||||
}
|
||||
|
||||
private static void OnMaximumTokensChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
|
||||
{
|
||||
if (d is AutoSuggestTokenBox { MaximumTokens: >= 0 } ttb && e.NewValue is int newMaxTokens)
|
||||
{
|
||||
int 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 (int i = tokenCount; i > tokenCount - tokensToRemove; --i)
|
||||
{
|
||||
if (ttb.innerItemsSource.ItemsSource[i - 1] is { } token)
|
||||
{
|
||||
// Force remove the items. No warning and no option to cancel.
|
||||
ttb.innerItemsSource.Remove(token);
|
||||
ttb.OnTokenItemRemoved(ttb, token);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void OnTextPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
|
||||
{
|
||||
if (d is AutoSuggestTokenBox { currentTextEdit: { } } ttb)
|
||||
{
|
||||
if (e.NewValue is string newValue)
|
||||
{
|
||||
ttb.currentTextEdit.Text = newValue;
|
||||
|
||||
// Notify inner container of text change, see issue #4749
|
||||
if (ttb.ContainerFromItem(ttb.currentTextEdit) is AutoSuggestTokenBoxItem item)
|
||||
{
|
||||
item.UpdateText(newValue);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void ClearAllTextSelections(AutoSuggestTokenBoxItem? ignoreItem)
|
||||
{
|
||||
// Clear any selection in the text box
|
||||
foreach (object? item in Items)
|
||||
{
|
||||
if (item is not ITokenStringContainer)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (ContainerFromItem(item) is AutoSuggestTokenBoxItem container)
|
||||
{
|
||||
if (container != ignoreItem)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(container.AutoSuggestTextBox);
|
||||
container.AutoSuggestTextBox.SelectionLength = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void CopySelectedToClipboard()
|
||||
{
|
||||
DataPackage dataPackage = new()
|
||||
{
|
||||
RequestedOperation = DataPackageOperation.Copy,
|
||||
};
|
||||
|
||||
string tokenString = PrepareSelectionForClipboard();
|
||||
|
||||
if (!string.IsNullOrEmpty(tokenString))
|
||||
{
|
||||
dataPackage.SetText(tokenString);
|
||||
Clipboard.SetContent(dataPackage);
|
||||
}
|
||||
}
|
||||
|
||||
private void FocusPrimaryAutoSuggestBox()
|
||||
{
|
||||
if (Items.Count > 0)
|
||||
{
|
||||
if (ContainerFromIndex(Items.Count - 1) is AutoSuggestTokenBoxItem container)
|
||||
{
|
||||
container.Focus(FocusState.Programmatic);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private AutoSuggestTokenBoxItem? GetCurrentContainerItem()
|
||||
{
|
||||
return IsXamlRootAvailable && XamlRoot is not null
|
||||
? FocusManager.GetFocusedElement(XamlRoot) as AutoSuggestTokenBoxItem
|
||||
: FocusManager.GetFocusedElement() as AutoSuggestTokenBoxItem;
|
||||
}
|
||||
|
||||
private object GetFocusedElement()
|
||||
{
|
||||
return IsXamlRootAvailable && XamlRoot is not null
|
||||
? FocusManager.GetFocusedElement(XamlRoot)
|
||||
: FocusManager.GetFocusedElement();
|
||||
}
|
||||
|
||||
private bool MoveFocusAndSelection(MoveDirection direction)
|
||||
{
|
||||
bool ret = false;
|
||||
|
||||
if (GetCurrentContainerItem() is { } currentContainerItem)
|
||||
{
|
||||
object? currentItem = ItemFromContainer(currentContainerItem);
|
||||
int previousIndex = Items.IndexOf(currentItem);
|
||||
int index = previousIndex;
|
||||
|
||||
switch (direction)
|
||||
{
|
||||
case MoveDirection.Previous:
|
||||
if (previousIndex > 0)
|
||||
{
|
||||
index -= 1;
|
||||
break;
|
||||
}
|
||||
|
||||
if (TabNavigateBackOnArrow)
|
||||
{
|
||||
FocusManager.TryMoveFocus(FocusNavigationDirection.Previous, new()
|
||||
{
|
||||
SearchRoot = XamlRoot.Content,
|
||||
});
|
||||
}
|
||||
|
||||
ret = true;
|
||||
|
||||
break;
|
||||
case MoveDirection.Next:
|
||||
if (previousIndex < Items.Count - 1)
|
||||
{
|
||||
index += 1;
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
// Only do stuff if the index is actually changing
|
||||
if (index != previousIndex)
|
||||
{
|
||||
if (ContainerFromIndex(index) is AutoSuggestTokenBoxItem newItem)
|
||||
{
|
||||
// Check for the new item being a text control.
|
||||
// this must happen before focus is set to avoid seeing the caret
|
||||
// jump in come cases
|
||||
if (Items[index] is ITokenStringContainer && !IsShiftPressed)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(newItem.AutoSuggestTextBox);
|
||||
newItem.AutoSuggestTextBox.SelectionLength = 0;
|
||||
newItem.AutoSuggestTextBox.SelectionStart = direction switch
|
||||
{
|
||||
MoveDirection.Previous => newItem.AutoSuggestTextBox.Text.Length,
|
||||
MoveDirection.Next => 0,
|
||||
_ => throw new NotSupportedException(),
|
||||
};
|
||||
}
|
||||
|
||||
newItem.Focus(FocusState.Keyboard);
|
||||
|
||||
// if no control keys are selected then the selection also becomes just this item
|
||||
if (IsShiftPressed)
|
||||
{
|
||||
// What we do here depends on where the selection started
|
||||
// if the previous item is between the start and new position then we add the new item to the selected range
|
||||
// if the new item is between the start and the previous position then we remove the previous position
|
||||
int newDistance = Math.Abs(SelectedIndex - index);
|
||||
int oldDistance = Math.Abs(SelectedIndex - previousIndex);
|
||||
|
||||
if (newDistance > oldDistance)
|
||||
{
|
||||
SelectedItems.Add(Items[index]);
|
||||
}
|
||||
else
|
||||
{
|
||||
SelectedItems.Remove(Items[previousIndex]);
|
||||
}
|
||||
}
|
||||
else if (!IsControlPressed)
|
||||
{
|
||||
SelectedIndex = index;
|
||||
|
||||
// This looks like a bug in the underlying ListViewBase control.
|
||||
// Might need to be reviewed if the base behavior is fixed
|
||||
// When two consecutive items are selected and the navigation moves between them,
|
||||
// the first time that happens the old focused item is not unselected
|
||||
if (SelectedItems.Count > 1)
|
||||
{
|
||||
SelectedItems.Clear();
|
||||
SelectedIndex = index;
|
||||
}
|
||||
}
|
||||
|
||||
ret = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
private void OnCharacterReceived(UIElement sender, CharacterReceivedRoutedEventArgs args)
|
||||
{
|
||||
if (ContainerFromItem(currentTextEdit) is AutoSuggestTokenBoxItem container && !(GetFocusedElement().Equals(container.AutoSuggestTextBox) || char.IsControl(args.Character)))
|
||||
{
|
||||
if (SelectedItems.Count > 0)
|
||||
{
|
||||
int index = innerItemsSource.IndexOf(SelectedItems.First());
|
||||
|
||||
RemoveAllSelectedTokens();
|
||||
|
||||
void RemoveOldItems()
|
||||
{
|
||||
// If we're before the last textbox and it's empty, redirect focus to that one instead
|
||||
if (index == innerItemsSource.Count - 1 && string.IsNullOrWhiteSpace(lastTextEdit.Text))
|
||||
{
|
||||
if (ContainerFromItem(lastTextEdit) is AutoSuggestTokenBoxItem lastContainer)
|
||||
{
|
||||
lastContainer.UseCharacterAsUser = true;
|
||||
|
||||
lastTextEdit.Text = string.Empty + args.Character;
|
||||
UpdateCurrentTextEdit(lastTextEdit);
|
||||
|
||||
ArgumentNullException.ThrowIfNull(lastContainer.AutoSuggestTextBox);
|
||||
lastContainer.AutoSuggestTextBox.SelectionStart = 1;
|
||||
lastContainer.AutoSuggestTextBox.Focus(FocusState.Keyboard);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
// Otherwise, create a new textbox for this text.
|
||||
UpdateCurrentTextEdit(new PretokenStringContainer((string.Empty + args.Character).Trim()));
|
||||
innerItemsSource.Insert(index, currentTextEdit);
|
||||
|
||||
void Containerization()
|
||||
{
|
||||
if (ContainerFromIndex(index) is AutoSuggestTokenBoxItem newContainer)
|
||||
{
|
||||
newContainer.UseCharacterAsUser = true;
|
||||
|
||||
void WaitForLoad(object s, RoutedEventArgs eargs)
|
||||
{
|
||||
if (newContainer.AutoSuggestTextBox is not null)
|
||||
{
|
||||
newContainer.AutoSuggestTextBox.SelectionStart = 1;
|
||||
newContainer.AutoSuggestTextBox.Focus(FocusState.Keyboard);
|
||||
}
|
||||
|
||||
newContainer.AutoSuggestTextBoxLoaded -= WaitForLoad;
|
||||
}
|
||||
|
||||
newContainer.AutoSuggestTextBoxLoaded += WaitForLoad;
|
||||
}
|
||||
}
|
||||
|
||||
// Need to wait for containerization
|
||||
_ = DispatcherQueue.EnqueueAsync(Containerization, DispatcherQueuePriority.Normal);
|
||||
}
|
||||
}
|
||||
|
||||
// Wait for removal of old items
|
||||
_ = DispatcherQueue.EnqueueAsync(RemoveOldItems, DispatcherQueuePriority.Normal);
|
||||
}
|
||||
else
|
||||
{
|
||||
// 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[^1] is ITokenStringContainer textEdit)
|
||||
{
|
||||
if (ContainerFromIndex(Items.Count - 1) is AutoSuggestTokenBoxItem last) // Should be our last text box
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(last.AutoSuggestTextBox);
|
||||
string text = last.AutoSuggestTextBox.Text;
|
||||
int selectionStart = last.AutoSuggestTextBox.SelectionStart;
|
||||
int position = Math.Min(selectionStart, text.Length);
|
||||
textEdit.Text = text[..position] + args.Character + text[position..];
|
||||
|
||||
last.AutoSuggestTextBox.SelectionStart = position + 1;
|
||||
last.AutoSuggestTextBox.Focus(FocusState.Keyboard);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void OnItemClearAllAction(AutoSuggestTokenBoxItem sender, RoutedEventArgs args)
|
||||
{
|
||||
int newSelectedIndex = SelectedRanges.Count > 0
|
||||
? SelectedRanges[0].FirstIndex - 1
|
||||
: -1;
|
||||
|
||||
RemoveAllSelectedTokens();
|
||||
|
||||
SelectedIndex = newSelectedIndex;
|
||||
|
||||
if (newSelectedIndex is -1)
|
||||
{
|
||||
newSelectedIndex = Items.Count - 1;
|
||||
}
|
||||
|
||||
// focus the item prior to the first selected item
|
||||
if (ContainerFromIndex(newSelectedIndex) is AutoSuggestTokenBoxItem container)
|
||||
{
|
||||
container.Focus(FocusState.Keyboard);
|
||||
}
|
||||
}
|
||||
|
||||
private void OnItemClick(object sender, ItemClickEventArgs e)
|
||||
{
|
||||
if (!IsControlPressed)
|
||||
{
|
||||
IsClearingForClick = true;
|
||||
ClearAllTextSelections(default);
|
||||
}
|
||||
}
|
||||
|
||||
private void OnItemGotFocus(object sender, RoutedEventArgs e)
|
||||
{
|
||||
if (sender is AutoSuggestTokenBoxItem { AutoSuggestBox: { } autoSuggestBox, Content: ITokenStringContainer text } item)
|
||||
{
|
||||
UpdateCurrentTextEdit(text);
|
||||
|
||||
// Custom: Show all items when focus on the textbox
|
||||
OnTextChanged(autoSuggestBox, new());
|
||||
}
|
||||
}
|
||||
|
||||
private void OnItemLostFocus(object sender, RoutedEventArgs e)
|
||||
{
|
||||
// Keep track of our currently focused textbox
|
||||
if (sender is AutoSuggestTokenBoxItem { Content: ITokenStringContainer text } && string.IsNullOrWhiteSpace(text.Text) && text != lastTextEdit)
|
||||
{
|
||||
// We're leaving an inner textbox that's blank, so we'll remove it
|
||||
innerItemsSource.Remove(text);
|
||||
|
||||
UpdateCurrentTextEdit(lastTextEdit);
|
||||
|
||||
UpdatePlaceholderVisibility();
|
||||
}
|
||||
}
|
||||
|
||||
private void OnItemsSourceChanged(DependencyObject sender, DependencyProperty dp)
|
||||
{
|
||||
// If we're given a different ItemsSource, we need to wrap that collection in our helper class.
|
||||
if (ItemsSource is { } and not InterspersedObservableCollection)
|
||||
{
|
||||
innerItemsSource = new(ItemsSource);
|
||||
|
||||
if (MaximumTokens >= 0 && IsTokenLimitReached())
|
||||
{
|
||||
// Reduce down to below the max as necessary.
|
||||
int endCount = MaximumTokens > 0 ? MaximumTokens : 0;
|
||||
for (int i = innerItemsSource.ItemsSource.Count - 1; i >= endCount; --i)
|
||||
{
|
||||
innerItemsSource.Remove(innerItemsSource[i]);
|
||||
}
|
||||
}
|
||||
|
||||
// Add our text box at the end of items and set its default value to our initial text, fix for #4749
|
||||
currentTextEdit = lastTextEdit = new PretokenStringContainer(true) { Text = Text };
|
||||
innerItemsSource.Insert(innerItemsSource.Count, currentTextEdit);
|
||||
ItemsSource = innerItemsSource;
|
||||
}
|
||||
}
|
||||
|
||||
private void OnPreviewKeyDown(object sender, KeyRoutedEventArgs e)
|
||||
{
|
||||
switch (e.Key)
|
||||
{
|
||||
case VirtualKey.C:
|
||||
if (IsControlPressed)
|
||||
{
|
||||
CopySelectedToClipboard();
|
||||
e.Handled = true;
|
||||
return;
|
||||
}
|
||||
|
||||
break;
|
||||
|
||||
case VirtualKey.X:
|
||||
if (IsControlPressed)
|
||||
{
|
||||
CopySelectedToClipboard();
|
||||
|
||||
// now clear all selected tokens and text, or all if none are selected
|
||||
RemoveAllSelectedTokens();
|
||||
}
|
||||
|
||||
break;
|
||||
|
||||
// For moving between tokens
|
||||
case VirtualKey.Left:
|
||||
e.Handled = MoveFocusAndSelection(MoveDirection.Previous);
|
||||
return;
|
||||
|
||||
case VirtualKey.Right:
|
||||
e.Handled = MoveFocusAndSelection(MoveDirection.Next);
|
||||
return;
|
||||
|
||||
case VirtualKey.A:
|
||||
// modify the select-all behavior to ensure the text in the edit box gets selected.
|
||||
if (IsControlPressed)
|
||||
{
|
||||
SelectAllTokensAndText();
|
||||
e.Handled = true;
|
||||
return;
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private void OnPreviewKeyUp(object sender, KeyRoutedEventArgs e)
|
||||
{
|
||||
switch (e.Key)
|
||||
{
|
||||
case VirtualKey.Escape:
|
||||
// Clear any selection and place the focus back into the text box
|
||||
DeselectAllTokensAndText();
|
||||
FocusPrimaryAutoSuggestBox();
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private string PrepareSelectionForClipboard()
|
||||
{
|
||||
string tokenString = string.Empty;
|
||||
bool addSeparator = false;
|
||||
|
||||
// Copy all items if none selected (and no text selected)
|
||||
foreach (object? item in SelectedItems.Count > 0 ? SelectedItems : Items)
|
||||
{
|
||||
if (addSeparator)
|
||||
{
|
||||
tokenString += TokenDelimiter;
|
||||
}
|
||||
else
|
||||
{
|
||||
addSeparator = true;
|
||||
}
|
||||
|
||||
if (item is ITokenStringContainer)
|
||||
{
|
||||
// grab any selected text
|
||||
if (ContainerFromItem(item) is AutoSuggestTokenBoxItem { AutoSuggestTextBox: { } textBox })
|
||||
{
|
||||
tokenString += textBox.Text.Substring(textBox.SelectionStart, textBox.SelectionLength);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
tokenString += item.ToString();
|
||||
}
|
||||
}
|
||||
|
||||
return tokenString;
|
||||
}
|
||||
|
||||
[Command("RemoveItemCommand")]
|
||||
private void RemoveToken(AutoSuggestTokenBoxItem item)
|
||||
{
|
||||
RemoveToken(item, default);
|
||||
}
|
||||
|
||||
private bool RemoveToken(AutoSuggestTokenBoxItem item, object? data)
|
||||
{
|
||||
data ??= ItemFromContainer(item);
|
||||
|
||||
TokenItemRemovingEventArgs tirea = new(data, item);
|
||||
OnTokenItemRemoving(this, tirea);
|
||||
|
||||
if (tirea.Cancel)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
innerItemsSource.Remove(data);
|
||||
|
||||
OnTokenItemRemoved(this, data);
|
||||
UpdatePlaceholderVisibility();
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private bool SelectNewItem(AutoSuggestTokenBoxItem item, int increment, Func<int, bool> testFunc)
|
||||
{
|
||||
// find the item in the list
|
||||
int currentIndex = IndexFromContainer(item);
|
||||
|
||||
// Select previous token item (if there is one).
|
||||
if (testFunc(currentIndex))
|
||||
{
|
||||
if (ContainerFromItem(Items[currentIndex + increment]) is ListViewItem newItem)
|
||||
{
|
||||
newItem.Focus(FocusState.Keyboard);
|
||||
SelectedItems.Add(Items[currentIndex + increment]);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private void UpdateCurrentTextEdit(ITokenStringContainer edit)
|
||||
{
|
||||
currentTextEdit = edit;
|
||||
|
||||
Text = edit.Text; // Update our text property.
|
||||
}
|
||||
|
||||
private void UpdatePlaceholderVisibility()
|
||||
{
|
||||
if (ContainerFromItem(lastTextEdit)?.FindDescendant("PlaceholderTextContentPresenter") is not { } placeholder)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Fix layout issue
|
||||
placeholder.Visibility = Visibility.Collapsed;
|
||||
|
||||
_ = CompositionTargetHelper.ExecuteAfterCompositionRenderingAsync(() =>
|
||||
{
|
||||
int currentTokens = innerItemsSource.ItemsSource.Count;
|
||||
int maxTokens = MaximumTokens;
|
||||
placeholder.Visibility = currentTokens >= maxTokens
|
||||
? Visibility.Collapsed
|
||||
: Visibility.Visible;
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -3,28 +3,26 @@
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:cw="using:CommunityToolkit.WinUI"
|
||||
xmlns:cwc="using:CommunityToolkit.WinUI.Controls"
|
||||
xmlns:shuxct="using:Snap.Hutao.UI.Xaml.Control.TokenizingTextBox"
|
||||
xmlns:shuxca="using:Snap.Hutao.UI.Xaml.Control.AutoSuggestBox"
|
||||
xmlns:shuxm="using:Snap.Hutao.UI.Xaml.Markup"
|
||||
xmlns:win="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
|
||||
<ResourceDictionary.MergedDictionaries>
|
||||
<ResourceDictionary Source="ms-appx:///UI/Xaml/Control/TokenizingTextBox/TokenizingTextBoxItem.xaml"/>
|
||||
<ResourceDictionary Source="ms-appx:///UI/Xaml/Control/AutoSuggestBox/AutoSuggestTokenBoxItem.xaml"/>
|
||||
</ResourceDictionary.MergedDictionaries>
|
||||
|
||||
<!-- Resources for TokenizingTextBox -->
|
||||
<Thickness x:Key="TokenizingTextBoxPadding">3,2,3,2</Thickness>
|
||||
<Thickness x:Key="TokenizingTextBoxPresenterMargin">0,0,6,0</Thickness>
|
||||
<x:Double x:Key="TokenizingTextBoxTokenSpacing">2</x:Double>
|
||||
<Thickness x:Key="AutoSuggestTokenBoxPadding">3,2,3,2</Thickness>
|
||||
<Thickness x:Key="AutoSuggestTokenBoxPresenterMargin">0,0,6,0</Thickness>
|
||||
<x:Double x:Key="AutoSuggestTokenBoxTokenSpacing">2</x:Double>
|
||||
|
||||
<shuxct:TokenizingTextBoxStyleSelector
|
||||
x:Key="TokenizingTextBoxStyleSelector"
|
||||
TextStyle="{StaticResource TokenizingTextBoxItemTextStyle}"
|
||||
TokenStyle="{StaticResource TokenizingTextBoxItemTokenStyle}"/>
|
||||
<shuxca:AutoSuggestTokenBoxStyleSelector
|
||||
x:Key="AutoSuggestTokenBoxStyleSelector"
|
||||
TextStyle="{StaticResource AutoSuggestTokenBoxItemTextStyle}"
|
||||
TokenStyle="{StaticResource AutoSuggestTokenBoxItemTokenStyle}"/>
|
||||
|
||||
<!-- Default style for TokenizingTextBox -->
|
||||
<Style BasedOn="{StaticResource DefaultTokenizingTextBoxStyle}" TargetType="shuxct:TokenizingTextBox"/>
|
||||
<Style BasedOn="{StaticResource DefaultAutoSuggestTokenBoxStyle}" TargetType="shuxca:AutoSuggestTokenBox"/>
|
||||
|
||||
<Style x:Key="DefaultTokenizingTextBoxStyle" TargetType="shuxct:TokenizingTextBox">
|
||||
<Setter Property="AutoSuggestBoxTextBoxStyle" Value="{StaticResource TokenizingTextBoxTextBoxStyle}"/>
|
||||
<Style x:Key="DefaultAutoSuggestTokenBoxStyle" TargetType="shuxca:AutoSuggestTokenBox">
|
||||
<Setter Property="AutoSuggestBoxTextBoxStyle" Value="{StaticResource AutoSuggestTokenBoxTextBoxStyle}"/>
|
||||
<Setter Property="Foreground" Value="{ThemeResource TextControlForeground}"/>
|
||||
<Setter Property="Background" Value="{ThemeResource TextControlBackground}"/>
|
||||
<Setter Property="BorderBrush" Value="{ThemeResource TextControlBorderBrush}"/>
|
||||
@@ -33,7 +31,7 @@
|
||||
<Setter Property="TabNavigation" Value="Once"/>
|
||||
<win:Setter Property="IsSwipeEnabled" Value="False"/>
|
||||
<Setter Property="CornerRadius" Value="{ThemeResource ControlCornerRadius}"/>
|
||||
<Setter Property="Padding" Value="{StaticResource TokenizingTextBoxPadding}"/>
|
||||
<Setter Property="Padding" Value="{StaticResource AutoSuggestTokenBoxPadding}"/>
|
||||
<Setter Property="SelectionMode" Value="Extended"/>
|
||||
<Setter Property="ScrollViewer.HorizontalScrollBarVisibility" Value="Disabled"/>
|
||||
<Setter Property="ScrollViewer.VerticalScrollBarVisibility" Value="Auto"/>
|
||||
@@ -44,7 +42,7 @@
|
||||
<Setter Property="ScrollViewer.ZoomMode" Value="Disabled"/>
|
||||
<win:Setter Property="ScrollViewer.IsDeferredScrollingEnabled" Value="False"/>
|
||||
<Setter Property="ScrollViewer.BringIntoViewOnFocusChange" Value="True"/>
|
||||
<Setter Property="TokenSpacing" Value="{StaticResource TokenizingTextBoxTokenSpacing}"/>
|
||||
<Setter Property="TokenSpacing" Value="{StaticResource AutoSuggestTokenBoxTokenSpacing}"/>
|
||||
<Setter Property="UseSystemFocusVisuals" Value="{StaticResource UseSystemFocusVisuals}"/>
|
||||
<Setter Property="IsItemClickEnabled" Value="True"/>
|
||||
<win:Setter Property="ItemContainerTransitions">
|
||||
@@ -56,18 +54,18 @@
|
||||
<Setter.Value>
|
||||
<ItemsPanelTemplate>
|
||||
<cwc:WrapPanel
|
||||
cw:FrameworkElementExtensions.AncestorType="shuxct:TokenizingTextBox"
|
||||
cw:FrameworkElementExtensions.AncestorType="shuxca:AutoSuggestTokenBox"
|
||||
HorizontalSpacing="{Binding (cw:FrameworkElementExtensions.Ancestor).TokenSpacing, RelativeSource={RelativeSource Self}}"
|
||||
StretchChild="Last"
|
||||
VerticalSpacing="{Binding (cw:FrameworkElementExtensions.Ancestor).TokenSpacing, RelativeSource={RelativeSource Self}}"/>
|
||||
</ItemsPanelTemplate>
|
||||
</Setter.Value>
|
||||
</Setter>
|
||||
<Setter Property="ItemContainerStyleSelector" Value="{StaticResource TokenizingTextBoxStyleSelector}"/>
|
||||
<Setter Property="Template" Value="{StaticResource TokenizingTextBoxTemplate}"/>
|
||||
<Setter Property="ItemContainerStyleSelector" Value="{StaticResource AutoSuggestTokenBoxStyleSelector}"/>
|
||||
<Setter Property="Template" Value="{StaticResource AutoSuggestTokenBoxTemplate}"/>
|
||||
</Style>
|
||||
|
||||
<ControlTemplate x:Key="TokenizingTextBoxTemplate" TargetType="shuxct:TokenizingTextBox">
|
||||
<ControlTemplate x:Key="AutoSuggestTokenBoxTemplate" TargetType="shuxca:AutoSuggestTokenBox">
|
||||
<Grid Name="RootPanel">
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="Auto"/>
|
||||
@@ -77,7 +75,7 @@
|
||||
|
||||
<Grid.ContextFlyout>
|
||||
<MenuFlyout>
|
||||
<MenuFlyoutItem Command="{Binding SelectAllTokensAndTextCommand, RelativeSource={RelativeSource Mode=TemplatedParent}}" Text="{shuxm:ResourceString Name=ControlTokenizingTextBoxSelectAllMenuItem}"/>
|
||||
<MenuFlyoutItem Command="{Binding SelectAllTokensAndTextCommand, RelativeSource={RelativeSource Mode=TemplatedParent}}" Text="{shuxm:ResourceString Name=ControlAutoSuggestTokenBoxSelectAllMenuItem}"/>
|
||||
</MenuFlyout>
|
||||
</Grid.ContextFlyout>
|
||||
|
||||
@@ -125,7 +123,7 @@
|
||||
VerticalScrollMode="{TemplateBinding ScrollViewer.VerticalScrollMode}"
|
||||
ZoomMode="{TemplateBinding ScrollViewer.ZoomMode}">
|
||||
|
||||
<ItemsPresenter Margin="{StaticResource TokenizingTextBoxPresenterMargin}" Padding="{TemplateBinding Padding}"/>
|
||||
<ItemsPresenter Margin="{StaticResource AutoSuggestTokenBoxPresenterMargin}" Padding="{TemplateBinding Padding}"/>
|
||||
</ScrollViewer>
|
||||
|
||||
<ContentPresenter
|
||||
@@ -6,32 +6,32 @@ using Microsoft.UI.Xaml.Automation.Peers;
|
||||
using Microsoft.UI.Xaml.Automation.Provider;
|
||||
using Microsoft.UI.Xaml.Controls;
|
||||
|
||||
namespace Snap.Hutao.UI.Xaml.Control.TokenizingTextBox;
|
||||
namespace Snap.Hutao.UI.Xaml.Control.AutoSuggestBox;
|
||||
|
||||
internal class TokenizingTextBoxAutomationPeer : ListViewBaseAutomationPeer, IValueProvider
|
||||
internal class AutoSuggestTokenBoxAutomationPeer : ListViewBaseAutomationPeer, IValueProvider
|
||||
{
|
||||
public TokenizingTextBoxAutomationPeer(TokenizingTextBox owner)
|
||||
public AutoSuggestTokenBoxAutomationPeer(AutoSuggestTokenBox owner)
|
||||
: base(owner)
|
||||
{
|
||||
}
|
||||
|
||||
public bool IsReadOnly => !OwningTokenizingTextBox.IsEnabled;
|
||||
public bool IsReadOnly => !OwningAutoSuggestTokenBox.IsEnabled;
|
||||
|
||||
public string Value => OwningTokenizingTextBox.Text;
|
||||
public string Value => OwningAutoSuggestTokenBox.Text;
|
||||
|
||||
private TokenizingTextBox OwningTokenizingTextBox
|
||||
private AutoSuggestTokenBox OwningAutoSuggestTokenBox
|
||||
{
|
||||
get => (TokenizingTextBox)Owner;
|
||||
get => (AutoSuggestTokenBox)Owner;
|
||||
}
|
||||
|
||||
public void SetValue(string value)
|
||||
{
|
||||
if (IsReadOnly)
|
||||
{
|
||||
throw new ElementNotEnabledException($"Could not set the value of the {nameof(TokenizingTextBox)} ");
|
||||
throw new ElementNotEnabledException($"Could not set the value of the {nameof(AutoSuggestTokenBox)} ");
|
||||
}
|
||||
|
||||
OwningTokenizingTextBox.Text = value;
|
||||
OwningAutoSuggestTokenBox.Text = value;
|
||||
}
|
||||
|
||||
protected override string GetClassNameCore()
|
||||
@@ -41,13 +41,13 @@ internal class TokenizingTextBoxAutomationPeer : ListViewBaseAutomationPeer, IVa
|
||||
|
||||
protected override string GetNameCore()
|
||||
{
|
||||
string name = OwningTokenizingTextBox.Name;
|
||||
string name = OwningAutoSuggestTokenBox.Name;
|
||||
if (!string.IsNullOrWhiteSpace(name))
|
||||
{
|
||||
return name;
|
||||
}
|
||||
|
||||
name = AutomationProperties.GetName(OwningTokenizingTextBox);
|
||||
name = AutomationProperties.GetName(OwningAutoSuggestTokenBox);
|
||||
return !string.IsNullOrWhiteSpace(name) ? name : base.GetNameCore();
|
||||
}
|
||||
|
||||
@@ -62,7 +62,7 @@ internal class TokenizingTextBoxAutomationPeer : ListViewBaseAutomationPeer, IVa
|
||||
|
||||
protected override IList<AutomationPeer> GetChildrenCore()
|
||||
{
|
||||
TokenizingTextBox owner = OwningTokenizingTextBox;
|
||||
AutoSuggestTokenBox owner = OwningAutoSuggestTokenBox;
|
||||
|
||||
ItemCollection items = owner.Items;
|
||||
if (items.Count <= 0)
|
||||
@@ -73,7 +73,7 @@ internal class TokenizingTextBoxAutomationPeer : ListViewBaseAutomationPeer, IVa
|
||||
List<AutomationPeer> peers = new(items.Count);
|
||||
for (int i = 0; i < items.Count; i++)
|
||||
{
|
||||
if (owner.ContainerFromIndex(i) is TokenizingTextBoxItem element)
|
||||
if (owner.ContainerFromIndex(i) is AutoSuggestTokenBoxItem element)
|
||||
{
|
||||
peers.Add(FromElement(element) ?? CreatePeerForElement(element));
|
||||
}
|
||||
@@ -10,14 +10,14 @@ using Microsoft.UI.Xaml.Input;
|
||||
using Windows.Foundation;
|
||||
using Windows.System;
|
||||
|
||||
namespace Snap.Hutao.UI.Xaml.Control.TokenizingTextBox;
|
||||
namespace Snap.Hutao.UI.Xaml.Control.AutoSuggestBox;
|
||||
|
||||
[DependencyProperty("ClearButtonStyle", typeof(Style))]
|
||||
[DependencyProperty("Owner", typeof(TokenizingTextBox))]
|
||||
[DependencyProperty("Owner", typeof(AutoSuggestTokenBox))]
|
||||
[TemplatePart(Name = TokenRemoveButton, Type = typeof(ButtonBase))] //// Token case
|
||||
[TemplatePart(Name = TextAutoSuggestBox, Type = typeof(Microsoft.UI.Xaml.Controls.AutoSuggestBox))] //// String case
|
||||
[TemplatePart(Name = TextTokensCounter, Type = typeof(Microsoft.UI.Xaml.Controls.TextBlock))]
|
||||
internal partial class TokenizingTextBoxItem : ListViewItem
|
||||
internal partial class AutoSuggestTokenBoxItem : ListViewItem
|
||||
{
|
||||
private const string TokenRemoveButton = nameof(TokenRemoveButton);
|
||||
private const string TextAutoSuggestBox = nameof(TextAutoSuggestBox);
|
||||
@@ -29,16 +29,16 @@ internal partial class TokenizingTextBoxItem : ListViewItem
|
||||
private bool isSelectedFocusOnFirstCharacter;
|
||||
private bool isSelectedFocusOnLastCharacter;
|
||||
|
||||
public TokenizingTextBoxItem()
|
||||
public AutoSuggestTokenBoxItem()
|
||||
{
|
||||
DefaultStyleKey = typeof(TokenizingTextBoxItem);
|
||||
DefaultStyleKey = typeof(AutoSuggestTokenBoxItem);
|
||||
|
||||
KeyDown += OnKeyDown;
|
||||
}
|
||||
|
||||
public event TypedEventHandler<TokenizingTextBoxItem, RoutedEventArgs>? AutoSuggestTextBoxLoaded;
|
||||
public event TypedEventHandler<AutoSuggestTokenBoxItem, RoutedEventArgs>? AutoSuggestTextBoxLoaded;
|
||||
|
||||
public event TypedEventHandler<TokenizingTextBoxItem, RoutedEventArgs>? ClearAllAction;
|
||||
public event TypedEventHandler<AutoSuggestTokenBoxItem, RoutedEventArgs>? ClearAllAction;
|
||||
|
||||
public Microsoft.UI.Xaml.Controls.AutoSuggestBox? AutoSuggestBox
|
||||
{
|
||||
@@ -146,7 +146,7 @@ internal partial class TokenizingTextBoxItem : ListViewItem
|
||||
{
|
||||
fis.FontSize = 16;
|
||||
|
||||
if (Owner.TryFindResource("TokenizingTextBoxIconFontSize", out object? fontSizeObj) && fontSizeObj is double fontSize)
|
||||
if (Owner.TryFindResource("AutoSuggestTokenBoxIconFontSize", out object? fontSizeObj) && fontSizeObj is double fontSize)
|
||||
{
|
||||
fis.FontSize = fontSize;
|
||||
}
|
||||
@@ -173,14 +173,14 @@ internal partial class TokenizingTextBoxItem : ListViewItem
|
||||
private void OnASBGotFocus(object sender, RoutedEventArgs e)
|
||||
{
|
||||
// Verify if the usual behavior of clearing token selection is required
|
||||
if (!Owner.PauseTokenClearOnFocus && !TokenizingTextBox.IsShiftPressed)
|
||||
if (!Owner.PauseTokenClearOnFocus && !AutoSuggestTokenBox.IsShiftPressed)
|
||||
{
|
||||
Owner.DeselectAll();
|
||||
}
|
||||
|
||||
Owner.PauseTokenClearOnFocus = false;
|
||||
|
||||
VisualStateManager.GoToState(Owner, TokenizingTextBox.FocusedState, true);
|
||||
VisualStateManager.GoToState(Owner, AutoSuggestTokenBox.FocusedState, true);
|
||||
}
|
||||
|
||||
private void OnASBLoaded(object sender, RoutedEventArgs e)
|
||||
@@ -216,17 +216,17 @@ internal partial class TokenizingTextBoxItem : ListViewItem
|
||||
|
||||
private void OnASBLostFocus(object sender, RoutedEventArgs e)
|
||||
{
|
||||
VisualStateManager.GoToState(Owner, TokenizingTextBox.UnfocusedState, true);
|
||||
VisualStateManager.GoToState(Owner, AutoSuggestTokenBox.UnfocusedState, true);
|
||||
}
|
||||
|
||||
private void OnASBPointerEntered(object sender, PointerRoutedEventArgs e)
|
||||
{
|
||||
VisualStateManager.GoToState(Owner, TokenizingTextBox.PointerOverState, true);
|
||||
VisualStateManager.GoToState(Owner, AutoSuggestTokenBox.PointerOverState, true);
|
||||
}
|
||||
|
||||
private void OnASBPointerExited(object sender, PointerRoutedEventArgs e)
|
||||
{
|
||||
VisualStateManager.GoToState(Owner, TokenizingTextBox.NormalState, true);
|
||||
VisualStateManager.GoToState(Owner, AutoSuggestTokenBox.NormalState, true);
|
||||
}
|
||||
|
||||
private void OnASBQuerySubmitted(Microsoft.UI.Xaml.Controls.AutoSuggestBox sender, AutoSuggestBoxQuerySubmittedEventArgs args)
|
||||
@@ -316,7 +316,7 @@ internal partial class TokenizingTextBoxItem : ListViewItem
|
||||
{
|
||||
if (Owner.SelectPreviousItem(this))
|
||||
{
|
||||
if (!TokenizingTextBox.IsShiftPressed)
|
||||
if (!AutoSuggestTokenBox.IsShiftPressed)
|
||||
{
|
||||
// Clear any text box selection
|
||||
autoSuggestTextBox.SelectionLength = 0;
|
||||
@@ -333,7 +333,7 @@ internal partial class TokenizingTextBoxItem : ListViewItem
|
||||
{
|
||||
if (Owner.SelectNextItem(this))
|
||||
{
|
||||
if (!TokenizingTextBox.IsShiftPressed)
|
||||
if (!AutoSuggestTokenBox.IsShiftPressed)
|
||||
{
|
||||
// Clear any text box selection
|
||||
autoSuggestTextBox.SelectionLength = 0;
|
||||
@@ -343,7 +343,7 @@ internal partial class TokenizingTextBoxItem : ListViewItem
|
||||
}
|
||||
}
|
||||
}
|
||||
else if (e.Key is VirtualKey.A && TokenizingTextBox.IsControlPressed)
|
||||
else if (e.Key is VirtualKey.A && AutoSuggestTokenBox.IsControlPressed)
|
||||
{
|
||||
// Need to provide this shortcut from the textbox only, as ListViewBase will do it for us on token.
|
||||
Owner.SelectAllTokensAndText();
|
||||
@@ -352,7 +352,7 @@ internal partial class TokenizingTextBoxItem : ListViewItem
|
||||
|
||||
private void OnAutoSuggestTextBoxSelectionChanged(object sender, RoutedEventArgs args)
|
||||
{
|
||||
if (!(IsAllSelected || TokenizingTextBox.IsShiftPressed || Owner.IsClearingForClick))
|
||||
if (!(IsAllSelected || AutoSuggestTokenBox.IsShiftPressed || Owner.IsClearingForClick))
|
||||
{
|
||||
Owner.DeselectAllTokensAndText(this);
|
||||
}
|
||||
@@ -2,7 +2,7 @@
|
||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:muxc="using:Microsoft.UI.Xaml.Controls"
|
||||
xmlns:shuxct="using:Snap.Hutao.UI.Xaml.Control.TokenizingTextBox"
|
||||
xmlns:shuxca="using:Snap.Hutao.UI.Xaml.Control.AutoSuggestBox"
|
||||
xmlns:shuxm="using:Snap.Hutao.UI.Xaml.Markup"
|
||||
xmlns:win="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
|
||||
|
||||
@@ -75,16 +75,16 @@
|
||||
<!--<Thickness x:Key="ButtonPadding">8,4,8,5</Thickness> Not sure if we'll also need this later-->
|
||||
<Thickness x:Key="TextControlThemePadding">10,3,6,6</Thickness>
|
||||
<!-- Need local copy of this, as including WinUI overrides this to something that adds too much padding for our inner box -->
|
||||
<x:Double x:Key="TokenizingTextBoxIconFontSize">10</x:Double>
|
||||
<x:Double x:Key="AutoSuggestTokenBoxIconFontSize">10</x:Double>
|
||||
|
||||
<Thickness x:Key="TokenItemPadding">8,4,4,4</Thickness>
|
||||
<Thickness x:Key="TokenizingTextBoxItemPresenterMargin">0,-2,0,1</Thickness>
|
||||
<HorizontalAlignment x:Key="TokenizingTextBoxItemHorizontalContentAlignment">Center</HorizontalAlignment>
|
||||
<VerticalAlignment x:Key="TokenizingTextBoxItemVerticalContentAlignment">Center</VerticalAlignment>
|
||||
<Thickness x:Key="AutoSuggestTokenBoxItemPresenterMargin">0,-2,0,1</Thickness>
|
||||
<HorizontalAlignment x:Key="AutoSuggestTokenBoxItemHorizontalContentAlignment">Center</HorizontalAlignment>
|
||||
<VerticalAlignment x:Key="AutoSuggestTokenBoxItemVerticalContentAlignment">Center</VerticalAlignment>
|
||||
|
||||
<CornerRadius x:Key="PopupOverlayCornerRadius">0,0,0,8</CornerRadius>
|
||||
|
||||
<Style x:Key="TokenizingTextBoxDeleteButtonStyle" TargetType="Button">
|
||||
<Style x:Key="AutoSuggestTokenBoxDeleteButtonStyle" TargetType="Button">
|
||||
<Setter Property="Template">
|
||||
<Setter.Value>
|
||||
<ControlTemplate TargetType="Button">
|
||||
@@ -96,14 +96,14 @@
|
||||
BorderThickness="{TemplateBinding BorderThickness}"
|
||||
CornerRadius="{ThemeResource ControlCornerRadius}">
|
||||
<!-- FontSize is ignored here, see https://github.com/microsoft/microsoft-ui-xaml/issues/2568 -->
|
||||
<!-- Set in code-behind link:TokenizingTextBoxItem.AutoSuggestBox.cs#L104 -->
|
||||
<!-- Set in code-behind link:AutoSuggestTokenBoxItem.AutoSuggestBox.cs#L104 -->
|
||||
<TextBlock
|
||||
x:Name="GlyphElement"
|
||||
HorizontalAlignment="Center"
|
||||
VerticalAlignment="Center"
|
||||
win:AutomationProperties.AccessibilityView="Raw"
|
||||
FontFamily="{ThemeResource SymbolThemeFontFamily}"
|
||||
FontSize="{ThemeResource TokenizingTextBoxIconFontSize}"
|
||||
FontSize="{ThemeResource AutoSuggestTokenBoxIconFontSize}"
|
||||
FontStyle="Normal"
|
||||
Foreground="{ThemeResource TextControlButtonForeground}"
|
||||
Text=""/>
|
||||
@@ -153,7 +153,7 @@
|
||||
</Setter>
|
||||
</Style>
|
||||
|
||||
<Style x:Name="TokenizingTextBoxQueryButtonStyle" TargetType="Button">
|
||||
<Style x:Name="AutoSuggestTokenBoxQueryButtonStyle" TargetType="Button">
|
||||
<Setter Property="Template">
|
||||
<Setter.Value>
|
||||
<ControlTemplate TargetType="Button">
|
||||
@@ -231,7 +231,7 @@
|
||||
|
||||
<!-- Inner TextBox Style with removed borders to look like part of the outer textbox facade we've setup -->
|
||||
<Style
|
||||
x:Key="TokenizingTextBoxTextBoxStyle"
|
||||
x:Key="AutoSuggestTokenBoxTextBoxStyle"
|
||||
BasedOn="{StaticResource AutoSuggestBoxTextBoxStyle}"
|
||||
TargetType="TextBox">
|
||||
<Setter Property="MinWidth" Value="{ThemeResource TextControlThemeMinWidth}"/>
|
||||
@@ -325,7 +325,7 @@
|
||||
CornerRadius="{TemplateBinding CornerRadius}"
|
||||
FontSize="{TemplateBinding FontSize}"
|
||||
IsTabStop="False"
|
||||
Style="{StaticResource TokenizingTextBoxDeleteButtonStyle}"
|
||||
Style="{StaticResource AutoSuggestTokenBoxDeleteButtonStyle}"
|
||||
Visibility="Collapsed"/>
|
||||
|
||||
<TextBlock
|
||||
@@ -351,7 +351,7 @@
|
||||
CornerRadius="{TemplateBinding CornerRadius}"
|
||||
FontSize="{TemplateBinding FontSize}"
|
||||
IsTabStop="False"
|
||||
Style="{StaticResource TokenizingTextBoxQueryButtonStyle}"/>
|
||||
Style="{StaticResource AutoSuggestTokenBoxQueryButtonStyle}"/>
|
||||
|
||||
<VisualStateManager.VisualStateGroups>
|
||||
<VisualStateGroup x:Name="CommonStates">
|
||||
@@ -431,7 +431,7 @@
|
||||
</Setter>
|
||||
</Style>
|
||||
|
||||
<Style x:Key="TokenizingTextBoxItemTextStyle" TargetType="shuxct:TokenizingTextBoxItem">
|
||||
<Style x:Key="AutoSuggestTokenBoxItemTextStyle" TargetType="shuxca:AutoSuggestTokenBoxItem">
|
||||
<Setter Property="Background" Value="{ThemeResource SystemControlBackgroundChromeMediumLowBrush}"/>
|
||||
<Setter Property="BorderBrush" Value="{ThemeResource SystemControlTransparentBrush}"/>
|
||||
<Setter Property="IsTabStop" Value="False"/>
|
||||
@@ -439,7 +439,7 @@
|
||||
<Setter Property="MinWidth" Value="128"/>
|
||||
<Setter Property="Template">
|
||||
<Setter.Value>
|
||||
<ControlTemplate TargetType="shuxct:TokenizingTextBoxItem">
|
||||
<ControlTemplate TargetType="shuxca:AutoSuggestTokenBoxItem">
|
||||
<AutoSuggestBox
|
||||
Name="TextAutoSuggestBox"
|
||||
DisplayMemberPath="{Binding Path=Owner.DisplayMemberPath, RelativeSource={RelativeSource Mode=TemplatedParent}}"
|
||||
@@ -448,7 +448,7 @@
|
||||
PlaceholderText="{Binding Path=Owner.PlaceholderText, RelativeSource={RelativeSource Mode=TemplatedParent}}"
|
||||
Style="{StaticResource SystemAutoSuggestBoxStyle}"
|
||||
Text="{Binding Text, Mode=TwoWay}"
|
||||
TextBoxStyle="{StaticResource TokenizingTextBoxTextBoxStyle}"
|
||||
TextBoxStyle="{StaticResource AutoSuggestTokenBoxTextBoxStyle}"
|
||||
TextMemberPath="{Binding Path=Owner.TextMemberPath, RelativeSource={RelativeSource Mode=TemplatedParent}}"
|
||||
UpdateTextOnSelect="False"/>
|
||||
</ControlTemplate>
|
||||
@@ -524,10 +524,10 @@
|
||||
|
||||
|
||||
|
||||
<Style x:Key="TokenizingTextBoxItemTokenStyle" TargetType="shuxct:TokenizingTextBoxItem">
|
||||
<Style x:Key="AutoSuggestTokenBoxItemTokenStyle" TargetType="shuxca:AutoSuggestTokenBoxItem">
|
||||
<Setter Property="ClearButtonStyle" Value="{StaticResource SubtleButtonStyle}"/>
|
||||
<Setter Property="HorizontalContentAlignment" Value="{StaticResource TokenizingTextBoxItemHorizontalContentAlignment}"/>
|
||||
<Setter Property="VerticalContentAlignment" Value="{StaticResource TokenizingTextBoxItemVerticalContentAlignment}"/>
|
||||
<Setter Property="HorizontalContentAlignment" Value="{StaticResource AutoSuggestTokenBoxItemHorizontalContentAlignment}"/>
|
||||
<Setter Property="VerticalContentAlignment" Value="{StaticResource AutoSuggestTokenBoxItemVerticalContentAlignment}"/>
|
||||
<!--<Setter Property="HorizontalAlignment" Value="Center" />-->
|
||||
<Setter Property="VerticalAlignment" Value="Center"/>
|
||||
<Setter Property="FontFamily" Value="{ThemeResource ContentControlThemeFontFamily}"/>
|
||||
@@ -546,7 +546,7 @@
|
||||
<Setter Property="FontSize" Value="{ThemeResource ControlContentThemeFontSize}"/>
|
||||
<Setter Property="Template">
|
||||
<Setter.Value>
|
||||
<ControlTemplate TargetType="shuxct:TokenizingTextBoxItem">
|
||||
<ControlTemplate TargetType="shuxca:AutoSuggestTokenBoxItem">
|
||||
<Grid
|
||||
x:Name="PART_RootGrid"
|
||||
Height="{TemplateBinding Height}"
|
||||
@@ -572,8 +572,8 @@
|
||||
<MenuFlyoutItem
|
||||
Command="{Binding Owner.RemoveItemCommand, RelativeSource={RelativeSource Mode=TemplatedParent}}"
|
||||
CommandParameter="{Binding RelativeSource={RelativeSource Mode=TemplatedParent}}"
|
||||
Text="{shuxm:ResourceString Name=ControlTokenizingTextBoxRemoveMenuItem}"/>
|
||||
<MenuFlyoutItem Command="{Binding Owner.SelectAllTokensAndTextCommand, RelativeSource={RelativeSource Mode=TemplatedParent}}" Text="{shuxm:ResourceString Name=ControlTokenizingTextBoxSelectAllMenuItem}"/>
|
||||
Text="{shuxm:ResourceString Name=ControlAutoSuggestTokenBoxRemoveMenuItem}"/>
|
||||
<MenuFlyoutItem Command="{Binding Owner.SelectAllTokensAndTextCommand, RelativeSource={RelativeSource Mode=TemplatedParent}}" Text="{shuxm:ResourceString Name=ControlAutoSuggestTokenBoxSelectAllMenuItem}"/>
|
||||
</MenuFlyout>
|
||||
</Grid.ContextFlyout>
|
||||
<!-- Content -->
|
||||
@@ -666,8 +666,8 @@
|
||||
</Setter>
|
||||
</Style>
|
||||
|
||||
<!-- Default style for TokenizingTextBoxItem -->
|
||||
<Style BasedOn="{StaticResource TokenizingTextBoxItemTokenStyle}" TargetType="shuxct:TokenizingTextBoxItem"/>
|
||||
<!-- Default style for AutoSuggestTokenBoxItem -->
|
||||
<Style BasedOn="{StaticResource AutoSuggestTokenBoxItemTokenStyle}" TargetType="shuxca:AutoSuggestTokenBoxItem"/>
|
||||
|
||||
<Style x:Key="SubtleButtonStyle" TargetType="Button">
|
||||
<Setter Property="Background" Value="{ThemeResource SubtleFillColorTransparent}"/>
|
||||
@@ -4,9 +4,9 @@
|
||||
using Microsoft.UI.Xaml;
|
||||
using Microsoft.UI.Xaml.Controls;
|
||||
|
||||
namespace Snap.Hutao.UI.Xaml.Control.TokenizingTextBox;
|
||||
namespace Snap.Hutao.UI.Xaml.Control.AutoSuggestBox;
|
||||
|
||||
internal class TokenizingTextBoxStyleSelector : StyleSelector
|
||||
internal class AutoSuggestTokenBoxStyleSelector : StyleSelector
|
||||
{
|
||||
public Style TokenStyle { get; set; } = default!;
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// Copyright (c) DGP Studio. All rights reserved.
|
||||
// Licensed under the MIT license.
|
||||
|
||||
namespace Snap.Hutao.UI.Xaml.Control.TokenizingTextBox;
|
||||
namespace Snap.Hutao.UI.Xaml.Control.AutoSuggestBox;
|
||||
|
||||
internal interface ITokenStringContainer
|
||||
{
|
||||
@@ -6,7 +6,7 @@ using System.Collections;
|
||||
using System.Collections.ObjectModel;
|
||||
using System.Collections.Specialized;
|
||||
|
||||
namespace Snap.Hutao.UI.Xaml.Control.TokenizingTextBox;
|
||||
namespace Snap.Hutao.UI.Xaml.Control.AutoSuggestBox;
|
||||
|
||||
internal sealed class InterspersedObservableCollection : IList, IEnumerable<object>, INotifyCollectionChanged
|
||||
{
|
||||
@@ -3,7 +3,7 @@
|
||||
|
||||
using Microsoft.UI.Xaml;
|
||||
|
||||
namespace Snap.Hutao.UI.Xaml.Control.TokenizingTextBox;
|
||||
namespace Snap.Hutao.UI.Xaml.Control.AutoSuggestBox;
|
||||
|
||||
[DependencyProperty("Text", typeof(string))]
|
||||
internal sealed partial class PretokenStringContainer : DependencyObject, ITokenStringContainer
|
||||
@@ -3,7 +3,7 @@
|
||||
|
||||
using CommunityToolkit.Common.Deferred;
|
||||
|
||||
namespace Snap.Hutao.UI.Xaml.Control.TokenizingTextBox;
|
||||
namespace Snap.Hutao.UI.Xaml.Control.AutoSuggestBox;
|
||||
|
||||
internal sealed class TokenItemAddingEventArgs : DeferredCancelEventArgs
|
||||
{
|
||||
@@ -3,11 +3,11 @@
|
||||
|
||||
using CommunityToolkit.Common.Deferred;
|
||||
|
||||
namespace Snap.Hutao.UI.Xaml.Control.TokenizingTextBox;
|
||||
namespace Snap.Hutao.UI.Xaml.Control.AutoSuggestBox;
|
||||
|
||||
internal sealed class TokenItemRemovingEventArgs : DeferredCancelEventArgs
|
||||
{
|
||||
public TokenItemRemovingEventArgs(object item, TokenizingTextBoxItem token)
|
||||
public TokenItemRemovingEventArgs(object item, AutoSuggestTokenBoxItem token)
|
||||
{
|
||||
Item = item;
|
||||
Token = token;
|
||||
@@ -15,5 +15,5 @@ internal sealed class TokenItemRemovingEventArgs : DeferredCancelEventArgs
|
||||
|
||||
public object Item { get; private set; }
|
||||
|
||||
public TokenizingTextBoxItem Token { get; private set; }
|
||||
public AutoSuggestTokenBoxItem Token { get; private set; }
|
||||
}
|
||||
@@ -1,902 +0,0 @@
|
||||
// Copyright (c) DGP Studio. All rights reserved.
|
||||
// Licensed under the MIT license.
|
||||
|
||||
using CommunityToolkit.WinUI;
|
||||
using CommunityToolkit.WinUI.Helpers;
|
||||
using Microsoft.UI.Dispatching;
|
||||
using Microsoft.UI.Input;
|
||||
using Microsoft.UI.Xaml;
|
||||
using Microsoft.UI.Xaml.Automation.Peers;
|
||||
using Microsoft.UI.Xaml.Controls;
|
||||
using Microsoft.UI.Xaml.Input;
|
||||
using Windows.ApplicationModel.DataTransfer;
|
||||
using Windows.Foundation.Metadata;
|
||||
using Windows.UI.Core;
|
||||
using VirtualKey = Windows.System.VirtualKey;
|
||||
|
||||
namespace Snap.Hutao.UI.Xaml.Control.TokenizingTextBox;
|
||||
|
||||
[DependencyProperty("AutoSuggestBoxStyle", typeof(Style))]
|
||||
[DependencyProperty("AutoSuggestBoxTextBoxStyle", typeof(Style))]
|
||||
[DependencyProperty("MaximumTokens", typeof(int), -1, nameof(OnMaximumTokensChanged))]
|
||||
[DependencyProperty("PlaceholderText", typeof(string))]
|
||||
[DependencyProperty("QueryIcon", typeof(IconSource))]
|
||||
[DependencyProperty("SuggestedItemsSource", typeof(object))]
|
||||
[DependencyProperty("SuggestedItemTemplate", typeof(DataTemplate))]
|
||||
[DependencyProperty("SuggestedItemTemplateSelector", typeof(DataTemplateSelector))]
|
||||
[DependencyProperty("SuggestedItemContainerStyle", typeof(Style))]
|
||||
[DependencyProperty("TabNavigateBackOnArrow", typeof(bool), false)]
|
||||
[DependencyProperty("Text", typeof(string), default, nameof(OnTextPropertyChanged))]
|
||||
[DependencyProperty("TextMemberPath", typeof(string))]
|
||||
[DependencyProperty("TokenItemTemplate", typeof(DataTemplate))]
|
||||
[DependencyProperty("TokenItemTemplateSelector", typeof(DataTemplateSelector))]
|
||||
[DependencyProperty("TokenDelimiter", typeof(string), " ")]
|
||||
[DependencyProperty("TokenSpacing", typeof(double))]
|
||||
[TemplatePart(Name = NormalState, Type = typeof(VisualState))]
|
||||
[TemplatePart(Name = PointerOverState, Type = typeof(VisualState))]
|
||||
[TemplatePart(Name = FocusedState, Type = typeof(VisualState))]
|
||||
[TemplatePart(Name = UnfocusedState, Type = typeof(VisualState))]
|
||||
[TemplatePart(Name = MaxReachedState, Type = typeof(VisualState))]
|
||||
[TemplatePart(Name = MaxUnreachedState, Type = typeof(VisualState))]
|
||||
internal partial class TokenizingTextBox : ListViewBase
|
||||
{
|
||||
public const string NormalState = "Normal";
|
||||
public const string PointerOverState = "PointerOver";
|
||||
public const string FocusedState = "Focused";
|
||||
public const string UnfocusedState = "Unfocused";
|
||||
public const string MaxReachedState = "MaxReached";
|
||||
public const string MaxUnreachedState = "MaxUnreached";
|
||||
|
||||
private InterspersedObservableCollection innerItemsSource;
|
||||
private ITokenStringContainer currentTextEdit; // Don't update this directly outside of initialization, use UpdateCurrentTextEdit Method
|
||||
private ITokenStringContainer lastTextEdit;
|
||||
|
||||
public TokenizingTextBox()
|
||||
{
|
||||
innerItemsSource = [];
|
||||
currentTextEdit = lastTextEdit = new PretokenStringContainer(true);
|
||||
innerItemsSource.Insert(innerItemsSource.Count, currentTextEdit);
|
||||
ItemsSource = innerItemsSource;
|
||||
|
||||
DefaultStyleKey = typeof(TokenizingTextBox);
|
||||
|
||||
RegisterPropertyChangedCallback(ItemsSourceProperty, OnItemsSourceChanged);
|
||||
PreviewKeyDown += OnPreviewKeyDown;
|
||||
PreviewKeyUp += OnPreviewKeyUp;
|
||||
CharacterReceived += OnCharacterReceived;
|
||||
ItemClick += OnItemClick;
|
||||
}
|
||||
|
||||
private enum MoveDirection
|
||||
{
|
||||
Next,
|
||||
Previous,
|
||||
}
|
||||
|
||||
public static bool IsControlPressed
|
||||
{
|
||||
get => InputKeyboardSource.GetKeyStateForCurrentThread(VirtualKey.Control).HasFlag(CoreVirtualKeyStates.Down);
|
||||
}
|
||||
|
||||
public static bool IsShiftPressed
|
||||
{
|
||||
get => InputKeyboardSource.GetKeyStateForCurrentThread(VirtualKey.Shift).HasFlag(CoreVirtualKeyStates.Down);
|
||||
}
|
||||
|
||||
public static bool IsXamlRootAvailable { get; } = ApiInformation.IsPropertyPresent("Windows.UI.Xaml.UIElement", "XamlRoot");
|
||||
|
||||
public bool IsClearingForClick { get; set; }
|
||||
|
||||
public bool PauseTokenClearOnFocus { get; set; }
|
||||
|
||||
public string SelectedTokenText
|
||||
{
|
||||
get => PrepareSelectionForClipboard();
|
||||
}
|
||||
|
||||
public void AddToken(object data, bool atEnd = false)
|
||||
{
|
||||
if (MaximumTokens >= 0 && IsTokenLimitReached())
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (data is string str)
|
||||
{
|
||||
TokenItemAddingEventArgs tiaea = new(str);
|
||||
OnTokenItemAdding(this, tiaea);
|
||||
|
||||
if (tiaea.Cancel)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (tiaea.Item is not null)
|
||||
{
|
||||
data = tiaea.Item;
|
||||
}
|
||||
}
|
||||
|
||||
// Custom: Avoid add same token
|
||||
if (innerItemsSource.Contains(data))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// If we've been typing in the last box, just add this to the end of our collection
|
||||
if (atEnd || currentTextEdit == lastTextEdit)
|
||||
{
|
||||
innerItemsSource.InsertAt(innerItemsSource.Count - 1, data);
|
||||
}
|
||||
else
|
||||
{
|
||||
// Otherwise, we'll insert before our current box
|
||||
ITokenStringContainer edit = currentTextEdit;
|
||||
int index = innerItemsSource.IndexOf(edit);
|
||||
|
||||
// Insert our new data item at the location of our textbox
|
||||
innerItemsSource.InsertAt(index, data);
|
||||
|
||||
// Remove our textbox
|
||||
innerItemsSource.Remove(edit);
|
||||
}
|
||||
|
||||
TokenizingTextBoxItem last = (TokenizingTextBoxItem)ContainerFromItem(lastTextEdit);
|
||||
ArgumentNullException.ThrowIfNull(last.AutoSuggestTextBox);
|
||||
last.AutoSuggestTextBox.Focus(FocusState.Keyboard);
|
||||
|
||||
OnTokenItemAdded(this, data);
|
||||
UpdatePlaceholderVisibility();
|
||||
}
|
||||
|
||||
public void Clear()
|
||||
{
|
||||
while (innerItemsSource.Count > 1)
|
||||
{
|
||||
if (ContainerFromItem(innerItemsSource[0]) is TokenizingTextBoxItem container)
|
||||
{
|
||||
if (!RemoveToken(container, innerItemsSource[0]))
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Text = string.Empty;
|
||||
}
|
||||
|
||||
public void DeselectAllTokensAndText(TokenizingTextBoxItem? ignoreItem = default)
|
||||
{
|
||||
this.DeselectAll();
|
||||
ClearAllTextSelections(ignoreItem);
|
||||
}
|
||||
|
||||
public bool IsTokenLimitReached()
|
||||
{
|
||||
return innerItemsSource.ItemsSource.Count >= MaximumTokens;
|
||||
}
|
||||
|
||||
public void RefreshTokenCounter()
|
||||
{
|
||||
if (ContainerFromIndex(Items.Count - 1) is not TokenizingTextBoxItem { AutoSuggestBox: { } autoSuggestBox, AutoSuggestTextBox: { } autoSuggestTextBox })
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (autoSuggestBox.FindDescendant("TextTokensCounter") is not Microsoft.UI.Xaml.Controls.TextBlock maxTokensCounter)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
int currentTokens = innerItemsSource.ItemsSource.Count;
|
||||
int maxTokens = MaximumTokens;
|
||||
|
||||
maxTokensCounter.Text = $"{currentTokens}/{maxTokens}";
|
||||
maxTokensCounter.Visibility = Visibility.Visible;
|
||||
|
||||
string targetState = IsTokenLimitReached()
|
||||
? MaxReachedState
|
||||
: MaxUnreachedState;
|
||||
|
||||
VisualStateManager.GoToState(autoSuggestTextBox, targetState, true);
|
||||
}
|
||||
|
||||
public void RemoveAllSelectedTokens()
|
||||
{
|
||||
while (SelectedItems.Count > 0)
|
||||
{
|
||||
if (ContainerFromItem(SelectedItems[0]) is TokenizingTextBoxItem container)
|
||||
{
|
||||
if (IndexFromContainer(container) != Items.Count - 1)
|
||||
{
|
||||
// if its a text box, remove any selected text, and if its then empty remove the container, unless its focused
|
||||
if (SelectedItems[0] is ITokenStringContainer)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(container.AutoSuggestTextBox);
|
||||
TextBox astb = container.AutoSuggestTextBox;
|
||||
|
||||
// grab any selected text
|
||||
string tempStr = astb.SelectionStart is 0
|
||||
? string.Empty
|
||||
: astb.Text[..astb.SelectionStart];
|
||||
tempStr += astb.SelectionStart + astb.SelectionLength < astb.Text.Length
|
||||
? astb.Text[(astb.SelectionStart + astb.SelectionLength)..]
|
||||
: string.Empty;
|
||||
|
||||
if (tempStr.Length is 0)
|
||||
{
|
||||
RemoveToken(container);
|
||||
}
|
||||
else
|
||||
{
|
||||
astb.Text = tempStr;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
RemoveToken(container);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (SelectedItems.Count is 1)
|
||||
{
|
||||
// Only remains the default textbox.
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[Command("SelectAllTokensAndTextCommand")]
|
||||
public void SelectAllTokensAndText()
|
||||
{
|
||||
void SelectAllTokensAndTextCore()
|
||||
{
|
||||
this.SelectAllSafe();
|
||||
|
||||
// need to synchronize the select all and the focus behavior on the text box
|
||||
// because there is no way to identify that the focus has been set from this point
|
||||
// to avoid instantly clearing the selection of tokens
|
||||
PauseTokenClearOnFocus = true;
|
||||
|
||||
foreach (object? item in Items)
|
||||
{
|
||||
if (item is not ITokenStringContainer)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
// grab any selected text
|
||||
if (ContainerFromItem(item) is TokenizingTextBoxItem pretoken)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(pretoken.AutoSuggestTextBox);
|
||||
pretoken.AutoSuggestTextBox.SelectionStart = 0;
|
||||
pretoken.AutoSuggestTextBox.SelectionLength = pretoken.AutoSuggestTextBox.Text.Length;
|
||||
}
|
||||
}
|
||||
|
||||
if (ContainerFromIndex(Items.Count - 1) is TokenizingTextBoxItem container)
|
||||
{
|
||||
container.Focus(FocusState.Programmatic);
|
||||
}
|
||||
}
|
||||
|
||||
_ = DispatcherQueue.EnqueueAsync(SelectAllTokensAndTextCore, DispatcherQueuePriority.Normal);
|
||||
}
|
||||
|
||||
public bool SelectNextItem(TokenizingTextBoxItem item)
|
||||
{
|
||||
return SelectNewItem(item, 1, i => i < Items.Count - 1);
|
||||
}
|
||||
|
||||
public bool SelectPreviousItem(TokenizingTextBoxItem item)
|
||||
{
|
||||
return SelectNewItem(item, -1, i => i > 0);
|
||||
}
|
||||
|
||||
public virtual void OnQuerySubmitted(Microsoft.UI.Xaml.Controls.AutoSuggestBox sender, AutoSuggestBoxQuerySubmittedEventArgs args)
|
||||
{
|
||||
}
|
||||
|
||||
public virtual void OnSuggestionsChosen(Microsoft.UI.Xaml.Controls.AutoSuggestBox sender, AutoSuggestBoxSuggestionChosenEventArgs args)
|
||||
{
|
||||
}
|
||||
|
||||
public virtual void OnTextChanged(Microsoft.UI.Xaml.Controls.AutoSuggestBox sender, AutoSuggestBoxTextChangedEventArgs args)
|
||||
{
|
||||
}
|
||||
|
||||
public virtual void OnTokenItemAdded(TokenizingTextBox sender, object args)
|
||||
{
|
||||
RefreshTokenCounter();
|
||||
}
|
||||
|
||||
public virtual void OnTokenItemAdding(TokenizingTextBox sender, TokenItemAddingEventArgs args)
|
||||
{
|
||||
}
|
||||
|
||||
public virtual void OnTokenItemRemoved(TokenizingTextBox sender, object args)
|
||||
{
|
||||
RefreshTokenCounter();
|
||||
}
|
||||
|
||||
public virtual void OnTokenItemRemoving(TokenizingTextBox sender, TokenItemRemovingEventArgs args)
|
||||
{
|
||||
}
|
||||
|
||||
protected void UpdateCurrentTextEdit(ITokenStringContainer edit)
|
||||
{
|
||||
currentTextEdit = edit;
|
||||
|
||||
Text = edit.Text; // Update our text property.
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
protected override DependencyObject GetContainerForItemOverride()
|
||||
{
|
||||
return new TokenizingTextBoxItem();
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
protected override bool IsItemItsOwnContainerOverride(object item)
|
||||
{
|
||||
return item is TokenizingTextBoxItem;
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
protected override AutomationPeer OnCreateAutomationPeer()
|
||||
{
|
||||
return new TokenizingTextBoxAutomationPeer(this);
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
protected override void PrepareContainerForItemOverride(DependencyObject element, object item)
|
||||
{
|
||||
base.PrepareContainerForItemOverride(element, item);
|
||||
|
||||
if (element is TokenizingTextBoxItem tokenItem)
|
||||
{
|
||||
tokenItem.Owner = this;
|
||||
|
||||
tokenItem.ContentTemplateSelector = TokenItemTemplateSelector;
|
||||
tokenItem.ContentTemplate = TokenItemTemplate;
|
||||
|
||||
tokenItem.ClearAllAction -= OnItemClearAllAction;
|
||||
tokenItem.ClearAllAction += OnItemClearAllAction;
|
||||
|
||||
tokenItem.GotFocus -= OnItemGotFocus;
|
||||
tokenItem.GotFocus += OnItemGotFocus;
|
||||
|
||||
tokenItem.LostFocus -= OnItemLostFocus;
|
||||
tokenItem.LostFocus += OnItemLostFocus;
|
||||
}
|
||||
}
|
||||
|
||||
private static void OnMaximumTokensChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
|
||||
{
|
||||
if (d is TokenizingTextBox { MaximumTokens: >= 0 } ttb && e.NewValue is int newMaxTokens)
|
||||
{
|
||||
int 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 (int i = tokenCount; i > tokenCount - tokensToRemove; --i)
|
||||
{
|
||||
if (ttb.innerItemsSource.ItemsSource[i - 1] is { } token)
|
||||
{
|
||||
// Force remove the items. No warning and no option to cancel.
|
||||
ttb.innerItemsSource.Remove(token);
|
||||
ttb.OnTokenItemRemoved(ttb, token);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void OnTextPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
|
||||
{
|
||||
if (d is TokenizingTextBox { currentTextEdit: { } } ttb)
|
||||
{
|
||||
if (e.NewValue is string newValue)
|
||||
{
|
||||
ttb.currentTextEdit.Text = newValue;
|
||||
|
||||
// Notify inner container of text change, see issue #4749
|
||||
if (ttb.ContainerFromItem(ttb.currentTextEdit) is TokenizingTextBoxItem item)
|
||||
{
|
||||
item.UpdateText(newValue);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void ClearAllTextSelections(TokenizingTextBoxItem? ignoreItem)
|
||||
{
|
||||
// Clear any selection in the text box
|
||||
foreach (object? item in Items)
|
||||
{
|
||||
if (item is not ITokenStringContainer)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (ContainerFromItem(item) is TokenizingTextBoxItem container)
|
||||
{
|
||||
if (container != ignoreItem)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(container.AutoSuggestTextBox);
|
||||
container.AutoSuggestTextBox.SelectionLength = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void CopySelectedToClipboard()
|
||||
{
|
||||
DataPackage dataPackage = new()
|
||||
{
|
||||
RequestedOperation = DataPackageOperation.Copy,
|
||||
};
|
||||
|
||||
string tokenString = PrepareSelectionForClipboard();
|
||||
|
||||
if (!string.IsNullOrEmpty(tokenString))
|
||||
{
|
||||
dataPackage.SetText(tokenString);
|
||||
Clipboard.SetContent(dataPackage);
|
||||
}
|
||||
}
|
||||
|
||||
private void FocusPrimaryAutoSuggestBox()
|
||||
{
|
||||
if (Items.Count > 0)
|
||||
{
|
||||
if (ContainerFromIndex(Items.Count - 1) is TokenizingTextBoxItem container)
|
||||
{
|
||||
container.Focus(FocusState.Programmatic);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private TokenizingTextBoxItem? GetCurrentContainerItem()
|
||||
{
|
||||
return IsXamlRootAvailable && XamlRoot is not null
|
||||
? FocusManager.GetFocusedElement(XamlRoot) as TokenizingTextBoxItem
|
||||
: FocusManager.GetFocusedElement() as TokenizingTextBoxItem;
|
||||
}
|
||||
|
||||
private object GetFocusedElement()
|
||||
{
|
||||
return IsXamlRootAvailable && XamlRoot is not null
|
||||
? FocusManager.GetFocusedElement(XamlRoot)
|
||||
: FocusManager.GetFocusedElement();
|
||||
}
|
||||
|
||||
private bool MoveFocusAndSelection(MoveDirection direction)
|
||||
{
|
||||
bool ret = false;
|
||||
|
||||
if (GetCurrentContainerItem() is { } currentContainerItem)
|
||||
{
|
||||
object? currentItem = ItemFromContainer(currentContainerItem);
|
||||
int previousIndex = Items.IndexOf(currentItem);
|
||||
int index = previousIndex;
|
||||
|
||||
switch (direction)
|
||||
{
|
||||
case MoveDirection.Previous:
|
||||
if (previousIndex > 0)
|
||||
{
|
||||
index -= 1;
|
||||
break;
|
||||
}
|
||||
|
||||
if (TabNavigateBackOnArrow)
|
||||
{
|
||||
FocusManager.TryMoveFocus(FocusNavigationDirection.Previous, new()
|
||||
{
|
||||
SearchRoot = XamlRoot.Content,
|
||||
});
|
||||
}
|
||||
|
||||
ret = true;
|
||||
|
||||
break;
|
||||
case MoveDirection.Next:
|
||||
if (previousIndex < Items.Count - 1)
|
||||
{
|
||||
index += 1;
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
// Only do stuff if the index is actually changing
|
||||
if (index != previousIndex)
|
||||
{
|
||||
if (ContainerFromIndex(index) is TokenizingTextBoxItem newItem)
|
||||
{
|
||||
// Check for the new item being a text control.
|
||||
// this must happen before focus is set to avoid seeing the caret
|
||||
// jump in come cases
|
||||
if (Items[index] is ITokenStringContainer && !IsShiftPressed)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(newItem.AutoSuggestTextBox);
|
||||
newItem.AutoSuggestTextBox.SelectionLength = 0;
|
||||
newItem.AutoSuggestTextBox.SelectionStart = direction switch
|
||||
{
|
||||
MoveDirection.Previous => newItem.AutoSuggestTextBox.Text.Length,
|
||||
MoveDirection.Next => 0,
|
||||
_ => throw new NotSupportedException(),
|
||||
};
|
||||
}
|
||||
|
||||
newItem.Focus(FocusState.Keyboard);
|
||||
|
||||
// if no control keys are selected then the selection also becomes just this item
|
||||
if (IsShiftPressed)
|
||||
{
|
||||
// What we do here depends on where the selection started
|
||||
// if the previous item is between the start and new position then we add the new item to the selected range
|
||||
// if the new item is between the start and the previous position then we remove the previous position
|
||||
int newDistance = Math.Abs(SelectedIndex - index);
|
||||
int oldDistance = Math.Abs(SelectedIndex - previousIndex);
|
||||
|
||||
if (newDistance > oldDistance)
|
||||
{
|
||||
SelectedItems.Add(Items[index]);
|
||||
}
|
||||
else
|
||||
{
|
||||
SelectedItems.Remove(Items[previousIndex]);
|
||||
}
|
||||
}
|
||||
else if (!IsControlPressed)
|
||||
{
|
||||
SelectedIndex = index;
|
||||
|
||||
// This looks like a bug in the underlying ListViewBase control.
|
||||
// Might need to be reviewed if the base behavior is fixed
|
||||
// When two consecutive items are selected and the navigation moves between them,
|
||||
// the first time that happens the old focused item is not unselected
|
||||
if (SelectedItems.Count > 1)
|
||||
{
|
||||
SelectedItems.Clear();
|
||||
SelectedIndex = index;
|
||||
}
|
||||
}
|
||||
|
||||
ret = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
private void OnCharacterReceived(UIElement sender, CharacterReceivedRoutedEventArgs args)
|
||||
{
|
||||
if (ContainerFromItem(currentTextEdit) is TokenizingTextBoxItem container && !(GetFocusedElement().Equals(container.AutoSuggestTextBox) || char.IsControl(args.Character)))
|
||||
{
|
||||
if (SelectedItems.Count > 0)
|
||||
{
|
||||
int index = innerItemsSource.IndexOf(SelectedItems.First());
|
||||
|
||||
RemoveAllSelectedTokens();
|
||||
|
||||
void RemoveOldItems()
|
||||
{
|
||||
// If we're before the last textbox and it's empty, redirect focus to that one instead
|
||||
if (index == innerItemsSource.Count - 1 && string.IsNullOrWhiteSpace(lastTextEdit.Text))
|
||||
{
|
||||
if (ContainerFromItem(lastTextEdit) is TokenizingTextBoxItem lastContainer)
|
||||
{
|
||||
lastContainer.UseCharacterAsUser = true;
|
||||
|
||||
lastTextEdit.Text = string.Empty + args.Character;
|
||||
UpdateCurrentTextEdit(lastTextEdit);
|
||||
|
||||
ArgumentNullException.ThrowIfNull(lastContainer.AutoSuggestTextBox);
|
||||
lastContainer.AutoSuggestTextBox.SelectionStart = 1;
|
||||
lastContainer.AutoSuggestTextBox.Focus(FocusState.Keyboard);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
// Otherwise, create a new textbox for this text.
|
||||
UpdateCurrentTextEdit(new PretokenStringContainer((string.Empty + args.Character).Trim()));
|
||||
innerItemsSource.Insert(index, currentTextEdit);
|
||||
|
||||
void Containerization()
|
||||
{
|
||||
if (ContainerFromIndex(index) is TokenizingTextBoxItem newContainer)
|
||||
{
|
||||
newContainer.UseCharacterAsUser = true;
|
||||
|
||||
void WaitForLoad(object s, RoutedEventArgs eargs)
|
||||
{
|
||||
if (newContainer.AutoSuggestTextBox is not null)
|
||||
{
|
||||
newContainer.AutoSuggestTextBox.SelectionStart = 1;
|
||||
newContainer.AutoSuggestTextBox.Focus(FocusState.Keyboard);
|
||||
}
|
||||
|
||||
newContainer.AutoSuggestTextBoxLoaded -= WaitForLoad;
|
||||
}
|
||||
|
||||
newContainer.AutoSuggestTextBoxLoaded += WaitForLoad;
|
||||
}
|
||||
}
|
||||
|
||||
// Need to wait for containerization
|
||||
_ = DispatcherQueue.EnqueueAsync(Containerization, DispatcherQueuePriority.Normal);
|
||||
}
|
||||
}
|
||||
|
||||
// Wait for removal of old items
|
||||
_ = DispatcherQueue.EnqueueAsync(RemoveOldItems, DispatcherQueuePriority.Normal);
|
||||
}
|
||||
else
|
||||
{
|
||||
// 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[^1] is ITokenStringContainer textEdit)
|
||||
{
|
||||
if (ContainerFromIndex(Items.Count - 1) is TokenizingTextBoxItem last) // Should be our last text box
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(last.AutoSuggestTextBox);
|
||||
string text = last.AutoSuggestTextBox.Text;
|
||||
int selectionStart = last.AutoSuggestTextBox.SelectionStart;
|
||||
int position = Math.Min(selectionStart, text.Length);
|
||||
textEdit.Text = text[..position] + args.Character + text[position..];
|
||||
|
||||
last.AutoSuggestTextBox.SelectionStart = position + 1;
|
||||
last.AutoSuggestTextBox.Focus(FocusState.Keyboard);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void OnItemClearAllAction(TokenizingTextBoxItem sender, RoutedEventArgs args)
|
||||
{
|
||||
int newSelectedIndex = SelectedRanges.Count > 0
|
||||
? SelectedRanges[0].FirstIndex - 1
|
||||
: -1;
|
||||
|
||||
RemoveAllSelectedTokens();
|
||||
|
||||
SelectedIndex = newSelectedIndex;
|
||||
|
||||
if (newSelectedIndex is -1)
|
||||
{
|
||||
newSelectedIndex = Items.Count - 1;
|
||||
}
|
||||
|
||||
// focus the item prior to the first selected item
|
||||
if (ContainerFromIndex(newSelectedIndex) is TokenizingTextBoxItem container)
|
||||
{
|
||||
container.Focus(FocusState.Keyboard);
|
||||
}
|
||||
}
|
||||
|
||||
private void OnItemClick(object sender, ItemClickEventArgs e)
|
||||
{
|
||||
if (!IsControlPressed)
|
||||
{
|
||||
IsClearingForClick = true;
|
||||
ClearAllTextSelections(default);
|
||||
}
|
||||
}
|
||||
|
||||
private void OnItemGotFocus(object sender, RoutedEventArgs e)
|
||||
{
|
||||
if (sender is TokenizingTextBoxItem { AutoSuggestBox: { } autoSuggestBox, Content: ITokenStringContainer text } item)
|
||||
{
|
||||
UpdateCurrentTextEdit(text);
|
||||
|
||||
// Custom: Show all items when focus on the textbox
|
||||
OnTextChanged(autoSuggestBox, new());
|
||||
}
|
||||
}
|
||||
|
||||
private void OnItemLostFocus(object sender, RoutedEventArgs e)
|
||||
{
|
||||
// Keep track of our currently focused textbox
|
||||
if (sender is TokenizingTextBoxItem { Content: ITokenStringContainer text } && string.IsNullOrWhiteSpace(text.Text) && text != lastTextEdit)
|
||||
{
|
||||
// We're leaving an inner textbox that's blank, so we'll remove it
|
||||
innerItemsSource.Remove(text);
|
||||
|
||||
UpdateCurrentTextEdit(lastTextEdit);
|
||||
|
||||
UpdatePlaceholderVisibility();
|
||||
}
|
||||
}
|
||||
|
||||
private void OnItemsSourceChanged(DependencyObject sender, DependencyProperty dp)
|
||||
{
|
||||
// If we're given a different ItemsSource, we need to wrap that collection in our helper class.
|
||||
if (ItemsSource is { } and not InterspersedObservableCollection)
|
||||
{
|
||||
innerItemsSource = new(ItemsSource);
|
||||
|
||||
if (MaximumTokens >= 0 && IsTokenLimitReached())
|
||||
{
|
||||
// Reduce down to below the max as necessary.
|
||||
int endCount = MaximumTokens > 0 ? MaximumTokens : 0;
|
||||
for (int i = innerItemsSource.ItemsSource.Count - 1; i >= endCount; --i)
|
||||
{
|
||||
innerItemsSource.Remove(innerItemsSource[i]);
|
||||
}
|
||||
}
|
||||
|
||||
// Add our text box at the end of items and set its default value to our initial text, fix for #4749
|
||||
currentTextEdit = lastTextEdit = new PretokenStringContainer(true) { Text = Text };
|
||||
innerItemsSource.Insert(innerItemsSource.Count, currentTextEdit);
|
||||
ItemsSource = innerItemsSource;
|
||||
}
|
||||
}
|
||||
|
||||
private void OnPreviewKeyDown(object sender, KeyRoutedEventArgs e)
|
||||
{
|
||||
switch (e.Key)
|
||||
{
|
||||
case VirtualKey.C:
|
||||
if (IsControlPressed)
|
||||
{
|
||||
CopySelectedToClipboard();
|
||||
e.Handled = true;
|
||||
return;
|
||||
}
|
||||
|
||||
break;
|
||||
|
||||
case VirtualKey.X:
|
||||
if (IsControlPressed)
|
||||
{
|
||||
CopySelectedToClipboard();
|
||||
|
||||
// now clear all selected tokens and text, or all if none are selected
|
||||
RemoveAllSelectedTokens();
|
||||
}
|
||||
|
||||
break;
|
||||
|
||||
// For moving between tokens
|
||||
case VirtualKey.Left:
|
||||
e.Handled = MoveFocusAndSelection(MoveDirection.Previous);
|
||||
return;
|
||||
|
||||
case VirtualKey.Right:
|
||||
e.Handled = MoveFocusAndSelection(MoveDirection.Next);
|
||||
return;
|
||||
|
||||
case VirtualKey.A:
|
||||
// modify the select-all behavior to ensure the text in the edit box gets selected.
|
||||
if (IsControlPressed)
|
||||
{
|
||||
SelectAllTokensAndText();
|
||||
e.Handled = true;
|
||||
return;
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private void OnPreviewKeyUp(object sender, KeyRoutedEventArgs e)
|
||||
{
|
||||
switch (e.Key)
|
||||
{
|
||||
case VirtualKey.Escape:
|
||||
// Clear any selection and place the focus back into the text box
|
||||
DeselectAllTokensAndText();
|
||||
FocusPrimaryAutoSuggestBox();
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private string PrepareSelectionForClipboard()
|
||||
{
|
||||
string tokenString = string.Empty;
|
||||
bool addSeparator = false;
|
||||
|
||||
// Copy all items if none selected (and no text selected)
|
||||
foreach (object? item in SelectedItems.Count > 0 ? SelectedItems : Items)
|
||||
{
|
||||
if (addSeparator)
|
||||
{
|
||||
tokenString += TokenDelimiter;
|
||||
}
|
||||
else
|
||||
{
|
||||
addSeparator = true;
|
||||
}
|
||||
|
||||
if (item is ITokenStringContainer)
|
||||
{
|
||||
// grab any selected text
|
||||
if (ContainerFromItem(item) is TokenizingTextBoxItem { AutoSuggestTextBox: { } textBox })
|
||||
{
|
||||
tokenString += textBox.Text.Substring(textBox.SelectionStart, textBox.SelectionLength);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
tokenString += item.ToString();
|
||||
}
|
||||
}
|
||||
|
||||
return tokenString;
|
||||
}
|
||||
|
||||
[Command("RemoveItemCommand")]
|
||||
private void RemoveToken(TokenizingTextBoxItem item)
|
||||
{
|
||||
RemoveToken(item, default);
|
||||
}
|
||||
|
||||
private bool RemoveToken(TokenizingTextBoxItem item, object? data)
|
||||
{
|
||||
data ??= ItemFromContainer(item);
|
||||
|
||||
TokenItemRemovingEventArgs tirea = new(data, item);
|
||||
OnTokenItemRemoving(this, tirea);
|
||||
|
||||
if (tirea.Cancel)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
innerItemsSource.Remove(data);
|
||||
|
||||
OnTokenItemRemoved(this, data);
|
||||
UpdatePlaceholderVisibility();
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private bool SelectNewItem(TokenizingTextBoxItem item, int increment, Func<int, bool> testFunc)
|
||||
{
|
||||
// find the item in the list
|
||||
int currentIndex = IndexFromContainer(item);
|
||||
|
||||
// Select previous token item (if there is one).
|
||||
if (testFunc(currentIndex))
|
||||
{
|
||||
if (ContainerFromItem(Items[currentIndex + increment]) is ListViewItem newItem)
|
||||
{
|
||||
newItem.Focus(FocusState.Keyboard);
|
||||
SelectedItems.Add(Items[currentIndex + increment]);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private void UpdatePlaceholderVisibility()
|
||||
{
|
||||
if (ContainerFromItem(lastTextEdit)?.FindDescendant("PlaceholderTextContentPresenter") is not { } placeholder)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Fix layout issue
|
||||
placeholder.Visibility = Visibility.Collapsed;
|
||||
|
||||
_ = CompositionTargetHelper.ExecuteAfterCompositionRenderingAsync(() =>
|
||||
{
|
||||
int currentTokens = innerItemsSource.ItemsSource.Count;
|
||||
int maxTokens = MaximumTokens;
|
||||
placeholder.Visibility = currentTokens >= maxTokens
|
||||
? Visibility.Collapsed
|
||||
: Visibility.Visible;
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -335,20 +335,11 @@
|
||||
MaximumTokens="5"
|
||||
PlaceholderText="{shuxm:ResourceString Name=ViewPageWiKiAvatarAutoSuggestBoxPlaceHolder}"
|
||||
QueryIcon="{cw:FontIconSource Glyph=}"
|
||||
Style="{StaticResource DefaultTokenizingTextBoxStyle}"
|
||||
Style="{StaticResource DefaultAutoSuggestTokenBoxStyle}"
|
||||
SuggestedItemTemplate="{StaticResource TokenTemplate}"
|
||||
SuggestedItemsSource="{Binding AvailableTokens.Values}"
|
||||
Text="{Binding FilterToken, Mode=TwoWay}"
|
||||
TokenItemTemplate="{StaticResource TokenTemplate}">
|
||||
<shuxca:AutoSuggestTokenBox.ItemsPanel>
|
||||
<ItemsPanelTemplate>
|
||||
<cwc:WrapPanel
|
||||
cw:FrameworkElementExtensions.AncestorType="shuxca:AutoSuggestTokenBox"
|
||||
HorizontalSpacing="2"
|
||||
StretchChild="Last"/>
|
||||
</ItemsPanelTemplate>
|
||||
</shuxca:AutoSuggestTokenBox.ItemsPanel>
|
||||
</shuxca:AutoSuggestTokenBox>
|
||||
TokenItemTemplate="{StaticResource TokenTemplate}"/>
|
||||
</AppBarElementContainer>
|
||||
<AppBarButton
|
||||
Command="{Binding CultivateCommand}"
|
||||
|
||||
@@ -197,20 +197,11 @@
|
||||
MaximumTokens="5"
|
||||
PlaceholderText="{shuxm:ResourceString Name=ViewPageWiKiWeaponAutoSuggestBoxPlaceHolder}"
|
||||
QueryIcon="{cw:FontIconSource Glyph=}"
|
||||
Style="{StaticResource DefaultTokenizingTextBoxStyle}"
|
||||
Style="{StaticResource DefaultAutoSuggestTokenBoxStyle}"
|
||||
SuggestedItemTemplate="{StaticResource TokenTemplate}"
|
||||
SuggestedItemsSource="{Binding AvailableTokens.Values}"
|
||||
Text="{Binding FilterToken, Mode=TwoWay}"
|
||||
TokenItemTemplate="{StaticResource TokenTemplate}">
|
||||
<shuxca:AutoSuggestTokenBox.ItemsPanel>
|
||||
<ItemsPanelTemplate>
|
||||
<cwc:WrapPanel
|
||||
cw:FrameworkElementExtensions.AncestorType="shuxca:AutoSuggestTokenBox"
|
||||
HorizontalSpacing="2"
|
||||
StretchChild="Last"/>
|
||||
</ItemsPanelTemplate>
|
||||
</shuxca:AutoSuggestTokenBox.ItemsPanel>
|
||||
</shuxca:AutoSuggestTokenBox>
|
||||
TokenItemTemplate="{StaticResource TokenTemplate}"/>
|
||||
</AppBarElementContainer>
|
||||
<AppBarButton
|
||||
Command="{Binding CultivateCommand}"
|
||||
|
||||
Reference in New Issue
Block a user