Compare commits
7 Commits
08a8a5338f
...
c4ece6e9b7
Author | SHA1 | Date | |
---|---|---|---|
![]() |
c4ece6e9b7 | ||
![]() |
be914e4b2e | ||
![]() |
6f91dacb0c | ||
![]() |
f3ae953772 | ||
![]() |
2daf5b6c1e | ||
![]() |
82594cff34 | ||
![]() |
f62c1f267e |
226
.editorconfig
Normal file
226
.editorconfig
Normal file
@ -0,0 +1,226 @@
|
||||
# Remove the line below if you want to inherit .editorconfig settings from higher directories
|
||||
root = true
|
||||
|
||||
# C# files
|
||||
[*.cs]
|
||||
|
||||
#### Core EditorConfig Options ####
|
||||
|
||||
# Indentation and spacing
|
||||
indent_size = 3
|
||||
indent_style = tab
|
||||
tab_width = 3
|
||||
|
||||
# New line preferences
|
||||
end_of_line = crlf
|
||||
insert_final_newline = false
|
||||
|
||||
#### .NET Coding Conventions ####
|
||||
|
||||
# Organize usings
|
||||
dotnet_separate_import_directive_groups = false
|
||||
dotnet_sort_system_directives_first = false
|
||||
file_header_template = unset
|
||||
|
||||
# this. and Me. preferences
|
||||
dotnet_style_qualification_for_event = false:suggestion
|
||||
dotnet_style_qualification_for_field = false:suggestion
|
||||
dotnet_style_qualification_for_method = false:suggestion
|
||||
dotnet_style_qualification_for_property = false:suggestion
|
||||
|
||||
# Language keywords vs BCL types preferences
|
||||
dotnet_style_predefined_type_for_locals_parameters_members = true:suggestion
|
||||
dotnet_style_predefined_type_for_member_access = true:suggestion
|
||||
|
||||
# Parentheses preferences
|
||||
dotnet_style_parentheses_in_arithmetic_binary_operators = always_for_clarity:suggestion
|
||||
dotnet_style_parentheses_in_other_binary_operators = always_for_clarity:suggestion
|
||||
dotnet_style_parentheses_in_other_operators = never_if_unnecessary:suggestion
|
||||
dotnet_style_parentheses_in_relational_binary_operators = always_for_clarity:suggestion
|
||||
|
||||
# Modifier preferences
|
||||
dotnet_style_require_accessibility_modifiers = for_non_interface_members
|
||||
|
||||
# Expression-level preferences
|
||||
dotnet_style_coalesce_expression = true
|
||||
dotnet_style_collection_initializer = true
|
||||
dotnet_style_explicit_tuple_names = true
|
||||
dotnet_style_namespace_match_folder = true
|
||||
dotnet_style_null_propagation = true
|
||||
dotnet_style_object_initializer = true
|
||||
dotnet_style_operator_placement_when_wrapping = beginning_of_line
|
||||
dotnet_style_prefer_auto_properties = true:suggestion
|
||||
dotnet_style_prefer_compound_assignment = true
|
||||
dotnet_style_prefer_conditional_expression_over_assignment = true:suggestion
|
||||
dotnet_style_prefer_conditional_expression_over_return = true:suggestion
|
||||
dotnet_style_prefer_foreach_explicit_cast_in_source = when_strongly_typed
|
||||
dotnet_style_prefer_inferred_anonymous_type_member_names = true
|
||||
dotnet_style_prefer_inferred_tuple_names = false
|
||||
dotnet_style_prefer_is_null_check_over_reference_equality_method = true
|
||||
dotnet_style_prefer_simplified_boolean_expressions = true
|
||||
dotnet_style_prefer_simplified_interpolation = true
|
||||
|
||||
# Field preferences
|
||||
dotnet_style_readonly_field = true
|
||||
|
||||
# Parameter preferences
|
||||
dotnet_code_quality_unused_parameters = all
|
||||
|
||||
# Suppression preferences
|
||||
dotnet_remove_unnecessary_suppression_exclusions = 0
|
||||
|
||||
# New line preferences
|
||||
dotnet_style_allow_multiple_blank_lines_experimental = false:suggestion
|
||||
dotnet_style_allow_statement_immediately_after_block_experimental = false:suggestion
|
||||
|
||||
#### C# Coding Conventions ####
|
||||
|
||||
# var preferences
|
||||
csharp_style_var_elsewhere = true:warning
|
||||
csharp_style_var_for_built_in_types = true:warning
|
||||
csharp_style_var_when_type_is_apparent = true:warning
|
||||
|
||||
# Expression-bodied members
|
||||
csharp_style_expression_bodied_accessors = when_on_single_line:suggestion
|
||||
csharp_style_expression_bodied_constructors = when_on_single_line:suggestion
|
||||
csharp_style_expression_bodied_indexers = when_on_single_line:suggestion
|
||||
csharp_style_expression_bodied_lambdas = when_on_single_line:suggestion
|
||||
csharp_style_expression_bodied_local_functions = when_on_single_line:suggestion
|
||||
csharp_style_expression_bodied_methods = when_on_single_line:suggestion
|
||||
csharp_style_expression_bodied_operators = when_on_single_line:suggestion
|
||||
csharp_style_expression_bodied_properties = when_on_single_line:suggestion
|
||||
|
||||
# Pattern matching preferences
|
||||
csharp_style_pattern_matching_over_as_with_null_check = true
|
||||
csharp_style_pattern_matching_over_is_with_cast_check = true
|
||||
csharp_style_prefer_extended_property_pattern = true
|
||||
csharp_style_prefer_not_pattern = true
|
||||
csharp_style_prefer_pattern_matching = true:suggestion
|
||||
csharp_style_prefer_switch_expression = true
|
||||
|
||||
# Null-checking preferences
|
||||
csharp_style_conditional_delegate_call = true
|
||||
|
||||
# Modifier preferences
|
||||
csharp_prefer_static_local_function = true
|
||||
csharp_preferred_modifier_order = public,private,protected,internal,static,extern,new,virtual,abstract,sealed,override,readonly,unsafe,volatile,async
|
||||
csharp_style_prefer_readonly_struct = true
|
||||
|
||||
# Code-block preferences
|
||||
csharp_prefer_braces = when_multiline:suggestion
|
||||
csharp_prefer_simple_using_statement = true
|
||||
csharp_style_namespace_declarations = file_scoped:warning
|
||||
csharp_style_prefer_method_group_conversion = true:suggestion
|
||||
csharp_style_prefer_top_level_statements = false:suggestion
|
||||
|
||||
# Expression-level preferences
|
||||
csharp_prefer_simple_default_expression = true
|
||||
csharp_style_deconstructed_variable_declaration = true
|
||||
csharp_style_implicit_object_creation_when_type_is_apparent = true
|
||||
csharp_style_inlined_variable_declaration = true
|
||||
csharp_style_prefer_index_operator = true
|
||||
csharp_style_prefer_local_over_anonymous_function = true
|
||||
csharp_style_prefer_null_check_over_type_check = true
|
||||
csharp_style_prefer_range_operator = true
|
||||
csharp_style_prefer_tuple_swap = true
|
||||
csharp_style_prefer_utf8_string_literals = true
|
||||
csharp_style_throw_expression = true
|
||||
csharp_style_unused_value_assignment_preference = discard_variable
|
||||
csharp_style_unused_value_expression_statement_preference = discard_variable:suggestion
|
||||
|
||||
# 'using' directive preferences
|
||||
csharp_using_directive_placement = outside_namespace:suggestion
|
||||
|
||||
# New line preferences
|
||||
csharp_style_allow_blank_line_after_colon_in_constructor_initializer_experimental = true:suggestion
|
||||
csharp_style_allow_blank_lines_between_consecutive_braces_experimental = false:suggestion
|
||||
csharp_style_allow_embedded_statements_on_same_line_experimental = false:suggestion
|
||||
|
||||
#### C# Formatting Rules ####
|
||||
|
||||
# New line preferences
|
||||
csharp_new_line_before_catch = true
|
||||
csharp_new_line_before_else = true
|
||||
csharp_new_line_before_finally = true
|
||||
csharp_new_line_before_members_in_anonymous_types = true
|
||||
csharp_new_line_before_members_in_object_initializers = true
|
||||
csharp_new_line_before_open_brace = all
|
||||
csharp_new_line_between_query_expression_clauses = true
|
||||
|
||||
# Indentation preferences
|
||||
csharp_indent_block_contents = true
|
||||
csharp_indent_braces = false
|
||||
csharp_indent_case_contents = true
|
||||
csharp_indent_case_contents_when_block = true
|
||||
csharp_indent_labels = no_change
|
||||
csharp_indent_switch_labels = true
|
||||
|
||||
# Space preferences
|
||||
csharp_space_after_cast = false
|
||||
csharp_space_after_colon_in_inheritance_clause = true
|
||||
csharp_space_after_comma = true
|
||||
csharp_space_after_dot = false
|
||||
csharp_space_after_keywords_in_control_flow_statements = true
|
||||
csharp_space_after_semicolon_in_for_statement = true
|
||||
csharp_space_around_binary_operators = before_and_after
|
||||
csharp_space_around_declaration_statements = false
|
||||
csharp_space_before_colon_in_inheritance_clause = true
|
||||
csharp_space_before_comma = false
|
||||
csharp_space_before_dot = false
|
||||
csharp_space_before_open_square_brackets = false
|
||||
csharp_space_before_semicolon_in_for_statement = false
|
||||
csharp_space_between_empty_square_brackets = false
|
||||
csharp_space_between_method_call_empty_parameter_list_parentheses = false
|
||||
csharp_space_between_method_call_name_and_opening_parenthesis = false
|
||||
csharp_space_between_method_call_parameter_list_parentheses = false
|
||||
csharp_space_between_method_declaration_empty_parameter_list_parentheses = false
|
||||
csharp_space_between_method_declaration_name_and_open_parenthesis = false
|
||||
csharp_space_between_method_declaration_parameter_list_parentheses = false
|
||||
csharp_space_between_parentheses = false
|
||||
csharp_space_between_square_brackets = false
|
||||
|
||||
# Wrapping preferences
|
||||
csharp_preserve_single_line_blocks = true
|
||||
csharp_preserve_single_line_statements = true
|
||||
|
||||
#### Naming styles ####
|
||||
|
||||
# Naming rules
|
||||
|
||||
dotnet_naming_rule.interface_should_be_begins_with_i.severity = suggestion
|
||||
dotnet_naming_rule.interface_should_be_begins_with_i.symbols = interface
|
||||
dotnet_naming_rule.interface_should_be_begins_with_i.style = begins_with_i
|
||||
|
||||
dotnet_naming_rule.types_should_be_pascal_case.severity = suggestion
|
||||
dotnet_naming_rule.types_should_be_pascal_case.symbols = types
|
||||
dotnet_naming_rule.types_should_be_pascal_case.style = pascal_case
|
||||
|
||||
dotnet_naming_rule.non_field_members_should_be_pascal_case.severity = suggestion
|
||||
dotnet_naming_rule.non_field_members_should_be_pascal_case.symbols = non_field_members
|
||||
dotnet_naming_rule.non_field_members_should_be_pascal_case.style = pascal_case
|
||||
|
||||
# Symbol specifications
|
||||
|
||||
dotnet_naming_symbols.interface.applicable_kinds = interface
|
||||
dotnet_naming_symbols.interface.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected
|
||||
dotnet_naming_symbols.interface.required_modifiers =
|
||||
|
||||
dotnet_naming_symbols.types.applicable_kinds = class, struct, interface, enum
|
||||
dotnet_naming_symbols.types.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected
|
||||
dotnet_naming_symbols.types.required_modifiers =
|
||||
|
||||
dotnet_naming_symbols.non_field_members.applicable_kinds = property, event, method
|
||||
dotnet_naming_symbols.non_field_members.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected
|
||||
dotnet_naming_symbols.non_field_members.required_modifiers =
|
||||
|
||||
# Naming styles
|
||||
|
||||
dotnet_naming_style.pascal_case.required_prefix =
|
||||
dotnet_naming_style.pascal_case.required_suffix =
|
||||
dotnet_naming_style.pascal_case.word_separator =
|
||||
dotnet_naming_style.pascal_case.capitalization = pascal_case
|
||||
|
||||
dotnet_naming_style.begins_with_i.required_prefix = I
|
||||
dotnet_naming_style.begins_with_i.required_suffix =
|
||||
dotnet_naming_style.begins_with_i.word_separator =
|
||||
dotnet_naming_style.begins_with_i.capitalization = pascal_case
|
@ -1,696 +0,0 @@
|
||||
using Connected.Utilities;
|
||||
using Microsoft.AspNetCore.Components;
|
||||
using Microsoft.AspNetCore.Components.Web;
|
||||
|
||||
namespace Connected.Components;
|
||||
|
||||
public partial class Autocomplete<T> : InputBase<T>, IDisposable
|
||||
{
|
||||
private Func<T, string>? _toStringFunc;
|
||||
private Task _currentSearchTask;
|
||||
private CancellationTokenSource _cancellationTokenSrc;
|
||||
private bool _isOpen;
|
||||
private Timer _timer;
|
||||
private T[] _items;
|
||||
private int _selectedListItemIndex = 0;
|
||||
private IList<int> _enabledItemIndices = new List<int>();
|
||||
private int _itemsReturned; //the number of items returned by the search function
|
||||
int _elementKey = 0;
|
||||
/// <summary>
|
||||
/// This boolean will keep track if the clear function is called too keep the set text function to be called.
|
||||
/// </summary>
|
||||
private bool _isCleared;
|
||||
private Input<string> _elementReference;
|
||||
/// <summary>
|
||||
/// We need a random id for the year items in the year list so we can scroll to the item safely in every DatePicker.
|
||||
/// </summary>
|
||||
private readonly string _componentId = Guid.NewGuid().ToString();
|
||||
|
||||
public Autocomplete()
|
||||
{
|
||||
Adornment = Adornment.End;
|
||||
IconSize = Size.Medium;
|
||||
}
|
||||
|
||||
[Inject]
|
||||
IScrollManager ScrollManager { get; set; }
|
||||
/// <summary>
|
||||
/// User class names for the popover, separated by space
|
||||
/// </summary>
|
||||
[Parameter]
|
||||
public string PopoverClass { get; set; }
|
||||
/// <summary>
|
||||
/// Set the anchor origin point to determen where the popover will open from.
|
||||
/// </summary>
|
||||
[Parameter]
|
||||
public Origin AnchorOrigin { get; set; } = Origin.BottomCenter;
|
||||
/// <summary>
|
||||
/// Sets the transform origin point for the popover.
|
||||
/// </summary>
|
||||
[Parameter]
|
||||
public Origin TransformOrigin { get; set; } = Origin.TopCenter;
|
||||
/// <summary>
|
||||
/// If true, compact vertical padding will be applied to all Autocomplete items.
|
||||
/// </summary>
|
||||
[Parameter]
|
||||
public bool Dense { get; set; }
|
||||
/// <summary>
|
||||
/// The Open Autocomplete Icon
|
||||
/// </summary>
|
||||
[Parameter]
|
||||
public string OpenIcon { get; set; } = Icons.Material.Filled.ArrowDropDown;
|
||||
/// <summary>
|
||||
/// The Close Autocomplete Icon
|
||||
/// </summary>
|
||||
[Parameter]
|
||||
public string CloseIcon { get; set; } = Icons.Material.Filled.ArrowDropUp;
|
||||
/// <summary>
|
||||
/// The maximum height of the Autocomplete when it is open.
|
||||
/// </summary>
|
||||
[Parameter]
|
||||
public int MaxHeight { get; set; } = 300;
|
||||
/// <summary>
|
||||
/// Defines how values are displayed in the drop-down list
|
||||
/// </summary>
|
||||
[Parameter]
|
||||
public Func<T, string>? ToStringFunc
|
||||
{
|
||||
get => _toStringFunc;
|
||||
set
|
||||
{
|
||||
if (_toStringFunc == value)
|
||||
return;
|
||||
|
||||
_toStringFunc = value;
|
||||
|
||||
Converter = new Converter<T>
|
||||
{
|
||||
SetFunc = _toStringFunc ?? (x => x?.ToString()),
|
||||
};
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// Whether to show the progress indicator.
|
||||
/// </summary>
|
||||
[Parameter]
|
||||
public bool ShowProgressIndicator { get; set; } = false;
|
||||
/// <summary>
|
||||
/// The color of the progress indicator.
|
||||
/// </summary>
|
||||
[Parameter]
|
||||
public ThemeColor ProgressIndicatorColor { get; set; } = ThemeColor.Default;
|
||||
private bool IsLoading => _currentSearchTask is not null && !_currentSearchTask.IsCompleted;
|
||||
/// <summary>
|
||||
/// Func that returns a list of items matching the typed text. Provides a cancellation token that
|
||||
/// is marked as cancelled when the user changes the search text or selects a value from the list.
|
||||
/// This can be used to cancel expensive asynchronous work occuring within the SearchFunc itself.
|
||||
/// </summary>
|
||||
[Parameter]
|
||||
public Func<string, CancellationToken, Task<IEnumerable<T>>> SearchFuncWithCancel { get; set; }
|
||||
/// <summary>
|
||||
/// The SearchFunc returns a list of items matching the typed text
|
||||
/// </summary>
|
||||
[Parameter]
|
||||
public Func<string, Task<IEnumerable<T>>> SearchFunc { get; set; }
|
||||
/// <summary>
|
||||
/// Maximum items to display, defaults to 10.
|
||||
/// A null value will display all items.
|
||||
/// </summary>
|
||||
[Parameter]
|
||||
public int? MaxItems { get; set; } = 10;
|
||||
/// <summary>
|
||||
/// Minimum characters to initiate a search
|
||||
/// </summary>
|
||||
[Parameter]
|
||||
public int MinCharacters { get; set; } = 0;
|
||||
/// <summary>
|
||||
/// Reset value if user deletes the text
|
||||
/// </summary>
|
||||
[Parameter]
|
||||
public bool ResetValueOnEmptyText { get; set; } = false;
|
||||
/// <summary>
|
||||
/// If true, clicking the text field will select (highlight) its contents.
|
||||
/// </summary>
|
||||
[Parameter]
|
||||
public bool SelectOnClick { get; set; } = true;
|
||||
/// <summary>
|
||||
/// Debounce interval in milliseconds.
|
||||
/// </summary>
|
||||
[Parameter]
|
||||
public int DebounceInterval { get; set; } = 100;
|
||||
/// <summary>
|
||||
/// Optional presentation template for unselected items
|
||||
/// </summary>
|
||||
[Parameter]
|
||||
public RenderFragment<T> ItemTemplate { get; set; }
|
||||
/// <summary>
|
||||
/// Optional presentation template for the selected item
|
||||
/// </summary>
|
||||
[Parameter]
|
||||
public RenderFragment<T> ItemSelectedTemplate { get; set; }
|
||||
/// <summary>
|
||||
/// Optional presentation template for disabled item
|
||||
/// </summary>
|
||||
[Parameter]
|
||||
public RenderFragment<T> ItemDisabledTemplate { get; set; }
|
||||
/// <summary>
|
||||
/// Optional presentation template for when more items were returned from the Search function than the MaxItems limit
|
||||
/// </summary>
|
||||
[Parameter]
|
||||
public RenderFragment MoreItemsTemplate { get; set; }
|
||||
/// <summary>
|
||||
/// Optional presentation template for when no items were returned from the Search function
|
||||
/// </summary>
|
||||
[Parameter]
|
||||
public RenderFragment NoItemsTemplate { get; set; }
|
||||
/// <summary>
|
||||
/// Optional template for progress indicator
|
||||
/// </summary>
|
||||
[Parameter]
|
||||
public RenderFragment ProgressIndicatorTemplate { get; set; }
|
||||
/// <summary>
|
||||
/// Optional template for showing progress indicator inside the popover
|
||||
/// </summary>
|
||||
[Parameter]
|
||||
public RenderFragment ProgressIndicatorInPopoverTemplate { get; set; }
|
||||
/// <summary>
|
||||
/// On drop-down close override Text with selected Value. This makes it clear to the user
|
||||
/// which list value is currently selected and disallows incomplete values in Text.
|
||||
/// </summary>
|
||||
[Parameter]
|
||||
public bool CoerceText { get; set; } = true;
|
||||
/// <summary>
|
||||
/// If user input is not found by the search func and CoerceValue is set to true the user input
|
||||
/// will be applied to the Value which allows to validate it and display an error message.
|
||||
/// </summary>
|
||||
[Parameter]
|
||||
public bool CoerceValue { get; set; }
|
||||
/// <summary>
|
||||
/// Function to be invoked when checking whether an item should be disabled or not
|
||||
/// </summary>
|
||||
[Parameter]
|
||||
public Func<T, bool> ItemDisabledFunc { get; set; }
|
||||
/// <summary>
|
||||
/// Returns the open state of the drop-down.
|
||||
/// </summary>
|
||||
public bool IsOpen
|
||||
{
|
||||
get => _isOpen;
|
||||
// Note: the setter is protected because it was needed by a user who derived his own autocomplete from this class.
|
||||
// Note: setting IsOpen will not open or close it. Use ToggleMenu() for that.
|
||||
protected set
|
||||
{
|
||||
if (value == _isOpen)
|
||||
return;
|
||||
|
||||
_isOpen = value;
|
||||
|
||||
IsOpenChanged.InvokeAsync(_isOpen).AndForget();
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// An event triggered when the state of IsOpen has changed
|
||||
/// </summary>
|
||||
[Parameter]
|
||||
public EventCallback<bool> IsOpenChanged { get; set; }
|
||||
/// <summary>
|
||||
/// If true, the currently selected item from the drop-down (if it is open) is selected.
|
||||
/// </summary>
|
||||
[Parameter]
|
||||
public bool SelectValueOnTab { get; set; } = false;
|
||||
/// <summary>
|
||||
/// Show clear button.
|
||||
/// </summary>
|
||||
[Parameter]
|
||||
public bool Clearable { get; set; } = false;
|
||||
/// <summary>
|
||||
/// Button click event for clear button. Called after text and value has been cleared.
|
||||
/// </summary>
|
||||
[Parameter]
|
||||
public EventCallback<MouseEventArgs> OnClearButtonClick { get; set; }
|
||||
|
||||
private string CurrentIcon => !string.IsNullOrWhiteSpace(AdornmentIcon) ? AdornmentIcon : _isOpen ? CloseIcon : OpenIcon;
|
||||
|
||||
protected string ClassList()
|
||||
{
|
||||
return new CssBuilder("select")
|
||||
.AddClass(Class)
|
||||
.Build();
|
||||
}
|
||||
|
||||
protected string AutocompleteClassList()
|
||||
{
|
||||
return new CssBuilder("select")
|
||||
.AddClass("autocomplete")
|
||||
.AddClass("width-full", FullWidth)
|
||||
.AddClass("autocomplete--with-progress", ShowProgressIndicator && IsLoading)
|
||||
.Build();
|
||||
}
|
||||
|
||||
protected string CircularProgressClassList()
|
||||
{
|
||||
return new CssBuilder("progress-indicator-circular")
|
||||
.AddClass("progress-indicator-circular--with-adornment", Adornment == Adornment.End)
|
||||
.Build();
|
||||
}
|
||||
|
||||
public async Task SelectOption(T value)
|
||||
{
|
||||
await SetValueAsync(value);
|
||||
|
||||
if (_items is not null)
|
||||
_selectedListItemIndex = Array.IndexOf(_items, value);
|
||||
|
||||
var optionText = GetItemString(value);
|
||||
|
||||
if (!_isCleared)
|
||||
await SetTextAsync(optionText, false);
|
||||
|
||||
_timer?.Dispose();
|
||||
|
||||
IsOpen = false;
|
||||
|
||||
BeginValidate();
|
||||
|
||||
if (!_isCleared)
|
||||
_elementReference?.SetText(optionText);
|
||||
|
||||
_elementReference?.FocusAsync().AndForget();
|
||||
|
||||
StateHasChanged();
|
||||
}
|
||||
/// <summary>
|
||||
/// Toggle the menu (if not disabled or not readonly, and is opened).
|
||||
/// </summary>
|
||||
public async Task ToggleMenu()
|
||||
{
|
||||
if ((Disabled || ReadOnly) && !IsOpen)
|
||||
return;
|
||||
|
||||
await ChangeMenu(!IsOpen);
|
||||
}
|
||||
|
||||
private async Task ChangeMenu(bool open)
|
||||
{
|
||||
if (open)
|
||||
{
|
||||
if (SelectOnClick)
|
||||
await _elementReference.SelectAsync();
|
||||
|
||||
await OnSearchAsync();
|
||||
}
|
||||
else
|
||||
{
|
||||
_timer?.Dispose();
|
||||
|
||||
RestoreScrollPosition();
|
||||
|
||||
await CoerceTextToValue();
|
||||
|
||||
IsOpen = false;
|
||||
|
||||
StateHasChanged();
|
||||
}
|
||||
}
|
||||
|
||||
protected override void OnInitialized()
|
||||
{
|
||||
var text = GetItemString(Value);
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(text))
|
||||
Text = text;
|
||||
}
|
||||
|
||||
protected override void OnAfterRender(bool firstRender)
|
||||
{
|
||||
_isCleared = false;
|
||||
|
||||
base.OnAfterRender(firstRender);
|
||||
}
|
||||
|
||||
protected override Task UpdateTextPropertyAsync(bool updateValue)
|
||||
{
|
||||
_timer?.Dispose();
|
||||
// This keeps the text from being set when clear() was called
|
||||
if (_isCleared)
|
||||
return Task.CompletedTask;
|
||||
|
||||
return base.UpdateTextPropertyAsync(updateValue);
|
||||
}
|
||||
|
||||
protected override async Task UpdateValuePropertyAsync(bool updateText)
|
||||
{
|
||||
_timer?.Dispose();
|
||||
|
||||
if (ResetValueOnEmptyText && string.IsNullOrWhiteSpace(Text))
|
||||
await SetValueAsync(default, updateText);
|
||||
|
||||
if (DebounceInterval <= 0)
|
||||
await OnSearchAsync();
|
||||
else
|
||||
_timer = new Timer(OnTimerComplete, null, DebounceInterval, Timeout.Infinite);
|
||||
}
|
||||
|
||||
private void OnTimerComplete(object stateInfo)
|
||||
{
|
||||
InvokeAsync(OnSearchAsync);
|
||||
}
|
||||
private void CancelToken()
|
||||
{
|
||||
try
|
||||
{
|
||||
_cancellationTokenSrc?.Cancel();
|
||||
}
|
||||
catch
|
||||
{
|
||||
}
|
||||
|
||||
_cancellationTokenSrc = new CancellationTokenSource();
|
||||
}
|
||||
/// <remarks>
|
||||
/// This async method needs to return a task and be awaited in order for
|
||||
/// unit tests that trigger this method to work correctly.
|
||||
/// </remarks>
|
||||
private async Task OnSearchAsync()
|
||||
{
|
||||
if (MinCharacters > 0 && (string.IsNullOrWhiteSpace(Text) || Text.Length < MinCharacters))
|
||||
{
|
||||
IsOpen = false;
|
||||
StateHasChanged();
|
||||
return;
|
||||
}
|
||||
|
||||
IEnumerable<T> searchedItems = Array.Empty<T>();
|
||||
CancelToken();
|
||||
|
||||
try
|
||||
{
|
||||
if (ProgressIndicatorInPopoverTemplate is not null)
|
||||
IsOpen = true;
|
||||
|
||||
var searchTask = SearchFuncWithCancel is not null ? SearchFuncWithCancel(Text, _cancellationTokenSrc.Token) : SearchFunc(Text);
|
||||
|
||||
_currentSearchTask = searchTask;
|
||||
|
||||
StateHasChanged();
|
||||
|
||||
searchedItems = await searchTask ?? Array.Empty<T>();
|
||||
}
|
||||
catch (TaskCanceledException)
|
||||
{
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Console.WriteLine($"The search function failed to return results: {e.Message}");
|
||||
}
|
||||
|
||||
_itemsReturned = searchedItems.Count();
|
||||
|
||||
if (MaxItems.HasValue)
|
||||
searchedItems = searchedItems.Take(MaxItems.Value);
|
||||
|
||||
_items = searchedItems.ToArray();
|
||||
_enabledItemIndices = _items.Select((item, idx) => (item, idx)).Where(tuple => ItemDisabledFunc?.Invoke(tuple.item) != true).Select(tuple => tuple.idx).ToList();
|
||||
_selectedListItemIndex = _enabledItemIndices.Any() ? _enabledItemIndices.First() : -1;
|
||||
|
||||
IsOpen = true;
|
||||
|
||||
if (_items?.Length == 0)
|
||||
{
|
||||
await CoerceValueToText();
|
||||
|
||||
StateHasChanged();
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
StateHasChanged();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Clears the autocomplete's text
|
||||
/// </summary>
|
||||
public async Task Clear()
|
||||
{
|
||||
_isCleared = true;
|
||||
IsOpen = false;
|
||||
|
||||
await SetTextAsync(string.Empty, updateValue: false);
|
||||
await CoerceValueToText();
|
||||
|
||||
if (_elementReference is not null)
|
||||
await _elementReference.SetText(string.Empty);
|
||||
|
||||
_timer?.Dispose();
|
||||
|
||||
StateHasChanged();
|
||||
}
|
||||
|
||||
protected override async void ResetValue()
|
||||
{
|
||||
await Clear();
|
||||
base.ResetValue();
|
||||
}
|
||||
|
||||
private string GetItemString(T item)
|
||||
{
|
||||
if (item is null)
|
||||
return string.Empty;
|
||||
try
|
||||
{
|
||||
return Converter.Set(item);
|
||||
}
|
||||
catch (NullReferenceException) { }
|
||||
|
||||
return "null";
|
||||
}
|
||||
|
||||
internal virtual async Task OnInputKeyDown(KeyboardEventArgs args)
|
||||
{
|
||||
switch (args.Key)
|
||||
{
|
||||
case "Tab":
|
||||
// NOTE: We need to catch Tab in Keydown because a tab will move focus to the next element and thus
|
||||
// in OnInputKeyUp we'd never get the tab key
|
||||
if (!IsOpen)
|
||||
return;
|
||||
if (SelectValueOnTab)
|
||||
await OnEnterKey();
|
||||
else
|
||||
IsOpen = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
internal virtual async Task OnInputKeyUp(KeyboardEventArgs args)
|
||||
{
|
||||
switch (args.Key)
|
||||
{
|
||||
case "Enter":
|
||||
case "NumpadEnter":
|
||||
if (!IsOpen)
|
||||
await ToggleMenu();
|
||||
else
|
||||
await OnEnterKey();
|
||||
|
||||
break;
|
||||
case "ArrowDown":
|
||||
if (!IsOpen)
|
||||
await ToggleMenu();
|
||||
else
|
||||
{
|
||||
var increment = _enabledItemIndices.ElementAtOrDefault(_enabledItemIndices.IndexOf(_selectedListItemIndex) + 1) - _selectedListItemIndex;
|
||||
|
||||
await SelectNextItem(increment < 0 ? 1 : increment);
|
||||
}
|
||||
|
||||
break;
|
||||
case "ArrowUp":
|
||||
if (args.AltKey)
|
||||
await ChangeMenu(false);
|
||||
else if (!IsOpen)
|
||||
await ToggleMenu();
|
||||
else
|
||||
{
|
||||
var decrement = _selectedListItemIndex - _enabledItemIndices.ElementAtOrDefault(_enabledItemIndices.IndexOf(_selectedListItemIndex) - 1);
|
||||
await SelectNextItem(-(decrement < 0 ? 1 : decrement));
|
||||
}
|
||||
|
||||
break;
|
||||
case "Escape":
|
||||
await ChangeMenu(false);
|
||||
|
||||
break;
|
||||
case "Tab":
|
||||
await Task.Delay(1);
|
||||
|
||||
if (!IsOpen)
|
||||
return;
|
||||
|
||||
if (SelectValueOnTab)
|
||||
await OnEnterKey();
|
||||
else
|
||||
await ToggleMenu();
|
||||
|
||||
break;
|
||||
case "Backspace":
|
||||
if (args.CtrlKey && args.ShiftKey)
|
||||
Reset();
|
||||
break;
|
||||
}
|
||||
|
||||
base.InvokeKeyUp(args);
|
||||
}
|
||||
|
||||
private ValueTask SelectNextItem(int increment)
|
||||
{
|
||||
if (increment == 0 || _items is null || !_items.Any() || !_enabledItemIndices.Any())
|
||||
return ValueTask.CompletedTask;
|
||||
// if we are at the end, or the beginning we just do an rollover
|
||||
_selectedListItemIndex = Math.Clamp(value: (10 * _items.Length + _selectedListItemIndex + increment) % _items.Length, min: 0, max: _items.Length - 1);
|
||||
|
||||
return ScrollToListItem(_selectedListItemIndex);
|
||||
}
|
||||
/// <summary>
|
||||
/// Scroll to a specific item index in the Autocomplete list of items.
|
||||
/// </summary>
|
||||
/// <param name="index">the index to scroll to</param>
|
||||
public ValueTask ScrollToListItem(int index)
|
||||
{
|
||||
var id = GetListItemId(index);
|
||||
//id of the scrolled element
|
||||
return ScrollManager.ScrollToListItemAsync(id);
|
||||
}
|
||||
/*
|
||||
* This restores the scroll position after closing the menu and element being 0
|
||||
*/
|
||||
private void RestoreScrollPosition()
|
||||
{
|
||||
if (_selectedListItemIndex != 0)
|
||||
return;
|
||||
|
||||
ScrollManager.ScrollToListItemAsync(GetListItemId(0));
|
||||
}
|
||||
|
||||
private string GetListItemId(in int index)
|
||||
{
|
||||
return $"{_componentId}_item{index}";
|
||||
}
|
||||
|
||||
internal Task OnEnterKey()
|
||||
{
|
||||
if (!IsOpen)
|
||||
return Task.CompletedTask;
|
||||
|
||||
if (_items is null || !_items.Any())
|
||||
return Task.CompletedTask;
|
||||
|
||||
if (_selectedListItemIndex >= 0 && _selectedListItemIndex < _items.Length)
|
||||
return SelectOption(_items[_selectedListItemIndex]);
|
||||
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
private Task OnInputBlurred(FocusEventArgs args)
|
||||
{
|
||||
OnBlur.InvokeAsync(args);
|
||||
|
||||
return Task.CompletedTask;
|
||||
// we should not validate on blur in autocomplete, because the user needs to click out of the input to select a value,
|
||||
// resulting in a premature validation. thus, don't call base
|
||||
//base.OnBlurred(args);
|
||||
}
|
||||
|
||||
private Task CoerceTextToValue()
|
||||
{
|
||||
if (!CoerceText)
|
||||
return Task.CompletedTask;
|
||||
|
||||
_timer?.Dispose();
|
||||
|
||||
var text = Value is null ? null : GetItemString(Value);
|
||||
/*
|
||||
* Don't update the value to prevent the popover from opening again after coercion
|
||||
*/
|
||||
if (text != Text)
|
||||
return SetTextAsync(text, updateValue: false);
|
||||
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
private Task CoerceValueToText()
|
||||
{
|
||||
if (!CoerceValue)
|
||||
return Task.CompletedTask;
|
||||
|
||||
_timer?.Dispose();
|
||||
|
||||
var value = Converter.Get(Text);
|
||||
|
||||
return SetValueAsync(value, updateText: false);
|
||||
}
|
||||
|
||||
protected override void Dispose(bool disposing)
|
||||
{
|
||||
_timer?.Dispose();
|
||||
|
||||
if (_cancellationTokenSrc is not null)
|
||||
{
|
||||
try
|
||||
{
|
||||
_cancellationTokenSrc.Dispose();
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
|
||||
base.Dispose(disposing);
|
||||
}
|
||||
/// <summary>
|
||||
/// Focus the input in the Autocomplete component.
|
||||
/// </summary>
|
||||
public override ValueTask FocusAsync()
|
||||
{
|
||||
return _elementReference.FocusAsync();
|
||||
}
|
||||
/// <summary>
|
||||
/// Blur from the input in the Autocomplete component.
|
||||
/// </summary>
|
||||
public override ValueTask BlurAsync()
|
||||
{
|
||||
return _elementReference.BlurAsync();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Select all text within the Autocomplete input.
|
||||
/// </summary>
|
||||
public override ValueTask SelectAsync()
|
||||
{
|
||||
return _elementReference.SelectAsync();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Select all text within the Autocomplete input and aligns its start and end points to the text content of the current input.
|
||||
/// </summary>
|
||||
public override ValueTask SelectRangeAsync(int pos1, int pos2)
|
||||
{
|
||||
return _elementReference.SelectRangeAsync(pos1, pos2);
|
||||
}
|
||||
|
||||
private async Task OnTextChanged(string text)
|
||||
{
|
||||
await TextChanged.InvokeAsync();
|
||||
|
||||
if (text is null)
|
||||
return;
|
||||
|
||||
await SetTextAsync(text, true);
|
||||
}
|
||||
|
||||
private async Task ListItemOnClick(T item)
|
||||
{
|
||||
await SelectOption(item);
|
||||
}
|
||||
}
|
File diff suppressed because it is too large
Load Diff
@ -1,639 +0,0 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Globalization;
|
||||
using System.Linq.Expressions;
|
||||
using System.Reflection;
|
||||
using Connected.Annotations;
|
||||
using Microsoft.AspNetCore.Components;
|
||||
using Microsoft.AspNetCore.Components.Forms;
|
||||
using static System.String;
|
||||
|
||||
namespace Connected.Components;
|
||||
|
||||
public abstract class FormComponent<T, U> : UIComponent, IFormComponent, IDisposable
|
||||
{
|
||||
private Converter<T, U> _converter;
|
||||
|
||||
protected FormComponent(Converter<T, U> converter)
|
||||
{
|
||||
_converter = converter ?? throw new ArgumentNullException(nameof(converter));
|
||||
_converter.OnError = OnConversionError;
|
||||
}
|
||||
|
||||
[CascadingParameter] internal IForm Form { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// If true, this is a top-level form component. If false, this input is a sub-component of another input (i.e. TextField, Select, etc).
|
||||
/// If it is sub-component, it will NOT do form validation!!
|
||||
/// </summary>
|
||||
[CascadingParameter(Name = "SubscribeToParentForm")]
|
||||
internal bool SubscribeToParentForm { get; set; } = true;
|
||||
|
||||
/// <summary>
|
||||
/// If true, this form input is required to be filled out.
|
||||
/// </summary>
|
||||
[Parameter]
|
||||
[Category(CategoryTypes.FormComponent.Validation)]
|
||||
public bool Required { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// The error text that will be displayed if the input is not filled out but required.
|
||||
/// </summary>
|
||||
[Parameter]
|
||||
[Category(CategoryTypes.FormComponent.Validation)]
|
||||
public string RequiredError { get; set; } = "Required";
|
||||
|
||||
/// <summary>
|
||||
/// The ErrorText that will be displayed if Error true.
|
||||
/// </summary>
|
||||
[Parameter]
|
||||
[Category(CategoryTypes.FormComponent.Validation)]
|
||||
public string ErrorText { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// If true, the label will be displayed in an error state.
|
||||
/// </summary>
|
||||
[Parameter]
|
||||
[Category(CategoryTypes.FormComponent.Validation)]
|
||||
public bool Error { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// The ErrorId that will be used by aria-describedby if Error true
|
||||
/// </summary>
|
||||
[Parameter]
|
||||
[Category(CategoryTypes.FormComponent.Validation)]
|
||||
public string ErrorId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// The generic converter of the component.
|
||||
/// </summary>
|
||||
[Parameter]
|
||||
[Category(CategoryTypes.FormComponent.Behavior)]
|
||||
public Converter<T, U> Converter
|
||||
{
|
||||
get => _converter;
|
||||
set => SetConverter(value);
|
||||
}
|
||||
|
||||
protected virtual bool SetConverter(Converter<T, U> value)
|
||||
{
|
||||
var changed = (_converter != value);
|
||||
if (changed)
|
||||
{
|
||||
_converter = value ?? throw new ArgumentNullException(nameof(value)); // converter is mandatory at all times
|
||||
_converter.OnError = OnConversionError;
|
||||
}
|
||||
return changed;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The culture of the component.
|
||||
/// </summary>
|
||||
[Parameter]
|
||||
[Category(CategoryTypes.FormComponent.Behavior)]
|
||||
public CultureInfo Culture
|
||||
{
|
||||
get => _converter.Culture;
|
||||
set => SetCulture(value);
|
||||
}
|
||||
|
||||
protected virtual bool SetCulture(CultureInfo value)
|
||||
{
|
||||
var changed = (_converter.Culture != value);
|
||||
if (changed)
|
||||
{
|
||||
_converter.Culture = value;
|
||||
}
|
||||
return changed;
|
||||
}
|
||||
|
||||
private void OnConversionError(string error)
|
||||
{
|
||||
// note: we need to update the form here because the conversion error might lead to not updating the value
|
||||
// ... which leads to not updating the form
|
||||
Touched = true;
|
||||
Form?.Update(this);
|
||||
OnConversionErrorOccurred(error);
|
||||
}
|
||||
|
||||
protected virtual void OnConversionErrorOccurred(string error)
|
||||
{
|
||||
/* Descendants can override this method to catch conversion errors */
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// True if the conversion from string to T failed
|
||||
/// </summary>
|
||||
public bool ConversionError => _converter.GetError;
|
||||
|
||||
/// <summary>
|
||||
/// The error message of the conversion error from string to T. Null otherwise
|
||||
/// </summary>
|
||||
public string ConversionErrorMessage => _converter.GetErrorMessage;
|
||||
|
||||
/// <summary>
|
||||
/// True if the input has any of the following errors: An error set from outside, a conversion error or
|
||||
/// one or more validation errors
|
||||
/// </summary>
|
||||
public bool HasErrors => Error || ConversionError || ValidationErrors.Count > 0;
|
||||
|
||||
/// <summary>
|
||||
/// Return the validation error text or the conversion error message.
|
||||
/// </summary>
|
||||
/// <returns>Error text/message</returns>
|
||||
public string GetErrorText()
|
||||
{
|
||||
// ErrorText is either set from outside or the first validation error
|
||||
if (!IsNullOrWhiteSpace(ErrorText))
|
||||
return ErrorText;
|
||||
|
||||
if (!IsNullOrWhiteSpace(ConversionErrorMessage))
|
||||
return ConversionErrorMessage;
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// This manages the state of having been "touched" by the user. A form control always starts out untouched
|
||||
/// but becomes touched when the user performed input or the blur event was raised.
|
||||
///
|
||||
/// The touched state is only relevant for inputs that have no value (i.e. empty text fields). Being untouched will
|
||||
/// suppress RequiredError
|
||||
/// </summary>
|
||||
public bool Touched { get; protected set; }
|
||||
|
||||
#region MudForm Validation
|
||||
|
||||
public List<string> ValidationErrors { get; set; } = new List<string>();
|
||||
|
||||
/// <summary>
|
||||
/// A validation func or a validation attribute. Supported types are:
|
||||
/// <para>Func<T, bool> ... will output the standard error message "Invalid" if false</para>
|
||||
/// <para>Func<T, string> ... outputs the result as error message, no error if null </para>
|
||||
/// <para>Func<T, IEnumerable< string >> ... outputs all the returned error messages, no error if empty</para>
|
||||
/// <para>Func<object, string, IEnumerable< string >> input Form.Model, Full Path of Member ... outputs all the returned error messages, no error if empty</para>
|
||||
/// <para>Func<T, Task< bool >> ... will output the standard error message "Invalid" if false</para>
|
||||
/// <para>Func<T, Task< string >> ... outputs the result as error message, no error if null</para>
|
||||
/// <para>Func<T, Task<IEnumerable< string >>> ... outputs all the returned error messages, no error if empty</para>
|
||||
/// <para>Func<object, string, Task<IEnumerable< string >>> input Form.Model, Full Path of Member ... outputs all the returned error messages, no error if empty</para>
|
||||
/// <para>System.ComponentModel.DataAnnotations.ValidationAttribute instances</para>
|
||||
/// </summary>
|
||||
[Parameter]
|
||||
[Category(CategoryTypes.FormComponent.Validation)]
|
||||
public object Validation { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// This is the form component's value.
|
||||
/// </summary>
|
||||
protected T _value;
|
||||
|
||||
// These are the fire-and-forget methods to launch an async validation process.
|
||||
// After each async step, we make sure the current Value of the component has not changed while
|
||||
// async code was executed to avoid race condition which could lead to incorrect validation results.
|
||||
protected void BeginValidateAfter(Task task)
|
||||
{
|
||||
Func<Task> execute = async () =>
|
||||
{
|
||||
var value = _value;
|
||||
|
||||
await task;
|
||||
|
||||
// we validate only if the value hasn't changed while we waited for task.
|
||||
// if it has in fact changed, another validate call will follow anyway
|
||||
if (EqualityComparer<T>.Default.Equals(value, _value))
|
||||
{
|
||||
BeginValidate();
|
||||
}
|
||||
};
|
||||
execute().AndForget();
|
||||
}
|
||||
|
||||
protected void BeginValidate()
|
||||
{
|
||||
Func<Task> execute = async () =>
|
||||
{
|
||||
var value = _value;
|
||||
|
||||
await ValidateValue();
|
||||
|
||||
if (EqualityComparer<T>.Default.Equals(value, _value))
|
||||
{
|
||||
EditFormValidate();
|
||||
}
|
||||
};
|
||||
execute().AndForget();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Cause this component to validate its value.
|
||||
/// </summary>
|
||||
public Task Validate()
|
||||
{
|
||||
// when a validation is forced, we must set Touched to true, because for untouched fields with
|
||||
// no value, validation does nothing due to the way forms are expected to work (display errors
|
||||
// only after fields have been touched).
|
||||
Touched = true;
|
||||
return ValidateValue();
|
||||
}
|
||||
|
||||
protected virtual async Task ValidateValue()
|
||||
{
|
||||
var changed = false;
|
||||
var errors = new List<string>();
|
||||
try
|
||||
{
|
||||
// conversion error
|
||||
if (ConversionError)
|
||||
errors.Add(ConversionErrorMessage);
|
||||
// validation errors
|
||||
if (Validation is ValidationAttribute)
|
||||
ValidateWithAttribute(Validation as ValidationAttribute, _value, errors);
|
||||
else if (Validation is Func<T, bool>)
|
||||
ValidateWithFunc(Validation as Func<T, bool>, _value, errors);
|
||||
else if (Validation is Func<T, string>)
|
||||
ValidateWithFunc(Validation as Func<T, string>, _value, errors);
|
||||
else if (Validation is Func<T, IEnumerable<string>>)
|
||||
ValidateWithFunc(Validation as Func<T, IEnumerable<string>>, _value, errors);
|
||||
else if (Validation is Func<object, string, IEnumerable<string>>)
|
||||
ValidateModelWithFullPathOfMember(Validation as Func<object, string, IEnumerable<string>>, errors);
|
||||
else
|
||||
{
|
||||
var value = _value;
|
||||
|
||||
if (Validation is Func<T, Task<bool>>)
|
||||
await ValidateWithFunc(Validation as Func<T, Task<bool>>, _value, errors);
|
||||
else if (Validation is Func<T, Task<string>>)
|
||||
await ValidateWithFunc(Validation as Func<T, Task<string>>, _value, errors);
|
||||
else if (Validation is Func<T, Task<IEnumerable<string>>>)
|
||||
await ValidateWithFunc(Validation as Func<T, Task<IEnumerable<string>>>, _value, errors);
|
||||
else if (Validation is Func<object, string, Task<IEnumerable<string>>>)
|
||||
await ValidateModelWithFullPathOfMember(Validation as Func<object, string, Task<IEnumerable<string>>>, errors);
|
||||
|
||||
changed = !EqualityComparer<T>.Default.Equals(value, _value);
|
||||
}
|
||||
|
||||
// Run each validation attributes of the property targeted with `For`
|
||||
if (_validationAttrsFor != null)
|
||||
{
|
||||
foreach (var attr in _validationAttrsFor)
|
||||
{
|
||||
ValidateWithAttribute(attr, _value, errors);
|
||||
}
|
||||
}
|
||||
|
||||
// required error (must be last, because it is least important!)
|
||||
if (Required)
|
||||
{
|
||||
if (Touched && !HasValue(_value))
|
||||
errors.Add(RequiredError);
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
// If Value has changed while we were validating it, ignore results and exit
|
||||
if (!changed)
|
||||
{
|
||||
// this must be called in any case, because even if Validation is null the user might have set Error and ErrorText manually
|
||||
// if Error and ErrorText are set by the user, setting them here will have no effect.
|
||||
// if Error, create an error id that can be used by aria-describedby on input control
|
||||
ValidationErrors = errors;
|
||||
Error = errors.Count > 0;
|
||||
ErrorText = errors.FirstOrDefault();
|
||||
ErrorId = HasErrors ? Guid.NewGuid().ToString() : null;
|
||||
Form?.Update(this);
|
||||
StateHasChanged();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
protected virtual bool HasValue(T value)
|
||||
{
|
||||
if (typeof(T) == typeof(string))
|
||||
return !IsNullOrWhiteSpace(value as string);
|
||||
|
||||
return value != null;
|
||||
}
|
||||
|
||||
[UnconditionalSuppressMessage("Trimming", "IL2026:Members annotated with 'RequiresUnreferencedCodeAttribute' require dynamic access otherwise can break functionality when trimming application code", Justification = "In the context of EditContext.Model / FieldIdentifier.Model they won't get trimmed.")]
|
||||
protected virtual void ValidateWithAttribute(ValidationAttribute attr, T value, List<string> errors)
|
||||
{
|
||||
try
|
||||
{
|
||||
// The validation context is applied either on the `EditContext.Model`, '_fieldIdentifier.Model', or `this` as a stub subject.
|
||||
// Complex validation with fields references (like `CompareAttribute`) should use an EditContext or For when not using EditContext.
|
||||
var validationContextSubject = EditContext?.Model ?? _fieldIdentifier.Model ?? this;
|
||||
var validationContext = new ValidationContext(validationContextSubject);
|
||||
if (validationContext.MemberName is null && _fieldIdentifier.FieldName is not null)
|
||||
validationContext.MemberName = _fieldIdentifier.FieldName;
|
||||
var validationResult = attr.GetValidationResult(value, validationContext);
|
||||
if (validationResult != ValidationResult.Success)
|
||||
errors.Add(validationResult.ErrorMessage);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
// Maybe conditionally add full error message if `IWebAssemblyHostEnvironment.IsDevelopment()`
|
||||
// Or log using proper logger.
|
||||
errors.Add($"An unhandled exception occurred: {e.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
protected virtual void ValidateWithFunc(Func<T, bool> func, T value, List<string> errors)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!func(value))
|
||||
errors.Add("Invalid");
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
errors.Add("Error in validation func: " + e.Message);
|
||||
}
|
||||
}
|
||||
|
||||
protected virtual void ValidateWithFunc(Func<T, string> func, T value, List<string> errors)
|
||||
{
|
||||
try
|
||||
{
|
||||
var error = func(value);
|
||||
if (error != null)
|
||||
errors.Add(error);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
errors.Add("Error in validation func: " + e.Message);
|
||||
}
|
||||
}
|
||||
|
||||
protected virtual void ValidateWithFunc(Func<T, IEnumerable<string>> func, T value, List<string> errors)
|
||||
{
|
||||
try
|
||||
{
|
||||
foreach (var error in func(value))
|
||||
errors.Add(error);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
errors.Add("Error in validation func: " + e.Message);
|
||||
}
|
||||
}
|
||||
|
||||
protected virtual void ValidateModelWithFullPathOfMember(Func<object, string, IEnumerable<string>> func, List<string> errors)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (Form?.Model == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (For == null)
|
||||
{
|
||||
errors.Add($"For is null, please set parameter For on the form input component of type {GetType().Name}");
|
||||
return;
|
||||
}
|
||||
|
||||
foreach (var error in func(Form.Model, For.GetFullPathOfMember()))
|
||||
errors.Add(error);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
errors.Add("Error in validation func: " + e.Message);
|
||||
}
|
||||
}
|
||||
|
||||
protected virtual async Task ValidateWithFunc(Func<T, Task<bool>> func, T value, List<string> errors)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!await func(value))
|
||||
errors.Add("Invalid");
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
errors.Add("Error in validation func: " + e.Message);
|
||||
}
|
||||
}
|
||||
|
||||
protected virtual async Task ValidateWithFunc(Func<T, Task<string>> func, T value, List<string> errors)
|
||||
{
|
||||
try
|
||||
{
|
||||
var error = await func(value);
|
||||
if (error != null)
|
||||
errors.Add(error);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
errors.Add("Error in validation func: " + e.Message);
|
||||
}
|
||||
}
|
||||
|
||||
protected virtual async Task ValidateWithFunc(Func<T, Task<IEnumerable<string>>> func, T value, List<string> errors)
|
||||
{
|
||||
try
|
||||
{
|
||||
foreach (var error in await func(value))
|
||||
errors.Add(error);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
errors.Add("Error in validation func: " + e.Message);
|
||||
}
|
||||
}
|
||||
|
||||
protected virtual async Task ValidateModelWithFullPathOfMember(Func<object, string, Task<IEnumerable<string>>> func, List<string> errors)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (Form?.Model == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (For == null)
|
||||
{
|
||||
errors.Add($"For is null, please set parameter For on the form input component of type {GetType().Name}");
|
||||
return;
|
||||
}
|
||||
|
||||
foreach (var error in await func(Form.Model, For.GetFullPathOfMember()))
|
||||
errors.Add(error);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
errors.Add("Error in validation func: " + e.Message);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Notify the Form that a field has changed if SubscribeToParentForm is true
|
||||
/// </summary>
|
||||
protected void FieldChanged(object newValue)
|
||||
{
|
||||
if (SubscribeToParentForm)
|
||||
Form?.FieldChanged(this, newValue);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reset the value and the validation.
|
||||
/// </summary>
|
||||
public void Reset()
|
||||
{
|
||||
ResetValue();
|
||||
ResetValidation();
|
||||
}
|
||||
|
||||
protected virtual void ResetValue()
|
||||
{
|
||||
/* to be overridden */
|
||||
_value = default;
|
||||
Touched = false;
|
||||
StateHasChanged();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reset the validation.
|
||||
/// </summary>
|
||||
public void ResetValidation()
|
||||
{
|
||||
Error = false;
|
||||
ValidationErrors.Clear();
|
||||
ErrorText = null;
|
||||
StateHasChanged();
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
|
||||
#region --> Blazor EditForm validation support
|
||||
|
||||
/// <summary>
|
||||
/// This is the form validation context for Blazor's <EditForm></EditForm> component
|
||||
/// </summary>
|
||||
[CascadingParameter]
|
||||
EditContext EditContext { get; set; } = default!;
|
||||
|
||||
/// <summary>
|
||||
/// Triggers field to be validated.
|
||||
/// </summary>
|
||||
internal void EditFormValidate()
|
||||
{
|
||||
if (_fieldIdentifier.FieldName != null)
|
||||
{
|
||||
EditContext?.NotifyFieldChanged(_fieldIdentifier);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Specify an expression which returns the model's field for which validation messages should be displayed.
|
||||
/// </summary>
|
||||
#nullable enable
|
||||
[Parameter]
|
||||
[Category(CategoryTypes.FormComponent.Validation)]
|
||||
public Expression<Func<T>>? For { get; set; }
|
||||
#nullable disable
|
||||
|
||||
public bool IsForNull => For == null;
|
||||
|
||||
/// <summary>
|
||||
/// Stores the list of validation attributes attached to the property targeted by <seealso cref="For"/>. If <seealso cref="For"/> is null, this property is null too.
|
||||
/// </summary>
|
||||
#nullable enable
|
||||
private IEnumerable<ValidationAttribute>? _validationAttrsFor;
|
||||
#nullable disable
|
||||
|
||||
private void OnValidationStateChanged(object sender, ValidationStateChangedEventArgs e)
|
||||
{
|
||||
if (EditContext != null && !_fieldIdentifier.Equals(default(FieldIdentifier)))
|
||||
{
|
||||
var error_msgs = EditContext.GetValidationMessages(_fieldIdentifier).ToArray();
|
||||
Error = error_msgs.Length > 0;
|
||||
ErrorText = (Error ? error_msgs[0] : null);
|
||||
StateHasChanged();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Points to a field of the model for which validation messages should be displayed.
|
||||
/// </summary>
|
||||
private FieldIdentifier _fieldIdentifier;
|
||||
|
||||
/// <summary>
|
||||
/// To find out whether or not For parameter has changed we keep a separate reference
|
||||
/// </summary>
|
||||
#nullable enable
|
||||
private Expression<Func<T>>? _currentFor;
|
||||
#nullable disable
|
||||
|
||||
/// <summary>
|
||||
/// To find out whether or not EditContext parameter has changed we keep a separate reference
|
||||
/// </summary>
|
||||
#nullable enable
|
||||
private EditContext? _currentEditContext;
|
||||
#nullable disable
|
||||
|
||||
protected override void OnParametersSet()
|
||||
{
|
||||
if (For != null && For != _currentFor)
|
||||
{
|
||||
// Extract validation attributes
|
||||
// Sourced from https://stackoverflow.com/a/43076222/4839162
|
||||
// and also https://stackoverflow.com/questions/59407225/getting-a-custom-attribute-from-a-property-using-an-expression
|
||||
var expression = (MemberExpression)For.Body;
|
||||
var propertyInfo = (PropertyInfo)expression.Expression?.Type.GetProperty(expression.Member.Name);
|
||||
_validationAttrsFor = propertyInfo?.GetCustomAttributes(typeof(ValidationAttribute), true).Cast<ValidationAttribute>();
|
||||
|
||||
_fieldIdentifier = FieldIdentifier.Create(For);
|
||||
_currentFor = For;
|
||||
}
|
||||
|
||||
if (EditContext != null && EditContext != _currentEditContext)
|
||||
{
|
||||
DetachValidationStateChangedListener();
|
||||
EditContext.OnValidationStateChanged += OnValidationStateChanged;
|
||||
_currentEditContext = EditContext;
|
||||
}
|
||||
}
|
||||
|
||||
private void DetachValidationStateChangedListener()
|
||||
{
|
||||
if (_currentEditContext != null)
|
||||
_currentEditContext.OnValidationStateChanged -= OnValidationStateChanged;
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
|
||||
protected override Task OnInitializedAsync()
|
||||
{
|
||||
RegisterAsFormComponent();
|
||||
return base.OnInitializedAsync();
|
||||
}
|
||||
|
||||
protected virtual void RegisterAsFormComponent()
|
||||
{
|
||||
if (SubscribeToParentForm)
|
||||
{
|
||||
Form?.Add(this);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Called to dispose this instance.
|
||||
/// </summary>
|
||||
/// <param name="disposing"><see langword="true"/> if called within <see cref="IDisposable.Dispose"/>.</param>
|
||||
protected virtual void Dispose(bool disposing)
|
||||
{
|
||||
}
|
||||
|
||||
void IDisposable.Dispose()
|
||||
{
|
||||
try
|
||||
{
|
||||
Form?.Remove(this);
|
||||
}
|
||||
catch { /* ignore */ }
|
||||
DetachValidationStateChangedListener();
|
||||
Dispose(disposing: true);
|
||||
}
|
||||
}
|
File diff suppressed because it is too large
Load Diff
@ -1,62 +0,0 @@
|
||||
using Connected.Annotations;
|
||||
using Connected.Middleware;
|
||||
using Microsoft.AspNetCore.Components;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace Connected.Components;
|
||||
|
||||
public abstract class UIComponent : ComponentBase
|
||||
{
|
||||
[Inject]
|
||||
private ILoggerFactory LoggerFactory { get; set; }
|
||||
[Inject]
|
||||
private IComponentMiddlewareService? MiddlewareService { get; set; }
|
||||
|
||||
private ILogger _logger;
|
||||
protected ILogger Logger => _logger ??= LoggerFactory.CreateLogger(GetType());
|
||||
|
||||
/// <summary>
|
||||
/// User class names, separated by space.
|
||||
/// </summary>
|
||||
[Parameter]
|
||||
[Category(CategoryTypes.ComponentBase.Common)]
|
||||
public string Class { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// User styles, applied on top of the component's own classes and styles.
|
||||
/// </summary>
|
||||
[Parameter]
|
||||
[Category(CategoryTypes.ComponentBase.Common)]
|
||||
public string Style { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Use Tag to attach any user data object to the component for your convenience.
|
||||
/// </summary>
|
||||
[Parameter]
|
||||
[Category(CategoryTypes.ComponentBase.Common)]
|
||||
public object Tag { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// UserAttributes carries all attributes you add to the component that don't match any of its parameters.
|
||||
/// They will be splatted onto the underlying HTML tag.
|
||||
/// </summary>
|
||||
[Parameter(CaptureUnmatchedValues = true)]
|
||||
[Category(CategoryTypes.ComponentBase.Common)]
|
||||
public Dictionary<string, object> UserAttributes { get; set; } = new Dictionary<string, object>();
|
||||
|
||||
/// <summary>
|
||||
/// If the UserAttributes contain an ID make it accessible for WCAG labelling of input fields
|
||||
/// </summary>
|
||||
public string FieldId => (UserAttributes?.ContainsKey("id") == true ? UserAttributes["id"].ToString() : $"mudinput-{Guid.NewGuid()}");
|
||||
|
||||
protected Type ResolveComponent<TComponent>()
|
||||
{
|
||||
if (MiddlewareService is null)
|
||||
return typeof(TComponent);
|
||||
|
||||
if (MiddlewareService.Select<TComponent>() is Type type)
|
||||
return type;
|
||||
|
||||
return typeof(TComponent);
|
||||
}
|
||||
}
|
12
Connected.Components.Showcase/App.razor
Normal file
12
Connected.Components.Showcase/App.razor
Normal file
@ -0,0 +1,12 @@
|
||||
<Router AppAssembly="@typeof(App).Assembly">
|
||||
<Found Context="routeData">
|
||||
<RouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)" />
|
||||
<FocusOnNavigate RouteData="@routeData" Selector="h1" />
|
||||
</Found>
|
||||
<NotFound>
|
||||
<PageTitle>Not found</PageTitle>
|
||||
<LayoutView Layout="@typeof(MainLayout)">
|
||||
<p role="alert">Sorry, there's nothing at this address.</p>
|
||||
</LayoutView>
|
||||
</NotFound>
|
||||
</Router>
|
@ -0,0 +1,14 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk.BlazorWebAssembly">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net7.0</TargetFramework>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly" Version="7.0.0-rc.2.22476.2" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly.DevServer" Version="7.0.0-rc.2.22476.2" PrivateAssets="all" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
5
Connected.Components.Showcase/MainLayout.razor
Normal file
5
Connected.Components.Showcase/MainLayout.razor
Normal file
@ -0,0 +1,5 @@
|
||||
@inherits LayoutComponentBase
|
||||
|
||||
<main>
|
||||
@Body
|
||||
</main>
|
3
Connected.Components.Showcase/Pages/Index.razor
Normal file
3
Connected.Components.Showcase/Pages/Index.razor
Normal file
@ -0,0 +1,3 @@
|
||||
@page "/"
|
||||
|
||||
<h1>Hello, world!</h1>
|
5
Connected.Components.Showcase/Pages/TextBox.razor
Normal file
5
Connected.Components.Showcase/Pages/TextBox.razor
Normal file
@ -0,0 +1,5 @@
|
||||
<h3>TextBox</h3>
|
||||
|
||||
@code {
|
||||
|
||||
}
|
11
Connected.Components.Showcase/Program.cs
Normal file
11
Connected.Components.Showcase/Program.cs
Normal file
@ -0,0 +1,11 @@
|
||||
using Connected.Components.Showcase;
|
||||
using Microsoft.AspNetCore.Components.Web;
|
||||
using Microsoft.AspNetCore.Components.WebAssembly.Hosting;
|
||||
|
||||
var builder = WebAssemblyHostBuilder.CreateDefault(args);
|
||||
builder.RootComponents.Add<App>("#app");
|
||||
builder.RootComponents.Add<HeadOutlet>("head::after");
|
||||
|
||||
builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) });
|
||||
|
||||
await builder.Build().RunAsync();
|
38
Connected.Components.Showcase/Properties/launchSettings.json
Normal file
38
Connected.Components.Showcase/Properties/launchSettings.json
Normal file
@ -0,0 +1,38 @@
|
||||
{
|
||||
"iisSettings": {
|
||||
"iisExpress": {
|
||||
"applicationUrl": "http://localhost:30375",
|
||||
"sslPort": 44321
|
||||
}
|
||||
},
|
||||
"profiles": {
|
||||
"http": {
|
||||
"commandName": "Project",
|
||||
"dotnetRunMessages": true,
|
||||
"launchBrowser": true,
|
||||
"inspectUri": "{wsProtocol}://{url.hostname}:{url.port}/_framework/debug/ws-proxy?browser={browserInspectUri}",
|
||||
"applicationUrl": "http://localhost:5035",
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||
}
|
||||
},
|
||||
"https": {
|
||||
"commandName": "Project",
|
||||
"dotnetRunMessages": true,
|
||||
"launchBrowser": true,
|
||||
"inspectUri": "{wsProtocol}://{url.hostname}:{url.port}/_framework/debug/ws-proxy?browser={browserInspectUri}",
|
||||
"applicationUrl": "https://localhost:0;http://localhost:5035",
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||
}
|
||||
},
|
||||
"IIS Express": {
|
||||
"commandName": "IISExpress",
|
||||
"launchBrowser": true,
|
||||
"inspectUri": "{wsProtocol}://{url.hostname}:{url.port}/_framework/debug/ws-proxy?browser={browserInspectUri}",
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
7
Connected.Components.Showcase/_Imports.razor
Normal file
7
Connected.Components.Showcase/_Imports.razor
Normal file
@ -0,0 +1,7 @@
|
||||
@using System.Net.Http
|
||||
@using System.Net.Http.Json
|
||||
@using Microsoft.AspNetCore.Components.Routing
|
||||
@using Microsoft.AspNetCore.Components.Web
|
||||
@using Microsoft.AspNetCore.Components.WebAssembly.Http
|
||||
@using Microsoft.JSInterop
|
||||
@using Connected.Components.Showcase
|
32
Connected.Components.Showcase/wwwroot/css/app.css
Normal file
32
Connected.Components.Showcase/wwwroot/css/app.css
Normal file
@ -0,0 +1,32 @@
|
||||
h1:focus {
|
||||
outline: none;
|
||||
}
|
||||
|
||||
#blazor-error-ui {
|
||||
background: lightyellow;
|
||||
bottom: 0;
|
||||
box-shadow: 0 -1px 2px rgba(0, 0, 0, 0.2);
|
||||
display: none;
|
||||
left: 0;
|
||||
padding: 0.6rem 1.25rem 0.7rem 1.25rem;
|
||||
position: fixed;
|
||||
width: 100%;
|
||||
z-index: 1000;
|
||||
}
|
||||
|
||||
#blazor-error-ui .dismiss {
|
||||
cursor: pointer;
|
||||
position: absolute;
|
||||
right: 0.75rem;
|
||||
top: 0.5rem;
|
||||
}
|
||||
|
||||
.blazor-error-boundary {
|
||||
background: url(data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNTYiIGhlaWdodD0iNDkiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiIG92ZXJmbG93PSJoaWRkZW4iPjxkZWZzPjxjbGlwUGF0aCBpZD0iY2xpcDAiPjxyZWN0IHg9IjIzNSIgeT0iNTEiIHdpZHRoPSI1NiIgaGVpZ2h0PSI0OSIvPjwvY2xpcFBhdGg+PC9kZWZzPjxnIGNsaXAtcGF0aD0idXJsKCNjbGlwMCkiIHRyYW5zZm9ybT0idHJhbnNsYXRlKC0yMzUgLTUxKSI+PHBhdGggZD0iTTI2My41MDYgNTFDMjY0LjcxNyA1MSAyNjUuODEzIDUxLjQ4MzcgMjY2LjYwNiA1Mi4yNjU4TDI2Ny4wNTIgNTIuNzk4NyAyNjcuNTM5IDUzLjYyODMgMjkwLjE4NSA5Mi4xODMxIDI5MC41NDUgOTIuNzk1IDI5MC42NTYgOTIuOTk2QzI5MC44NzcgOTMuNTEzIDI5MSA5NC4wODE1IDI5MSA5NC42NzgyIDI5MSA5Ny4wNjUxIDI4OS4wMzggOTkgMjg2LjYxNyA5OUwyNDAuMzgzIDk5QzIzNy45NjMgOTkgMjM2IDk3LjA2NTEgMjM2IDk0LjY3ODIgMjM2IDk0LjM3OTkgMjM2LjAzMSA5NC4wODg2IDIzNi4wODkgOTMuODA3MkwyMzYuMzM4IDkzLjAxNjIgMjM2Ljg1OCA5Mi4xMzE0IDI1OS40NzMgNTMuNjI5NCAyNTkuOTYxIDUyLjc5ODUgMjYwLjQwNyA1Mi4yNjU4QzI2MS4yIDUxLjQ4MzcgMjYyLjI5NiA1MSAyNjMuNTA2IDUxWk0yNjMuNTg2IDY2LjAxODNDMjYwLjczNyA2Ni4wMTgzIDI1OS4zMTMgNjcuMTI0NSAyNTkuMzEzIDY5LjMzNyAyNTkuMzEzIDY5LjYxMDIgMjU5LjMzMiA2OS44NjA4IDI1OS4zNzEgNzAuMDg4N0wyNjEuNzk1IDg0LjAxNjEgMjY1LjM4IDg0LjAxNjEgMjY3LjgyMSA2OS43NDc1QzI2Ny44NiA2OS43MzA5IDI2Ny44NzkgNjkuNTg3NyAyNjcuODc5IDY5LjMxNzkgMjY3Ljg3OSA2Ny4xMTgyIDI2Ni40NDggNjYuMDE4MyAyNjMuNTg2IDY2LjAxODNaTTI2My41NzYgODYuMDU0N0MyNjEuMDQ5IDg2LjA1NDcgMjU5Ljc4NiA4Ny4zMDA1IDI1OS43ODYgODkuNzkyMSAyNTkuNzg2IDkyLjI4MzcgMjYxLjA0OSA5My41Mjk1IDI2My41NzYgOTMuNTI5NSAyNjYuMTE2IDkzLjUyOTUgMjY3LjM4NyA5Mi4yODM3IDI2Ny4zODcgODkuNzkyMSAyNjcuMzg3IDg3LjMwMDUgMjY2LjExNiA4Ni4wNTQ3IDI2My41NzYgODYuMDU0N1oiIGZpbGw9IiNGRkU1MDAiIGZpbGwtcnVsZT0iZXZlbm9kZCIvPjwvZz48L3N2Zz4=) no-repeat 1rem/1.8rem, #b32121;
|
||||
padding: 1rem 1rem 1rem 3.7rem;
|
||||
color: white;
|
||||
}
|
||||
|
||||
.blazor-error-boundary::after {
|
||||
content: "An error has occurred."
|
||||
}
|
21
Connected.Components.Showcase/wwwroot/index.html
Normal file
21
Connected.Components.Showcase/wwwroot/index.html
Normal file
@ -0,0 +1,21 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<base href="/" />
|
||||
<link href="css/app.css" rel="stylesheet" />
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<div id="app">Loading...</div>
|
||||
|
||||
<div id="blazor-error-ui">
|
||||
An unhandled error has occurred.
|
||||
<a href="" class="reload">Reload</a>
|
||||
<a class="dismiss">🗙</a>
|
||||
</div>
|
||||
<script src="_framework/blazor.webassembly.js"></script>
|
||||
</body>
|
||||
|
||||
</html>
|
31
Connected.Components.sln
Normal file
31
Connected.Components.sln
Normal file
@ -0,0 +1,31 @@
|
||||
|
||||
Microsoft Visual Studio Solution File, Format Version 12.00
|
||||
# Visual Studio Version 17
|
||||
VisualStudioVersion = 17.4.33020.496
|
||||
MinimumVisualStudioVersion = 10.0.40219.1
|
||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Connected.Components", "connected.components\Connected.Components.csproj", "{70BF497D-6519-401B-A0EE-2E9856B13D96}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Connected.Components.Showcase", "Connected.Components.Showcase\Connected.Components.Showcase.csproj", "{EBB24FD8-A554-427C-A93B-B48C047D34CC}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
Debug|Any CPU = Debug|Any CPU
|
||||
Release|Any CPU = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(ProjectConfigurationPlatforms) = postSolution
|
||||
{70BF497D-6519-401B-A0EE-2E9856B13D96}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{70BF497D-6519-401B-A0EE-2E9856B13D96}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{70BF497D-6519-401B-A0EE-2E9856B13D96}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{70BF497D-6519-401B-A0EE-2E9856B13D96}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{EBB24FD8-A554-427C-A93B-B48C047D34CC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{EBB24FD8-A554-427C-A93B-B48C047D34CC}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{EBB24FD8-A554-427C-A93B-B48C047D34CC}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{EBB24FD8-A554-427C-A93B-B48C047D34CC}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(SolutionProperties) = preSolution
|
||||
HideSolutionNode = FALSE
|
||||
EndGlobalSection
|
||||
GlobalSection(ExtensibilityGlobals) = postSolution
|
||||
SolutionGuid = {CBDD97EC-4855-4005-97A7-29FE298FB057}
|
||||
EndGlobalSection
|
||||
EndGlobal
|
@ -5,14 +5,14 @@
|
||||
<CascadingValue Name="SubscribeToParentForm" Value="false" IsFixed="true">
|
||||
<div class="@AutocompleteClassList">
|
||||
<InputControl Label="@Label" Variant="@Variant" HelperText="@HelperText" HelperTextOnFocus="@HelperTextOnFocus" FullWidth="@FullWidth" Margin="@Margin" Class="@ClassList()" Style="@Style"
|
||||
Error="@Error" ErrorText="@ErrorText" Disabled="@Disabled" @onclick="@ToggleMenu" Required="@Required" ForId="@FieldId">
|
||||
Error="@HasError" ErrorText="@ErrorText" Disabled="@Disabled" @onclick="@ToggleMenu" Required="@Required" ForId="@FieldId">
|
||||
<InputContent>
|
||||
<Input @ref="_elementReference" @key="_elementKey" InputType="InputType.Text"
|
||||
Class="select-input" Margin="@Margin"
|
||||
Variant="@Variant"
|
||||
TextUpdateSuppression="@TextUpdateSuppression"
|
||||
Value="@Text" DisableUnderLine="@DisableUnderLine"
|
||||
Disabled="@Disabled" ReadOnly="@ReadOnly" Error="@Error"
|
||||
Disabled="@Disabled" ReadOnly="@ReadOnly" Error="@HasError"
|
||||
OnAdornmentClick="@OnAdornmentClick" AdornmentIcon="@CurrentIcon" Adornment="@Adornment" AdornmentColor="@AdornmentColor" IconSize="@IconSize" AdornmentText="@AdornmentText"
|
||||
Clearable="@Clearable" OnClearButtonClick="@OnClearButtonClick"
|
||||
@attributes="UserAttributes"
|
@ -0,0 +1,693 @@
|
||||
using Connected.Utilities;
|
||||
using Microsoft.AspNetCore.Components;
|
||||
using Microsoft.AspNetCore.Components.Web;
|
||||
|
||||
namespace Connected.Components;
|
||||
|
||||
public partial class Autocomplete<T> : InputBase<T>, IDisposable
|
||||
{
|
||||
private Func<T, string>? _toStringFunc;
|
||||
private Task _currentSearchTask;
|
||||
private CancellationTokenSource _cancellationTokenSrc;
|
||||
private bool _isOpen;
|
||||
private Timer _timer;
|
||||
private T[] _items;
|
||||
private int _selectedListItemIndex = 0;
|
||||
private IList<int> _enabledItemIndices = new List<int>();
|
||||
private int _itemsReturned; //the number of items returned by the search function
|
||||
int _elementKey = 0;
|
||||
/// <summary>
|
||||
/// This boolean will keep track if the clear function is called too keep the set text function to be called.
|
||||
/// </summary>
|
||||
private bool _isCleared;
|
||||
private Input<string> _elementReference;
|
||||
/// <summary>
|
||||
/// We need a random id for the year items in the year list so we can scroll to the item safely in every DatePicker.
|
||||
/// </summary>
|
||||
private readonly string _componentId = Guid.NewGuid().ToString();
|
||||
|
||||
public Autocomplete()
|
||||
{
|
||||
Adornment = Adornment.End;
|
||||
IconSize = Size.Medium;
|
||||
}
|
||||
|
||||
[Inject]
|
||||
IScrollManager ScrollManager { get; set; }
|
||||
/// <summary>
|
||||
/// User class names for the popover, separated by space
|
||||
/// </summary>
|
||||
[Parameter]
|
||||
public string PopoverClass { get; set; }
|
||||
/// <summary>
|
||||
/// Set the anchor origin point to determen where the popover will open from.
|
||||
/// </summary>
|
||||
[Parameter]
|
||||
public Origin AnchorOrigin { get; set; } = Origin.BottomCenter;
|
||||
/// <summary>
|
||||
/// Sets the transform origin point for the popover.
|
||||
/// </summary>
|
||||
[Parameter]
|
||||
public Origin TransformOrigin { get; set; } = Origin.TopCenter;
|
||||
/// <summary>
|
||||
/// If true, compact vertical padding will be applied to all Autocomplete items.
|
||||
/// </summary>
|
||||
[Parameter]
|
||||
public bool Dense { get; set; }
|
||||
/// <summary>
|
||||
/// The Open Autocomplete Icon
|
||||
/// </summary>
|
||||
[Parameter]
|
||||
public string OpenIcon { get; set; } = Icons.Material.Filled.ArrowDropDown;
|
||||
/// <summary>
|
||||
/// The Close Autocomplete Icon
|
||||
/// </summary>
|
||||
[Parameter]
|
||||
public string CloseIcon { get; set; } = Icons.Material.Filled.ArrowDropUp;
|
||||
/// <summary>
|
||||
/// The maximum height of the Autocomplete when it is open.
|
||||
/// </summary>
|
||||
[Parameter]
|
||||
public int MaxHeight { get; set; } = 300;
|
||||
/// <summary>
|
||||
/// Defines how values are displayed in the drop-down list
|
||||
/// </summary>
|
||||
[Parameter]
|
||||
public Func<T, string>? ToStringFunc
|
||||
{
|
||||
get => _toStringFunc;
|
||||
set
|
||||
{
|
||||
if (_toStringFunc == value)
|
||||
return;
|
||||
|
||||
_toStringFunc = value;
|
||||
|
||||
SetConverter(new LambdaConverter<T, string>(_toStringFunc ?? (x => x?.ToString()), null));
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// Whether to show the progress indicator.
|
||||
/// </summary>
|
||||
[Parameter]
|
||||
public bool ShowProgressIndicator { get; set; } = false;
|
||||
/// <summary>
|
||||
/// The color of the progress indicator.
|
||||
/// </summary>
|
||||
[Parameter]
|
||||
public ThemeColor ProgressIndicatorColor { get; set; } = ThemeColor.Default;
|
||||
private bool IsLoading => _currentSearchTask is not null && !_currentSearchTask.IsCompleted;
|
||||
/// <summary>
|
||||
/// Func that returns a list of items matching the typed text. Provides a cancellation token that
|
||||
/// is marked as cancelled when the user changes the search text or selects a value from the list.
|
||||
/// This can be used to cancel expensive asynchronous work occuring within the SearchFunc itself.
|
||||
/// </summary>
|
||||
[Parameter]
|
||||
public Func<string, CancellationToken, Task<IEnumerable<T>>> SearchFuncWithCancel { get; set; }
|
||||
/// <summary>
|
||||
/// The SearchFunc returns a list of items matching the typed text
|
||||
/// </summary>
|
||||
[Parameter]
|
||||
public Func<string, Task<IEnumerable<T>>> SearchFunc { get; set; }
|
||||
/// <summary>
|
||||
/// Maximum items to display, defaults to 10.
|
||||
/// A null value will display all items.
|
||||
/// </summary>
|
||||
[Parameter]
|
||||
public int? MaxItems { get; set; } = 10;
|
||||
/// <summary>
|
||||
/// Minimum characters to initiate a search
|
||||
/// </summary>
|
||||
[Parameter]
|
||||
public int MinCharacters { get; set; } = 0;
|
||||
/// <summary>
|
||||
/// Reset value if user deletes the text
|
||||
/// </summary>
|
||||
[Parameter]
|
||||
public bool ResetValueOnEmptyText { get; set; } = false;
|
||||
/// <summary>
|
||||
/// If true, clicking the text field will select (highlight) its contents.
|
||||
/// </summary>
|
||||
[Parameter]
|
||||
public bool SelectOnClick { get; set; } = true;
|
||||
/// <summary>
|
||||
/// Debounce interval in milliseconds.
|
||||
/// </summary>
|
||||
[Parameter]
|
||||
public int DebounceInterval { get; set; } = 100;
|
||||
/// <summary>
|
||||
/// Optional presentation template for unselected items
|
||||
/// </summary>
|
||||
[Parameter]
|
||||
public RenderFragment<T> ItemTemplate { get; set; }
|
||||
/// <summary>
|
||||
/// Optional presentation template for the selected item
|
||||
/// </summary>
|
||||
[Parameter]
|
||||
public RenderFragment<T> ItemSelectedTemplate { get; set; }
|
||||
/// <summary>
|
||||
/// Optional presentation template for disabled item
|
||||
/// </summary>
|
||||
[Parameter]
|
||||
public RenderFragment<T> ItemDisabledTemplate { get; set; }
|
||||
/// <summary>
|
||||
/// Optional presentation template for when more items were returned from the Search function than the MaxItems limit
|
||||
/// </summary>
|
||||
[Parameter]
|
||||
public RenderFragment MoreItemsTemplate { get; set; }
|
||||
/// <summary>
|
||||
/// Optional presentation template for when no items were returned from the Search function
|
||||
/// </summary>
|
||||
[Parameter]
|
||||
public RenderFragment NoItemsTemplate { get; set; }
|
||||
/// <summary>
|
||||
/// Optional template for progress indicator
|
||||
/// </summary>
|
||||
[Parameter]
|
||||
public RenderFragment ProgressIndicatorTemplate { get; set; }
|
||||
/// <summary>
|
||||
/// Optional template for showing progress indicator inside the popover
|
||||
/// </summary>
|
||||
[Parameter]
|
||||
public RenderFragment ProgressIndicatorInPopoverTemplate { get; set; }
|
||||
/// <summary>
|
||||
/// On drop-down close override Text with selected Value. This makes it clear to the user
|
||||
/// which list value is currently selected and disallows incomplete values in Text.
|
||||
/// </summary>
|
||||
[Parameter]
|
||||
public bool CoerceText { get; set; } = true;
|
||||
/// <summary>
|
||||
/// If user input is not found by the search func and CoerceValue is set to true the user input
|
||||
/// will be applied to the Value which allows to validate it and display an error message.
|
||||
/// </summary>
|
||||
[Parameter]
|
||||
public bool CoerceValue { get; set; }
|
||||
/// <summary>
|
||||
/// Function to be invoked when checking whether an item should be disabled or not
|
||||
/// </summary>
|
||||
[Parameter]
|
||||
public Func<T, bool> ItemDisabledFunc { get; set; }
|
||||
/// <summary>
|
||||
/// Returns the open state of the drop-down.
|
||||
/// </summary>
|
||||
public bool IsOpen
|
||||
{
|
||||
get => _isOpen;
|
||||
// Note: the setter is protected because it was needed by a user who derived his own autocomplete from this class.
|
||||
// Note: setting IsOpen will not open or close it. Use ToggleMenu() for that.
|
||||
protected set
|
||||
{
|
||||
if (value == _isOpen)
|
||||
return;
|
||||
|
||||
_isOpen = value;
|
||||
|
||||
IsOpenChanged.InvokeAsync(_isOpen).AndForget();
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// An event triggered when the state of IsOpen has changed
|
||||
/// </summary>
|
||||
[Parameter]
|
||||
public EventCallback<bool> IsOpenChanged { get; set; }
|
||||
/// <summary>
|
||||
/// If true, the currently selected item from the drop-down (if it is open) is selected.
|
||||
/// </summary>
|
||||
[Parameter]
|
||||
public bool SelectValueOnTab { get; set; } = false;
|
||||
/// <summary>
|
||||
/// Show clear button.
|
||||
/// </summary>
|
||||
[Parameter]
|
||||
public bool Clearable { get; set; } = false;
|
||||
/// <summary>
|
||||
/// Button click event for clear button. Called after text and value has been cleared.
|
||||
/// </summary>
|
||||
[Parameter]
|
||||
public EventCallback<MouseEventArgs> OnClearButtonClick { get; set; }
|
||||
|
||||
private string CurrentIcon => !string.IsNullOrWhiteSpace(AdornmentIcon) ? AdornmentIcon : _isOpen ? CloseIcon : OpenIcon;
|
||||
|
||||
protected string ClassList()
|
||||
{
|
||||
return new CssBuilder("select")
|
||||
.AddClass(Class)
|
||||
.Build();
|
||||
}
|
||||
|
||||
protected string AutocompleteClassList()
|
||||
{
|
||||
return new CssBuilder("select")
|
||||
.AddClass("autocomplete")
|
||||
.AddClass("width-full", FullWidth)
|
||||
.AddClass("autocomplete--with-progress", ShowProgressIndicator && IsLoading)
|
||||
.Build();
|
||||
}
|
||||
|
||||
protected string CircularProgressClassList()
|
||||
{
|
||||
return new CssBuilder("progress-indicator-circular")
|
||||
.AddClass("progress-indicator-circular--with-adornment", Adornment == Adornment.End)
|
||||
.Build();
|
||||
}
|
||||
|
||||
public async Task SelectOption(T value)
|
||||
{
|
||||
await SetValueAsync(value);
|
||||
|
||||
if (_items is not null)
|
||||
_selectedListItemIndex = Array.IndexOf(_items, value);
|
||||
|
||||
var optionText = GetItemString(value);
|
||||
|
||||
if (!_isCleared)
|
||||
await SetTextAsync(optionText, false);
|
||||
|
||||
_timer?.Dispose();
|
||||
|
||||
IsOpen = false;
|
||||
|
||||
BeginValidate();
|
||||
|
||||
if (!_isCleared)
|
||||
_elementReference?.SetText(optionText);
|
||||
|
||||
_elementReference?.FocusAsync().AndForget();
|
||||
|
||||
StateHasChanged();
|
||||
}
|
||||
/// <summary>
|
||||
/// Toggle the menu (if not disabled or not readonly, and is opened).
|
||||
/// </summary>
|
||||
public async Task ToggleMenu()
|
||||
{
|
||||
if ((Disabled || ReadOnly) && !IsOpen)
|
||||
return;
|
||||
|
||||
await ChangeMenu(!IsOpen);
|
||||
}
|
||||
|
||||
private async Task ChangeMenu(bool open)
|
||||
{
|
||||
if (open)
|
||||
{
|
||||
if (SelectOnClick)
|
||||
await _elementReference.SelectAsync();
|
||||
|
||||
await OnSearchAsync();
|
||||
}
|
||||
else
|
||||
{
|
||||
_timer?.Dispose();
|
||||
|
||||
RestoreScrollPosition();
|
||||
|
||||
await CoerceTextToValue();
|
||||
|
||||
IsOpen = false;
|
||||
|
||||
StateHasChanged();
|
||||
}
|
||||
}
|
||||
|
||||
protected override void OnInitialized()
|
||||
{
|
||||
var text = GetItemString(Value);
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(text))
|
||||
Text = text;
|
||||
}
|
||||
|
||||
protected override void OnAfterRender(bool firstRender)
|
||||
{
|
||||
_isCleared = false;
|
||||
|
||||
base.OnAfterRender(firstRender);
|
||||
}
|
||||
|
||||
protected override Task UpdateTextPropertyAsync(bool updateValue)
|
||||
{
|
||||
_timer?.Dispose();
|
||||
// This keeps the text from being set when clear() was called
|
||||
if (_isCleared)
|
||||
return Task.CompletedTask;
|
||||
|
||||
return base.UpdateTextPropertyAsync(updateValue);
|
||||
}
|
||||
|
||||
protected override async Task UpdateValuePropertyAsync(bool updateText)
|
||||
{
|
||||
_timer?.Dispose();
|
||||
|
||||
if (ResetValueOnEmptyText && string.IsNullOrWhiteSpace(Text))
|
||||
await SetValueAsync(default, updateText);
|
||||
|
||||
if (DebounceInterval <= 0)
|
||||
await OnSearchAsync();
|
||||
else
|
||||
_timer = new Timer(OnTimerComplete, null, DebounceInterval, Timeout.Infinite);
|
||||
}
|
||||
|
||||
private void OnTimerComplete(object stateInfo)
|
||||
{
|
||||
InvokeAsync(OnSearchAsync);
|
||||
}
|
||||
private void CancelToken()
|
||||
{
|
||||
try
|
||||
{
|
||||
_cancellationTokenSrc?.Cancel();
|
||||
}
|
||||
catch
|
||||
{
|
||||
}
|
||||
|
||||
_cancellationTokenSrc = new CancellationTokenSource();
|
||||
}
|
||||
/// <remarks>
|
||||
/// This async method needs to return a task and be awaited in order for
|
||||
/// unit tests that trigger this method to work correctly.
|
||||
/// </remarks>
|
||||
private async Task OnSearchAsync()
|
||||
{
|
||||
if (MinCharacters > 0 && (string.IsNullOrWhiteSpace(Text) || Text.Length < MinCharacters))
|
||||
{
|
||||
IsOpen = false;
|
||||
StateHasChanged();
|
||||
return;
|
||||
}
|
||||
|
||||
IEnumerable<T> searchedItems = Array.Empty<T>();
|
||||
CancelToken();
|
||||
|
||||
try
|
||||
{
|
||||
if (ProgressIndicatorInPopoverTemplate is not null)
|
||||
IsOpen = true;
|
||||
|
||||
var searchTask = SearchFuncWithCancel is not null ? SearchFuncWithCancel(Text, _cancellationTokenSrc.Token) : SearchFunc(Text);
|
||||
|
||||
_currentSearchTask = searchTask;
|
||||
|
||||
StateHasChanged();
|
||||
|
||||
searchedItems = await searchTask ?? Array.Empty<T>();
|
||||
}
|
||||
catch (TaskCanceledException)
|
||||
{
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Console.WriteLine($"The search function failed to return results: {e.Message}");
|
||||
}
|
||||
|
||||
_itemsReturned = searchedItems.Count();
|
||||
|
||||
if (MaxItems.HasValue)
|
||||
searchedItems = searchedItems.Take(MaxItems.Value);
|
||||
|
||||
_items = searchedItems.ToArray();
|
||||
_enabledItemIndices = _items.Select((item, idx) => (item, idx)).Where(tuple => ItemDisabledFunc?.Invoke(tuple.item) != true).Select(tuple => tuple.idx).ToList();
|
||||
_selectedListItemIndex = _enabledItemIndices.Any() ? _enabledItemIndices.First() : -1;
|
||||
|
||||
IsOpen = true;
|
||||
|
||||
if (_items?.Length == 0)
|
||||
{
|
||||
await CoerceValueToText();
|
||||
|
||||
StateHasChanged();
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
StateHasChanged();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Clears the autocomplete's text
|
||||
/// </summary>
|
||||
public async Task Clear()
|
||||
{
|
||||
_isCleared = true;
|
||||
IsOpen = false;
|
||||
|
||||
await SetTextAsync(string.Empty, updateValue: false);
|
||||
await CoerceValueToText();
|
||||
|
||||
if (_elementReference is not null)
|
||||
await _elementReference.SetText(string.Empty);
|
||||
|
||||
_timer?.Dispose();
|
||||
|
||||
StateHasChanged();
|
||||
}
|
||||
|
||||
protected override async void ResetValue()
|
||||
{
|
||||
await Clear();
|
||||
base.ResetValue();
|
||||
}
|
||||
|
||||
private string GetItemString(T item)
|
||||
{
|
||||
if (item is null)
|
||||
return string.Empty;
|
||||
try
|
||||
{
|
||||
return Converter.Convert(item);
|
||||
}
|
||||
catch (NullReferenceException) { }
|
||||
|
||||
return "null";
|
||||
}
|
||||
|
||||
internal virtual async Task OnInputKeyDown(KeyboardEventArgs args)
|
||||
{
|
||||
switch (args.Key)
|
||||
{
|
||||
case "Tab":
|
||||
// NOTE: We need to catch Tab in Keydown because a tab will move focus to the next element and thus
|
||||
// in OnInputKeyUp we'd never get the tab key
|
||||
if (!IsOpen)
|
||||
return;
|
||||
if (SelectValueOnTab)
|
||||
await OnEnterKey();
|
||||
else
|
||||
IsOpen = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
internal virtual async Task OnInputKeyUp(KeyboardEventArgs args)
|
||||
{
|
||||
switch (args.Key)
|
||||
{
|
||||
case "Enter":
|
||||
case "NumpadEnter":
|
||||
if (!IsOpen)
|
||||
await ToggleMenu();
|
||||
else
|
||||
await OnEnterKey();
|
||||
|
||||
break;
|
||||
case "ArrowDown":
|
||||
if (!IsOpen)
|
||||
await ToggleMenu();
|
||||
else
|
||||
{
|
||||
var increment = _enabledItemIndices.ElementAtOrDefault(_enabledItemIndices.IndexOf(_selectedListItemIndex) + 1) - _selectedListItemIndex;
|
||||
|
||||
await SelectNextItem(increment < 0 ? 1 : increment);
|
||||
}
|
||||
|
||||
break;
|
||||
case "ArrowUp":
|
||||
if (args.AltKey)
|
||||
await ChangeMenu(false);
|
||||
else if (!IsOpen)
|
||||
await ToggleMenu();
|
||||
else
|
||||
{
|
||||
var decrement = _selectedListItemIndex - _enabledItemIndices.ElementAtOrDefault(_enabledItemIndices.IndexOf(_selectedListItemIndex) - 1);
|
||||
await SelectNextItem(-(decrement < 0 ? 1 : decrement));
|
||||
}
|
||||
|
||||
break;
|
||||
case "Escape":
|
||||
await ChangeMenu(false);
|
||||
|
||||
break;
|
||||
case "Tab":
|
||||
await Task.Delay(1);
|
||||
|
||||
if (!IsOpen)
|
||||
return;
|
||||
|
||||
if (SelectValueOnTab)
|
||||
await OnEnterKey();
|
||||
else
|
||||
await ToggleMenu();
|
||||
|
||||
break;
|
||||
case "Backspace":
|
||||
if (args.CtrlKey && args.ShiftKey)
|
||||
Reset();
|
||||
break;
|
||||
}
|
||||
|
||||
base.InvokeKeyUp(args);
|
||||
}
|
||||
|
||||
private ValueTask SelectNextItem(int increment)
|
||||
{
|
||||
if (increment == 0 || _items is null || !_items.Any() || !_enabledItemIndices.Any())
|
||||
return ValueTask.CompletedTask;
|
||||
// if we are at the end, or the beginning we just do an rollover
|
||||
_selectedListItemIndex = Math.Clamp(value: (10 * _items.Length + _selectedListItemIndex + increment) % _items.Length, min: 0, max: _items.Length - 1);
|
||||
|
||||
return ScrollToListItem(_selectedListItemIndex);
|
||||
}
|
||||
/// <summary>
|
||||
/// Scroll to a specific item index in the Autocomplete list of items.
|
||||
/// </summary>
|
||||
/// <param name="index">the index to scroll to</param>
|
||||
public ValueTask ScrollToListItem(int index)
|
||||
{
|
||||
var id = GetListItemId(index);
|
||||
//id of the scrolled element
|
||||
return ScrollManager.ScrollToListItemAsync(id);
|
||||
}
|
||||
/*
|
||||
* This restores the scroll position after closing the menu and element being 0
|
||||
*/
|
||||
private void RestoreScrollPosition()
|
||||
{
|
||||
if (_selectedListItemIndex != 0)
|
||||
return;
|
||||
|
||||
ScrollManager.ScrollToListItemAsync(GetListItemId(0));
|
||||
}
|
||||
|
||||
private string GetListItemId(in int index)
|
||||
{
|
||||
return $"{_componentId}_item{index}";
|
||||
}
|
||||
|
||||
internal Task OnEnterKey()
|
||||
{
|
||||
if (!IsOpen)
|
||||
return Task.CompletedTask;
|
||||
|
||||
if (_items is null || !_items.Any())
|
||||
return Task.CompletedTask;
|
||||
|
||||
if (_selectedListItemIndex >= 0 && _selectedListItemIndex < _items.Length)
|
||||
return SelectOption(_items[_selectedListItemIndex]);
|
||||
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
private Task OnInputBlurred(FocusEventArgs args)
|
||||
{
|
||||
OnBlur.InvokeAsync(args);
|
||||
|
||||
return Task.CompletedTask;
|
||||
// we should not validate on blur in autocomplete, because the user needs to click out of the input to select a value,
|
||||
// resulting in a premature validation. thus, don't call base
|
||||
//base.OnBlurred(args);
|
||||
}
|
||||
|
||||
private Task CoerceTextToValue()
|
||||
{
|
||||
if (!CoerceText)
|
||||
return Task.CompletedTask;
|
||||
|
||||
_timer?.Dispose();
|
||||
|
||||
var text = Value is null ? null : GetItemString(Value);
|
||||
/*
|
||||
* Don't update the value to prevent the popover from opening again after coercion
|
||||
*/
|
||||
if (text != Text)
|
||||
return SetTextAsync(text, updateValue: false);
|
||||
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
private Task CoerceValueToText()
|
||||
{
|
||||
if (!CoerceValue)
|
||||
return Task.CompletedTask;
|
||||
|
||||
_timer?.Dispose();
|
||||
|
||||
var value = Converter.ConvertBack(Text);
|
||||
|
||||
return SetValueAsync(value, updateText: false);
|
||||
}
|
||||
|
||||
protected override void Dispose(bool disposing)
|
||||
{
|
||||
_timer?.Dispose();
|
||||
|
||||
if (_cancellationTokenSrc is not null)
|
||||
{
|
||||
try
|
||||
{
|
||||
_cancellationTokenSrc.Dispose();
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
|
||||
base.Dispose(disposing);
|
||||
}
|
||||
/// <summary>
|
||||
/// Focus the input in the Autocomplete component.
|
||||
/// </summary>
|
||||
public override ValueTask FocusAsync()
|
||||
{
|
||||
return _elementReference.FocusAsync();
|
||||
}
|
||||
/// <summary>
|
||||
/// Blur from the input in the Autocomplete component.
|
||||
/// </summary>
|
||||
public override ValueTask BlurAsync()
|
||||
{
|
||||
return _elementReference.BlurAsync();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Select all text within the Autocomplete input.
|
||||
/// </summary>
|
||||
public override ValueTask SelectAsync()
|
||||
{
|
||||
return _elementReference.SelectAsync();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Select all text within the Autocomplete input and aligns its start and end points to the text content of the current input.
|
||||
/// </summary>
|
||||
public override ValueTask SelectRangeAsync(int pos1, int pos2)
|
||||
{
|
||||
return _elementReference.SelectRangeAsync(pos1, pos2);
|
||||
}
|
||||
|
||||
private async Task OnTextChanged(string text)
|
||||
{
|
||||
await TextChanged.InvokeAsync();
|
||||
|
||||
if (text is null)
|
||||
return;
|
||||
|
||||
await SetTextAsync(text, true);
|
||||
}
|
||||
|
||||
private async Task ListItemOnClick(T item)
|
||||
{
|
||||
await SelectOption(item);
|
||||
}
|
||||
}
|
@ -44,17 +44,17 @@ public class BooleanInput<T> : FormComponent<T, bool?>
|
||||
/// </summary>
|
||||
[Parameter] public EventCallback<T> CheckedChanged { get; set; }
|
||||
|
||||
protected bool? BoolValue => Converter.Set(Checked);
|
||||
protected bool? BoolValue => Converter.Convert(Checked);
|
||||
|
||||
protected virtual Task OnChange(ChangeEventArgs args)
|
||||
{
|
||||
Touched = true;
|
||||
Modified = true;
|
||||
return SetBoolValueAsync((bool?)args.Value);
|
||||
}
|
||||
|
||||
protected Task SetBoolValueAsync(bool? value)
|
||||
{
|
||||
return SetCheckedAsync(Converter.Get(value));
|
||||
return SetCheckedAsync(Converter.ConvertBack(value));
|
||||
}
|
||||
|
||||
protected async Task SetCheckedAsync(T value)
|
||||
@ -74,7 +74,7 @@ public class BooleanInput<T> : FormComponent<T, bool?>
|
||||
{
|
||||
var changed = base.SetConverter(value);
|
||||
if (changed)
|
||||
SetBoolValueAsync(Converter.Set(Checked)).AndForget();
|
||||
SetBoolValueAsync(Converter.Convert(Checked)).AndForget();
|
||||
|
||||
return changed;
|
||||
}
|
@ -139,7 +139,7 @@ public partial class CheckBox<T> : BooleanInput<T>
|
||||
|
||||
protected override Task OnChange(ChangeEventArgs args)
|
||||
{
|
||||
Touched = true;
|
||||
Modified = true;
|
||||
|
||||
// Apply only when TriState parameter is set to true and T is bool?
|
||||
if (TriState && typeof(T) == typeof(bool?))
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
x
Reference in New Issue
Block a user