AutoComplete 自动完成
在可编辑输入框中根据当前文本展示建议,并可用键盘或鼠标选中建议值。
何时使用
- 输入内容通常来自一组候选值,但仍允许用户先自由输入时。
- 地址、用户名、文件名等候选较多,需要边输入边缩小范围时。
- 只需要固定选项且不允许自由文本时,使用 Select 选择器;需要在文本中插入提及时,使用 Mentions 提及输入。
在线体验
基本用法
import "github.com/tangoui/tango/ui"
var address string
var addresses = ui.Opts("Downing Street", "Wall Street", "Baker Street")
func page(c *ui.Context) {
ui.AutoComplete(c, &address, addresses).
Placeholder("请输入地址").
AllowClear().
Highlight()
}val 保存当前输入文本。静态选项按 Label 做不区分大小写的子串匹配;选中建议后,组件把该选项的 Value 写入 val。
常见用法
自定义过滤
Source 接收当前输入,返回本帧要显示的选项,适合拼音、别名或业务规则过滤。
import (
"strings"
"github.com/tangoui/tango/ui"
)
var query string
var cities = []ui.Option{{Label: "杭州西湖", Value: "xihu"}, {Label: "上海浦东", Value: "pudong"}}
func page(c *ui.Context) {
ui.AutoComplete(c, &query, cities).Source(func(q string) []ui.Option {
var out []ui.Option
for _, o := range cities {
if strings.Contains(strings.ToLower(o.Label), strings.ToLower(q)) {
out = append(out, o)
}
}
return out
})
}聚焦即显示建议
TriggerOnFocus 在输入框刚获得焦点时按当前文本打开建议,文本为空时展示全部静态选项。搭配 Remote 时,聚焦可立即触发一次查询。Selected 可读取本帧刚刚选中的值。
import "github.com/tangoui/tango/ui"
var user string
func page(c *ui.Context) {
w := ui.AutoComplete(c, &user, ui.Opts("alice", "bob")).TriggerOnFocus()
if value, ok := w.Selected(); ok {
_ = value // 在这里触发联动或加载详情
}
}远程搜索
Remote 在 UI 线程上收到查询,输入变化后的防抖延迟默认是 300 毫秒,可用 Debounce 覆盖。远程选项直接展示,设置 Source 时优先展示 Source 的结果。请求期间用 Loading(true) 显示加载状态。下面用 app.Post 把结果交回 UI 线程,再请求新的一帧。
import (
"time"
"github.com/tangoui/tango"
"github.com/tangoui/tango/ui"
)
// 创建一次页面函数。fetch 由应用提供,在后台获取候选项。
func remotePage(app *tango.App, fetch func(string) []ui.Option) func(*ui.Context) {
var query string
var options []ui.Option
var busy bool
var request int
return func(c *ui.Context) {
wake := c.Invalidator()
ui.AutoComplete(c, &query, options).
Debounce(200 * time.Millisecond).
Loading(busy).
Remote(func(q string) {
request++
id := request
busy = true
c.Invalidate()
go func() {
hits := fetch(q)
app.Post(func() {
if id == request && query == q {
options, busy = hits, false
wake()
}
})
}()
})
}
}外观与可访问名称
可用 Variant、Size、Status、Width 设置输入框外观;不在 Form 中使用时,用 A11yLabel 提供可访问名称。
import "github.com/tangoui/tango/ui"
var keyword string
func page(c *ui.Context) {
ui.AutoComplete(c, &keyword, nil).
Variant(ui.FieldFilled).
Width(280).
Status("error").
A11yLabel("搜索关键字")
}主题与样式
- AutoComplete 复用 Input 的输入框令牌,弹出列表使用 Select 的选项令牌;三套设计风格会自动调整边框、圆角、选中背景和匹配高亮。
- 输入框支持
outlined、filled、borderless、underlined四种Variant,尺寸可用ui.Small、默认值或ui.Large。 ConfigProvider.Defaults("AutoComplete", ui.Props{...})支持size、placeholder、allowClear、variant和placement。内部输入框同时继承Defaults("Input", ...)的variant、showCount、maxLength等键。
注意事项
- 即时模式下
val应放在页面函数外或稳定的状态对象中;不要在每帧用局部变量重置输入值。 - 建议多于 100 条时下拉列表自动虚拟化,只构建可见行和键盘高亮行,保留完整列表的宽度、高度和滚动范围。无障碍树只暴露已构建的建议。用
Virtual(false)构建所有行,或用Virtual(true)强制开启虚拟化。 - 虚拟化时,静态选项的匹配结果和宽度会复用。原地修改同一切片且长度不变时,传入递增的
DataVersion(version)或换一个新切片,下一帧会重新计算。Source和Remote的结果直接用于当前帧。 - Enter 选择当前建议,↑ / ↓ 移动,Escape 关闭。
- 组件自动提供可展开组合框语义;在表单外使用时设置
A11yLabel。
示例代码
以下是上方在线演示运行的 Go 源码(来自官方 gallery),点击标题展开。函数接收的 c *ui.Context 由窗口的 UI 循环每帧传入,接入方式见 Go GUI 入门。
API
签名与说明由 site/tools/compdoc 从 Go 源码和文档注释提取;点击名称跳到 Go API 参考 的对应条目。
入口函数
ui.AutoComplete
func AutoComplete(c *Context, val *string, opts []Option) *AutoCompleteWAutoComplete adds an input bound to *val that suggests opts (filtered by the typed text). Picking a suggestion writes its Value.
返回 *AutoCompleteW,可链式调用的方法见 AutoCompleteW 方法。
AutoCompleteW 方法
ui.AutoCompleteW:AutoCompleteW is a text input with a suggestion dropdown.
| 方法 | 说明 | 签名 |
|---|---|---|
A11yLabel | A11yLabel sets the accessible name (inside a FormItem the item label is used; the placeholder is the last resort). | A11yLabel(s string) *AutoCompleteW |
AllowClear | AllowClear() *AutoCompleteW | |
Changed | Changed reports a typed edit or a picked suggestion this frame. | Changed() bool |
DataVersion | DataVersion tells the autocomplete that the options slice was modified in place (a virtual list caches its matches and label widths by slice identity, length and this number): after editing options of the same slice without changing its length, change v (or pass a new slice) so the matches and the list's width are recomputed on the next frame. | DataVersion(v int) *AutoCompleteW |
Debounce | Debounce sets the delay before a Remote call. | Debounce(d time.Duration) *AutoCompleteW |
Disabled | Disabled(on bool) *AutoCompleteW | |
Highlight | Highlight emphasises the matched part of each suggestion. | Highlight() *AutoCompleteW |
IsOpen | IsOpen reports whether the dropdown (suggestions or the loading row) is shown. | IsOpen() bool |
Layout | Layout(o ...layout.Option) *AutoCompleteW | |
Loading | Loading shows a spinner and the loading text in the dropdown (in place of the suggestions with Remote, or when there are none). | Loading(on bool) *AutoCompleteW |
NotFoundContent | NotFoundContent keeps the dropdown open with text s when nothing matches (Ant notFoundContent; without it an empty list closes). | NotFoundContent(s string) *AutoCompleteW |
Open | Open forces the dropdown open (screenshots, tests). | Open() *AutoCompleteW |
Placeholder | Placeholder(s string) *AutoCompleteW | |
Placement | Placement sets where the suggestions open: BottomStart (default), BottomEnd, TopStart or TopEnd (Ant placement, Element placement); they flip when there is no room. | Placement(p Placement) *AutoCompleteW |
Prefix | Prefix(ic *icon.Icon) *AutoCompleteW | |
Remote | Remote turns on server-side suggestions: fn receives the typed text after Debounce (300ms by default) on the UI thread. | Remote(fn func(query string)) *AutoCompleteW |
Selected | Selected returns the value picked this frame and whether one was picked. | Selected() (string, bool) |
Size | Size(s ControlSize) *AutoCompleteW | |
Source | Source computes suggestions from the typed text (replaces filtering of the static options). | Source(fn func(q string) []Option) *AutoCompleteW |
Status | Status(s string) *AutoCompleteW | |
TriggerOnFocus | TriggerOnFocus opens the suggestions as soon as the input gains focus (Element trigger-on-focus), before anything is typed: the options (or Source's result) for the current text, all of them when it is empty. | TriggerOnFocus() *AutoCompleteW |
Variant | Variant sets the frame look (FieldOutlined by default; the inner Input's Variant). | Variant(v FieldVariant) *AutoCompleteW |
Virtual | Virtual forces the virtual suggestion list on or off; by default lists longer than 100 suggestions are virtual (only the visible rows and the keyboard row are built; the dropdown keeps the width, height and scroll range of the full list, but suggestions out of view are not in the accessibility tree). | Virtual(on bool) *AutoCompleteW |
Width | Width(px float32) *AutoCompleteW |
Option 参数类型
ui.Option:Option is an item of a Select / RadioGroup / CheckboxGroup. Group puts the option under a titled group in Select / MultiSelect / VirtualSelect dropdowns (Ant OptGroup, Element el-option-group); options of one group are listed together in order of the group's first appearance.
| 字段 | 说明 | 类型 |
|---|---|---|
Label | string | |
Value | string | |
Disabled | bool | |
Group | string |