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

2021-10-27  本文已影响0人  gruan

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

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

bool? 的DisplayText 读取不到

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

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

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

RemoteSourceAutoFill.razor

@typeparam TValue
@inherits BootstrapInput<TValue>

@if (IsShowLabel)
{
    <label class="form-label" required="@Required" for="@Id">@DisplayText</label>
}

<div class="@ClassString" @ref="RemoteSourceAutoFillElement">
    <input @attributes="AdditionalAttributes" class="@ClassName" autocomplete="off" type="text" placeholder="@PlaceHolder" @bind-value="@Query" @bind-value:event="oninput" @onblur="OnBlur" @onkeyup="OnKeyUp" @ref="FocusElement" />
    <i class="fa fa-fw fa-spinner fa-spin"></i>
    <div class="select-dropdown">
        <ul class="dropdown-list">
            @if (items != null && items.Any())
            {
                foreach (var item in items)
                {
                    <li class="dropdown-item" @onmousedown="e => OnClickItem(item)">
                    @if (Template != null)
                    {
                        @Template(item) 
                    }
                    else
                    {
                       <div>@this.GetDisplayText(item)</div>
                    }
                    </li>
                }
            }
            else
            {
                <li class="dropdown-item">@NoDataTip</li>
            }
        </ul>
    </div>
</div>

<CascadingValue Value="this" IsFixed="true">
    @ChildContent
</CascadingValue>

RemoteSourceAutoFill.razor.cs

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

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

        /// <summary>
        /// 
        /// </summary>
        private IEnumerable<TValue> items;

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


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



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



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


        /// <summary>
        /// 获取显示值
        /// </summary>
        [Parameter]
        [NotNull]
        public Func<TValue, string> GetDisplayText { get; set; }


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


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


        /// <summary>
        /// 
        /// </summary>
        [Inject]
        [NotNull]
        private IStringLocalizer<AutoComplete> Localizer { get; set; }


        /// <summary>
        /// 
        /// </summary>
        private TValue ActiveSelectedItem { get; set; }

        /// <summary>
        /// 
        /// </summary>
        protected ElementReference RemoteSourceAutoFillElement { get; set; }

        /// <summary>
        /// 
        /// </summary>
        protected int? CurrentItemIndex { get; set; }


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

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

        /// <summary>
        /// firstRender
        /// </summary>
        /// <param name="firstRender"></param>
        /// <returns></returns>
        protected override async Task OnAfterRenderAsync(bool firstRender)
        {
            await base.OnAfterRenderAsync(firstRender);

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


        /// <summary>
        /// 调用 JSInvoke 方法
        /// </summary>
        /// <param name="jsRuntime">IJSRuntime 实例</param>
        /// <param name="el">Element 实例或者组件 Id</param>
        /// <param name="func">Javascript 方法</param>
        /// <param name="args">Javascript 参数</param>
        public static ValueTask InvokeVoidAsync(IJSRuntime jsRuntime, object el = null, string func = null, params object[] args)
        {
            var paras = new List<object>();
            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;
        }

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

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

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

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

        /// <summary>
        /// OnKeyUp 方法
        /// </summary>
        /// <param name="args"></param>
        /// <returns></returns>
        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<TValue>();
            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;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        protected override string FormatValueAsString(TValue value) => this.GetDisplayText(value);

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

使用:

<GroupBox Title="查询">
    <Row ItemsPerRow="ItemsPerRow.Three" RowType="RowType.Inline">
        <RemoteSourceAutoFill TValue="CNB.ES.Models.B2CCity"
                              @bind-Value="city"
                              Search="SearchCity"
                              GetDisplayText="GetCityDisplayText"
                              DisplayText="城市"
                              ShowLabel="true" />
        @*Query="@Data?.JegoHotelDetail?.CityCode"*@

        <BootstrapInput @bind-Value="hotelQuery" DisplayText="酒店关键字" ShowLabel="true" />
        <Button Text="查找" OnClick="SearchHotel" />
    </Row>
</GroupBox>
        private async Task<IEnumerable<B2CCity>> 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;
        }
上一篇 下一篇

猜你喜欢

热点阅读