Bootstrap.Blazor 自动完成/填充 升级版 RemoteSourceAutoFill

这两天用 Blazor.Server 写了个小工具,算是对 Blazor 的入门吧。
用到了组件库:Bootstrap.Blazor 。这个库存, 总体来说, 很棒。

使用过程中, 发现了一个BUG,bool? 类型的数据,DisplayText 显示不出来, 用于修改时, bool? 类型的数据, 也读取不到真实的值。

bool? 的DisplayText 读取不到

另外, AutoFill / AutoComplete 两个组件的设计,脱离了真实的使用场景。自动完成的数据源, 一般都是建立在海量的数据基础之上(比如从 ES 中实时获取查询结果)。但是这两个组件却使用的是本地数据源,这显然是不可能的。

做为 AutoComplete 的升级 (AutoComplete 的数据源只能是 IEnumerable), AutoFill (数据源是IEnumerable) 要求 TValue 必须是实现ISelectedItem, 这个设计可以说很不合理, 太麻烦。

为了解决上面两个问题, 我复制AutoFill 的源码,写了这个 RemoteSourceAutoFill

RemoteSourceAutoFill.razor

@typeparam TValue
@inherits BootstrapInput

@if (IsShowLabel)
{
    
}

@ChildContent

RemoteSourceAutoFill.razor.cs

    /// 
    /// 支持远程数据源的自动完成
    /// 
    /// 
    public partial class RemoteSourceAutoFill /*where TValue : ISelectedItem*/
    {
        private bool _isLoading;
        private bool _isShown;
        private string _lastFilterText;

        /// 
        /// 获得 组件样式
        /// 
        protected virtual string ClassString => CssBuilder.Default("auto-complete")
            .AddClass("is-loading", _isLoading)
            .AddClass("is-complete", _isShown)
            .Build();

        /// 
        /// 
        /// 
        private IEnumerable items;

        /// 
        /// 获得/设置 无匹配数据时显示提示信息 默认提示"无匹配数据"
        /// 
        [Parameter]
        [NotNull]
        public string NoDataTip { get; set; }


        /// 
        /// 获得/设置 候选项模板
        /// 
        [Parameter]
        public RenderFragment Template { get; set; }



        /// 
        /// 获得/设置 选项改变回调方法 默认 null
        /// 
        [Parameter]
        public Func OnSelectedItemChanged { get; set; }



        /// 
        /// 文本框内容改变时, 触发的数据查询
        /// 
        [Parameter]
        public Func>> Search { get; set; }


        /// 
        /// 获取显示值
        /// 
        [Parameter]
        [NotNull]
        public Func GetDisplayText { get; set; }


        /// 
        /// 查询的字符串, 文本框的值
        /// 
        [Parameter]
        public string Query { get; set; }


        /// 
        /// 
        /// 
        [Parameter]
        public string QueryChanged { get; set; }


        /// 
        /// 
        /// 
        [Inject]
        [NotNull]
        private IStringLocalizer Localizer { get; set; }


        /// 
        /// 
        /// 
        private TValue ActiveSelectedItem { get; set; }

        /// 
        /// 
        /// 
        protected ElementReference RemoteSourceAutoFillElement { get; set; }

        /// 
        /// 
        /// 
        protected int? CurrentItemIndex { get; set; }


        /// 
        /// OnInitialized 方法
        /// 
        protected override void OnInitialized()
        {
            base.OnInitialized();

            NoDataTip ??= Localizer[nameof(NoDataTip)];
            PlaceHolder ??= Localizer[nameof(PlaceHolder)];
            items ??= Enumerable.Empty();
        }

        /// 
        /// firstRender
        /// 
        /// 
        /// 
        protected override async Task OnAfterRenderAsync(bool firstRender)
        {
            await base.OnAfterRenderAsync(firstRender);

            if (CurrentItemIndex.HasValue)
            {
                await InvokeVoidAsync(JSRuntime, RemoteSourceAutoFillElement, "bb_autoScrollItem", CurrentItemIndex.Value);
            }
        }


        /// 
        /// 调用 JSInvoke 方法
        /// 
        /// IJSRuntime 实例
        /// Element 实例或者组件 Id
        /// Javascript 方法
        /// Javascript 参数
        public static ValueTask InvokeVoidAsync(IJSRuntime jsRuntime, object el = null, string func = null, params object[] args)
        {
            var paras = new List();
            if (el != null) paras.Add(el);
            if (args != null) paras.AddRange(args);
            try
            {
                var _ = jsRuntime.InvokeVoidAsync($"$.{func}", paras.ToArray()).ConfigureAwait(false);
            }
            catch (TaskCanceledException) { }
            return ValueTask.CompletedTask;
        }

        /// 
        /// OnBlur 方法
        /// 
        protected async Task OnBlur()
        {
            _isShown = false;
            if (OnSelectedItemChanged != null && ActiveSelectedItem != null)
            {
                await OnSelectedItemChanged(ActiveSelectedItem);
                ActiveSelectedItem = default;
            }
        }

        /// 
        /// 鼠标点击候选项时回调此方法
        /// 
        protected virtual async Task OnClickItem(TValue val)
        {
            CurrentValue = val;
            this.Query = val != null ? this.GetDisplayText(val) : "";
            ActiveSelectedItem = default;
            if (OnSelectedItemChanged != null)
            {
                await OnSelectedItemChanged(val);
            }
        }

        /// 
        /// 获得/设置 是否跳过 Enter 按键处理 默认 false
        /// 
        protected bool SkipEnter { get; set; }

        /// 
        /// 获得/设置 是否跳过 Esc 按键处理 默认 false
        /// 
        protected bool SkipEsc { get; set; }

        /// 
        /// OnKeyUp 方法
        /// 
        /// 
        /// 
        protected virtual async Task OnKeyUp(KeyboardEventArgs args)
        {
            if (!_isLoading && _lastFilterText != this.Query)
            {
                _isLoading = true;
                _lastFilterText = this.Query;
                this.items = await this.Search(this.Query);
                _isLoading = false;
            }

            var source = this.items?.ToList() ?? new List();
            if (source.Any())
            {
                _isShown = true;

                // 键盘向上选择
                if (_isShown && args.Key == "ArrowUp")
                {
                    var index = 0;
                    if (ActiveSelectedItem != null)
                    {
                        index = source.IndexOf(ActiveSelectedItem) - 1;
                        if (index < 0)
                        {
                            index = source.Count - 1;
                        }
                    }
                    ActiveSelectedItem = source[index];
                    CurrentItemIndex = index;
                }
                else if (_isShown && args.Key == "ArrowDown")
                {
                    var index = 0;
                    if (ActiveSelectedItem != null)
                    {
                        index = source.IndexOf(ActiveSelectedItem) + 1;
                        if (index > source.Count - 1)
                        {
                            index = 0;
                        }
                    }
                    ActiveSelectedItem = source[index];
                    CurrentItemIndex = index;
                }
                else if (args.Key == "Escape")
                {
                    await OnBlur();
                    if (!SkipEsc && OnEscAsync != null)
                    {
                        await OnEscAsync(Value);
                    }
                }
                else if (args.Key == "Enter")
                {
                    if (ActiveSelectedItem == null)
                    {
                        ActiveSelectedItem = source.FirstOrDefault();
                    }
                    if (ActiveSelectedItem != null)
                    {
                        this.Query = this.GetDisplayText(ActiveSelectedItem);
                    }
                    await OnBlur();
                    if (!SkipEnter && OnEnterAsync != null)
                    {
                        await OnEnterAsync(Value);
                    }
                }

                if (this.ActiveSelectedItem != null)
                    this.CurrentValue = this.ActiveSelectedItem;
            }
        }

        /// 
        /// 
        /// 
        /// 
        /// 
        protected override string FormatValueAsString(TValue value) => this.GetDisplayText(value);

        ///// 
        ///// 
        ///// 
        ///// 
        ///// 
        ///// 
        ///// 
        //protected override bool TryParseValueFromString(string value, [MaybeNullWhen(false)] out TValue result, out string? validationErrorMessage)
        //{
        //    //CurrentValue.Text = value;
        //    result = CurrentValue;
        //    validationErrorMessage = null;
        //    return true;
        //}
    }
 
 

使用:


    
        
        @*Query="@Data?.JegoHotelDetail?.CityCode"*@

        
        
        private async Task> SearchCity(string txt)
        {
            var rst = await cityFinder.QueryAsync(new ES.Conds.B2CCityFindCondition()
            {
                Str = txt,
                Page = 0,
                PageSize = 10,
            });

            return rst?.Result;
        }

        private string GetCityDisplayText(B2CCity city)
        {
            return city.NameCnLong;
        }

你可能感兴趣的:(Bootstrap.Blazor 自动完成/填充 升级版 RemoteSourceAutoFill)