From 89787db944fff224d70b2561c6370cf48a3d73cb Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Thu, 26 Nov 2026 15:51:27 +0800 Subject: [PATCH 01/16] feat(ui): add statistic, input tag, autocomplete and indicator controls statistic shows one formatted number (decimals, digit groups, affixes, status color). inputtag enters several values as tags; Backspace in the empty field is reported through the new Editor.OnDeleteAtEdge hook, since the platform text system takes that key. autocomplete suggests completions while the value stays free text. indicator pins a count or a dot to a control's corner without taking room. TextFieldBase now takes the options of TextField. --- base/page_bases.go | 6 +- cmd/viva/initfiles/AGENTS.md.txt | 4 +- docs/maintaining-controls.md | 2 +- docs/skills/building-with-viva/SKILL.md | 4 +- internal/componentdemo/autocomplete.go | 67 ++++++ internal/componentdemo/catalog_d.go | 4 + internal/componentdemo/indicator.go | 59 +++++ internal/componentdemo/input_tag.go | 84 +++++++ internal/componentdemo/page_usage.go | 4 + internal/componentdemo/statistic.go | 48 ++++ internal/gallery/gallery_drive_test.go | 2 +- text/editor.go | 12 + text/editor_test.go | 19 ++ tools/docs/catalog_test.go | 8 + ui/autocomplete/autocomplete.go | 210 ++++++++++++++++++ ui/autocomplete/autocomplete_test.go | 165 ++++++++++++++ ui/facade.go | 4 +- ui/indicator/indicator.go | 110 ++++++++++ ui/indicator/indicator_test.go | 95 ++++++++ ui/inputtag/inputtag.go | 281 ++++++++++++++++++++++++ ui/inputtag/inputtag_test.go | 158 +++++++++++++ ui/statistic/statistic.go | 153 +++++++++++++ ui/statistic/statistic_test.go | 71 ++++++ website/content/guides/en/components.md | 2 +- website/content/guides/zh/components.md | 2 +- website/src/lib/i18n.ts | 16 ++ 26 files changed, 1577 insertions(+), 13 deletions(-) create mode 100644 internal/componentdemo/autocomplete.go create mode 100644 internal/componentdemo/indicator.go create mode 100644 internal/componentdemo/input_tag.go create mode 100644 internal/componentdemo/statistic.go create mode 100644 ui/autocomplete/autocomplete.go create mode 100644 ui/autocomplete/autocomplete_test.go create mode 100644 ui/indicator/indicator.go create mode 100644 ui/indicator/indicator_test.go create mode 100644 ui/inputtag/inputtag.go create mode 100644 ui/inputtag/inputtag_test.go create mode 100644 ui/statistic/statistic.go create mode 100644 ui/statistic/statistic_test.go diff --git a/base/page_bases.go b/base/page_bases.go index 5428d0d21..efc927fe1 100644 --- a/base/page_bases.go +++ b/base/page_bases.go @@ -132,8 +132,8 @@ func SelectBase[T comparable](c C, Value *T, choices []T, Label func(T) string) } // TextFieldBase is TextField without a look: the editable text, with no padding, -// background, border or corners of its own. -func TextFieldBase[T TextValue](c C, Value T, Label, placeholder string) Box { - b, _ := textFieldOf(c, Value, Label, placeholder, true, gfx.ID{}, nil) +// background, border or corners of its own. It takes the options of TextField. +func TextFieldBase[T TextValue](c C, Value T, Label, placeholder string, opts ...Option) Box { + b, _ := textFieldOf(c, Value, Label, placeholder, true, namedBy("TextFieldBase", opts), opts) return b } diff --git a/cmd/viva/initfiles/AGENTS.md.txt b/cmd/viva/initfiles/AGENTS.md.txt index 8dc068ab9..63c0f683c 100644 --- a/cmd/viva/initfiles/AGENTS.md.txt +++ b/cmd/viva/initfiles/AGENTS.md.txt @@ -234,7 +234,7 @@ func (m *model) page(c ui.C) { `ui/marker`, `ui/skeleton`, `ui/aspectratio`, `ui/questionnaire`, `ui/messagescroller`, `ui/message`, `ui/inputgroup`, `ui/inputotp`, `ui/multiselect`, `ui/hierarchypicker`, `ui/buttongroup`, `ui/togglegroup`, `ui/steps`, `ui/descriptions`, `ui/timeline`, `ui/rate`, `ui/inputnumber`, `ui/datepicker`, `ui/timepicker`, - `ui/transfer`, `ui/alert`, `ui/tag`, `ui/breadcrumb`, `ui/card`, `ui/empty`, `ui/result`, `ui/pagination`, `ui/editabletabs`, `ui/popconfirm`, `ui/divider`, `ui/typography`, `ui/validate`, `ui/upload`, `ui/anchor`, `ui/comment`, `ui/imagepreview`, `ui/mentions`, `ui/tour`. + `ui/transfer`, `ui/alert`, `ui/tag`, `ui/breadcrumb`, `ui/card`, `ui/empty`, `ui/result`, `ui/pagination`, `ui/editabletabs`, `ui/popconfirm`, `ui/divider`, `ui/typography`, `ui/validate`, `ui/upload`, `ui/anchor`, `ui/comment`, `ui/imagepreview`, `ui/mentions`, `ui/tour`, `ui/statistic`, `ui/inputtag`, `ui/autocomplete`, `ui/indicator`. - For read-only selectable output, keep a `textview.View` in the model and call `m.output.Declare(c, textview.Spec{Source: lines, Scroll: true})`. The caller owns the lines, spans and actions; `ui/textview` owns selection and drawing without an editing model. @@ -320,7 +320,7 @@ func (m *model) page(c ui.C) { model: `m.drop.Over()` paints the highlight while files are over it, and `m.drop.Dropped()` returns the files (and their paths, empty in a browser) once. `ui.OpenFiles(c, options, done)` is the system's picker, answering with files that read the same way; `ui.FilePath(file)` is a file's path where there is one. For a whole upload - area with a file list, use `ui/upload`, `ui/anchor`, `ui/comment`, `ui/imagepreview`, `ui/mentions`, `ui/tour`. + area with a file list, use `ui/upload`, `ui/anchor`, `ui/comment`, `ui/imagepreview`, `ui/mentions`, `ui/tour`, `ui/statistic`, `ui/inputtag`, `ui/autocomplete`, `ui/indicator`. - For a divider between two panes, use `ui.Splitter` (see "Keys, drag and the mouse"), not a `DragState`. ## Mistakes that compile (and how each is reported) diff --git a/docs/maintaining-controls.md b/docs/maintaining-controls.md index a429bd060..be9560cfd 100644 --- a/docs/maintaining-controls.md +++ b/docs/maintaining-controls.md @@ -53,7 +53,7 @@ Opt-in page packages live under `ui/` (`ui/codeeditor`, `ui/textview`, `ui `ui/metriccard`, `ui/marker`, `ui/sidebar`, `ui/buttongroup`, `ui/togglegroup`, `ui/multiselect`, `ui/hierarchypicker`, `ui/steps`, `ui/descriptions`, `ui/timeline`, `ui/rate`, -`ui/inputnumber`, `ui/datepicker`, `ui/timepicker`, `ui/transfer`, `ui/alert`, `ui/tag`, `ui/breadcrumb`, `ui/card`, `ui/empty`, `ui/result`, `ui/pagination`, `ui/editabletabs`, `ui/popconfirm`, `ui/divider`, `ui/typography`, `ui/validate`, `ui/upload`, `ui/anchor`, `ui/comment`, `ui/imagepreview`, `ui/mentions`, `ui/tour`). +`ui/inputnumber`, `ui/datepicker`, `ui/timepicker`, `ui/transfer`, `ui/alert`, `ui/tag`, `ui/breadcrumb`, `ui/card`, `ui/empty`, `ui/result`, `ui/pagination`, `ui/editabletabs`, `ui/popconfirm`, `ui/divider`, `ui/typography`, `ui/validate`, `ui/upload`, `ui/anchor`, `ui/comment`, `ui/imagepreview`, `ui/mentions`, `ui/tour`, `ui/statistic`, `ui/inputtag`, `ui/autocomplete`, `ui/indicator`). They import only the public `base`, `components`, `gfx`, `ui` and `window` packages, plus the focused `text` editor for editor-like controls and the root `markdown` parser for the Markdown view. They own stable handlers, and are never diff --git a/docs/skills/building-with-viva/SKILL.md b/docs/skills/building-with-viva/SKILL.md index fe48896de..1d7f5b2ea 100644 --- a/docs/skills/building-with-viva/SKILL.md +++ b/docs/skills/building-with-viva/SKILL.md @@ -89,7 +89,7 @@ func (m *model) page(c ui.C) { ### Optional page packages and custom surfaces - A heavy or stateful page control lives in an opt-in package under `ui/`; import it only when the page uses it. -- Editors and visuals: `ui/codeeditor`, `ui/textview`, `ui/chart`, `ui/markdown`, `ui/image`, `ui/calendar`, `ui/carousel`, `ui/columnresize`, `ui/reordergrid`. Navigation and overlays: `ui/command`, `ui/menubar`, `ui/navigationmenu`, `ui/sidebar`, `ui/hovercard`. Data and inputs: `ui/avatar`, `ui/avatareditor`, `ui/attachment`, `ui/metriccard`, `ui/marker`, `ui/skeleton`, `ui/aspectratio`, `ui/questionnaire`, `ui/messagescroller`, `ui/message`, `ui/inputgroup`, `ui/inputotp`, `ui/multiselect`, `ui/hierarchypicker`, `ui/buttongroup`, `ui/togglegroup`, `ui/steps`, `ui/descriptions`, `ui/timeline`, `ui/rate`, `ui/inputnumber`, `ui/datepicker`, `ui/timepicker`, `ui/transfer`, `ui/alert`, `ui/tag`, `ui/breadcrumb`, `ui/card`, `ui/empty`, `ui/result`, `ui/pagination`, `ui/editabletabs`, `ui/popconfirm`, `ui/divider`, `ui/typography`, `ui/validate`, `ui/upload`, `ui/anchor`, `ui/comment`, `ui/imagepreview`, `ui/mentions`, `ui/tour`. +- Editors and visuals: `ui/codeeditor`, `ui/textview`, `ui/chart`, `ui/markdown`, `ui/image`, `ui/calendar`, `ui/carousel`, `ui/columnresize`, `ui/reordergrid`. Navigation and overlays: `ui/command`, `ui/menubar`, `ui/navigationmenu`, `ui/sidebar`, `ui/hovercard`. Data and inputs: `ui/avatar`, `ui/avatareditor`, `ui/attachment`, `ui/metriccard`, `ui/marker`, `ui/skeleton`, `ui/aspectratio`, `ui/questionnaire`, `ui/messagescroller`, `ui/message`, `ui/inputgroup`, `ui/inputotp`, `ui/multiselect`, `ui/hierarchypicker`, `ui/buttongroup`, `ui/togglegroup`, `ui/steps`, `ui/descriptions`, `ui/timeline`, `ui/rate`, `ui/inputnumber`, `ui/datepicker`, `ui/timepicker`, `ui/transfer`, `ui/alert`, `ui/tag`, `ui/breadcrumb`, `ui/card`, `ui/empty`, `ui/result`, `ui/pagination`, `ui/editabletabs`, `ui/popconfirm`, `ui/divider`, `ui/typography`, `ui/validate`, `ui/upload`, `ui/anchor`, `ui/comment`, `ui/imagepreview`, `ui/mentions`, `ui/tour`, `ui/statistic`, `ui/inputtag`, `ui/autocomplete`, `ui/indicator`. - For read-only selectable output, keep a `textview.View` in the model and call `m.output.Declare(c, textview.Spec{Source: lines, Scroll: true})`. The caller owns lines, spans and actions; `ui/textview` owns selection and drawing without an editing model. - The package name is the capability, never a `view` suffix. Name its state type by role, not by repeating the package: `calendar.State`, `message.Row`, `attachment.Card`, `hovercard.Card`. Keep locals out of the package name (`cal`, `msg`, `pic`); a model field may keep the domain noun (`m.calendar`). - Some packages expose `pkg.View(c, label, &state)` (`calendar.View`, `markdown.View`); others expose a method on the state (`avatar.New().View(c, label)`, `questionnaire.New().View(c, label)`). `go doc github.com/vivaui/viva/ui/` shows which. @@ -107,7 +107,7 @@ func (m *model) page(c ui.C) { - A control you paint is `ui.Control(c, label, &m.handlers).Grow(1).Draw(m.draw)`. `ui.Handlers` receives keys, pointer, wheel and, with `gfx.RoleTextField` or `gfx.RoleTerminal`, typing and IME through `Text`. Its parts are declared in `Draw` with `d.Canvas.Hit(part, r)`; an event on a part reaches the same handlers with the part as its target. - Custom layout: `ui.CustomLayout(c, &m.layout).Children(...)` with `ui.Layout`'s `MeasureWidth`, `PlaceWidth`, `MeasureHeight`, `PlaceHeight`. The page keeps identity, focus and hits; the layout owns the children's geometry. - Drag and drop: a `ui.DragState` in the model, `.DragSource(&m.drag)` and `.DropTarget(&m.drag, accept, drop)` on `Hit` boxes, or `d.DragSource`/`d.DropTarget` inside a `Draw`. The page routes the pointer; `Dragging()`, `Source()`, `Target()`, `At()` paint the gesture. A press that does not move is still a click. A split pane is `ui.Splitter(c, &m.split)` with a `ui.SplitterState`, not a drag. -- Files from the system: `.DropFiles(&m.drop)` with a `ui.FileDropState` makes a box take files dragged onto it (`Over()` for the highlight, `Dropped()` for the files, once); `ui.OpenFiles(c, options, done)` is the system's picker and `ui.FilePath(file)` a file's path where it has one. `ui/upload`, `ui/anchor`, `ui/comment`, `ui/imagepreview`, `ui/mentions`, `ui/tour` is the whole area with its file list. +- Files from the system: `.DropFiles(&m.drop)` with a `ui.FileDropState` makes a box take files dragged onto it (`Over()` for the highlight, `Dropped()` for the files, once); `ui.OpenFiles(c, options, done)` is the system's picker and `ui.FilePath(file)` a file's path where it has one. `ui/upload`, `ui/anchor`, `ui/comment`, `ui/imagepreview`, `ui/mentions`, `ui/tour`, `ui/statistic`, `ui/inputtag`, `ui/autocomplete`, `ui/indicator` is the whole area with its file list. - Painting your own thing: `ui.Slot(c).Draw(func(d *ui.DrawContext) { ... })`, with `d.Canvas.Fill`, `Rounded`, `Border`, `RoundedBorder`, `Elevate`, `DrawPath`, `Label`, `LabelCenter`, `d.Fade`, `d.DashedBorder`. A circle is a `Rounded` square. `Box.Rect()` is only valid in the paint that declared it. - A shortcut is declared where it acts: `if ui.Shortcut(c, ui.Primary, "s") { m.save() }`; `box.Shortcut(0, "delete")` acts while the focus is inside that element. Plain keys stay with a field being typed in. diff --git a/internal/componentdemo/autocomplete.go b/internal/componentdemo/autocomplete.go new file mode 100644 index 000000000..25b25cf81 --- /dev/null +++ b/internal/componentdemo/autocomplete.go @@ -0,0 +1,67 @@ +package componentdemo + +import ( + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/ui/autocomplete" +) + +var autocompleteComponent = Component{ + ID: "autocomplete", Title: "Autocomplete", Category: "Forms", Summary: "自动补全:输入时提示包含所输文字的候选,值仍是自由文本。", + Source: "ui/autocomplete/autocomplete.go", paint: (*State).paintAutocomplete, initialize: (*State).initializeAutocomplete, + editable: func(string) (editableField, bool) { + return editableField{ID: autocompleteField, Initial: ""}, true + }, + Examples: []Example{ + {ID: "default", Title: "候选与自由输入", Description: "上下键移动,回车或 Tab 选中,Esc 关闭;没有高亮候选时回车留给页面,输入候选之外的文字也会保留。与 Combobox 不同,值不限于候选。", Snippet: `m.host = autocomplete.New() +m.host.View(c, &m.hostField, "Host", "Hostname", autocomplete.Spec{Options: m.known}) +if option, ok := m.host.Chosen(); ok { + // the field already holds option +}`, PageSnippet: `m.host = autocomplete.New() +m.host.View(c, &m.hostField, "Host", "Hostname", autocomplete.Spec{Options: m.known}) +if option, ok := m.host.Chosen(); ok { + // the field already holds option +}`, PageSnippetZh: `m.host = autocomplete.New() +m.host.View(c, &m.hostField, "Host", "Hostname", autocomplete.Spec{Options: m.known}) +if option, ok := m.host.Chosen(); ok { + // 输入框里已经是 option +}`}, + }, +} + +var ( + autocompleteUI = tree.Feature("autocomplete") + autocompleteField = tree.ID(autocompleteUI, "field") +) + +var autocompleteOptions = []string{"build-01", "build-02", "db-primary", "db-replica", "staging", "bastion"} + +type autocompleteDemo struct { + a *autocomplete.Autocomplete + field ui.Field + bound bool +} + +var autocompleteDemos = map[*State]*autocompleteDemo{} + +func autocompleteDemoFor(state *State) *autocompleteDemo { + if demo := autocompleteDemos[state]; demo != nil { + return demo + } + demo := &autocompleteDemo{a: autocomplete.New().FieldID(autocompleteField)} + autocompleteDemos[state] = demo + return demo +} + +func (state *State) initializeAutocomplete() { autocompleteDemoFor(state) } + +func (state *State) paintAutocomplete(canvas *gfx.Canvas, theme gfx.Theme, size gfx.Size) { + demo := autocompleteDemoFor(state) + if state.editing && state.editor != nil && !demo.bound { + demo.bound = true + demo.field.Bind(state.editor) + } + state.drawPage(canvas, theme, size, 360, state.Text("Autocomplete · 自动补全", "Autocomplete"), func(c ui.C) { + demo.a.View(c, &demo.field, state.Text("主机", "Host"), state.Text("主机名", "Hostname"), autocomplete.Spec{Options: autocompleteOptions}).FillWidth() + }) +} diff --git a/internal/componentdemo/catalog_d.go b/internal/componentdemo/catalog_d.go index d804d5ed0..209f60c39 100644 --- a/internal/componentdemo/catalog_d.go +++ b/internal/componentdemo/catalog_d.go @@ -27,4 +27,8 @@ var groupDComponents = []Component{ imagePreviewComponent, mentionsComponent, tourComponent, + statisticComponent, + inputTagComponent, + autocompleteComponent, + indicatorComponent, } diff --git a/internal/componentdemo/indicator.go b/internal/componentdemo/indicator.go new file mode 100644 index 000000000..4fdef7dc1 --- /dev/null +++ b/internal/componentdemo/indicator.go @@ -0,0 +1,59 @@ +package componentdemo + +import ( + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/ui/indicator" +) + +var indicatorComponent = Component{ + ID: "indicator", Title: "Indicator", Category: "Data Display", Summary: "角标:贴在控件右上角的数字或小圆点,如未读数。", + Source: "ui/indicator/indicator.go", paint: (*State).paintIndicator, + Examples: []Example{ + {ID: "default", Title: "数字与圆点", Description: "Count 超过 Max 显示“Max+”,为 0 时不显示(ShowZero 除外);Dot 改用小圆点。角标不占位,加上它控件不会移动。", Snippet: `indicator.View(c, "Inbox", indicator.Spec{Count: m.unread, Max: 99}, func() { + ui.Button(c, "Inbox").Icon(m.inboxIcon).IconOnly().Ghost() +})`, PageSnippet: `indicator.View(c, "Inbox", indicator.Spec{Count: m.unread, Max: 99}, func() { + ui.Button(c, "Inbox").Icon(m.inboxIcon).IconOnly().Ghost() +})`, PageSnippetZh: `indicator.View(c, "Inbox", indicator.Spec{Count: m.unread, Max: 99}, func() { + ui.Button(c, "Inbox").Icon(m.inboxIcon).IconOnly().Ghost() +})`}, + }, +} + +// indicatorDemo keeps the closures that declare the marked buttons, made once, so a +// warm paint allocates nothing. +type indicatorDemo struct { + c ui.C + state *State + kids [4]func() + row func() +} + +var indicatorDemos = map[*State]*indicatorDemo{} + +func indicatorDemoFor(state *State) *indicatorDemo { + if demo := indicatorDemos[state]; demo != nil { + return demo + } + demo := &indicatorDemo{state: state} + for i, words := range [4][2]string{{"消息", "Messages"}, {"通知", "Alerts"}, {"更新", "Updates"}, {"完成", "Done"}} { + demo.kids[i] = func() { ui.Button(demo.c, state.Text(words[0], words[1])).Outline() } + } + demo.row = func() { + c := demo.c + indicator.View(c, state.Text("消息", "Messages"), indicator.Spec{Count: 5}, demo.kids[0]) + indicator.View(c, state.Text("通知", "Alerts"), indicator.Spec{Count: 128}, demo.kids[1]) + indicator.View(c, state.Text("更新", "Updates"), indicator.Spec{Count: 1, Dot: true}, demo.kids[2]) + indicator.View(c, state.Text("完成", "Done"), indicator.Spec{Count: 3, Status: ui.StatusSuccess}, demo.kids[3]) + } + indicatorDemos[state] = demo + return demo +} + +func (state *State) paintIndicator(canvas *gfx.Canvas, theme gfx.Theme, size gfx.Size) { + demo := indicatorDemoFor(state) + state.drawPage(canvas, theme, size, 420, state.Text("Indicator · 角标", "Indicator"), func(c ui.C) { + demo.c = c + ui.Row(c).Gap(32).Pad(8).Children(demo.row) + }) +} diff --git a/internal/componentdemo/input_tag.go b/internal/componentdemo/input_tag.go new file mode 100644 index 000000000..6d3ef2388 --- /dev/null +++ b/internal/componentdemo/input_tag.go @@ -0,0 +1,84 @@ +package componentdemo + +import ( + "slices" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/ui/inputtag" +) + +var inputTagComponent = Component{ + ID: "input-tag", Title: "Input Tag", Category: "Forms", Summary: "标签输入:回车或逗号添加标签,空输入框按退格删除最后一个。", + Source: "ui/inputtag/inputtag.go", paint: (*State).paintInputTag, initialize: (*State).initializeInputTag, + editable: func(string) (editableField, bool) { + return editableField{ID: inputTagField, Initial: ""}, true + }, + Examples: []Example{ + {ID: "default", Title: "输入多个值", Description: "控件只报告添加与删除,标签列表由页面持有;重复、空白与超出上限的值被拒绝并让输入框显示无效外观。", Snippet: `m.hosts = inputtag.New() +m.hosts.View(c, "Allowed hosts", m.allowed, inputtag.Spec{Placeholder: "Add a host"}).FillWidth() +if value, ok := m.hosts.Added(); ok { + m.allowed = append(m.allowed, value) +} +if i, ok := m.hosts.Removed(); ok { + m.allowed = slices.Delete(m.allowed, i, i+1) +}`, PageSnippet: `m.hosts = inputtag.New() +m.hosts.View(c, "Allowed hosts", m.allowed, inputtag.Spec{Placeholder: "Add a host"}).FillWidth() +if value, ok := m.hosts.Added(); ok { + m.allowed = append(m.allowed, value) +} +if i, ok := m.hosts.Removed(); ok { + m.allowed = slices.Delete(m.allowed, i, i+1) +}`, PageSnippetZh: `m.hosts = inputtag.New() +m.hosts.View(c, "Allowed hosts", m.allowed, inputtag.Spec{Placeholder: "Add a host"}).FillWidth() +if value, ok := m.hosts.Added(); ok { + m.allowed = append(m.allowed, value) +} +if i, ok := m.hosts.Removed(); ok { + m.allowed = slices.Delete(m.allowed, i, i+1) +}`}, + }, +} + +var ( + inputTagUI = tree.Feature("input-tag") + inputTagField = tree.ID(inputTagUI, "field") +) + +type inputTagDemo struct { + t *inputtag.InputTag + tags []string + bound bool +} + +var inputTagDemos = map[*State]*inputTagDemo{} + +func inputTagDemoFor(state *State) *inputTagDemo { + if demo := inputTagDemos[state]; demo != nil { + return demo + } + demo := &inputTagDemo{t: inputtag.New().FieldID(inputTagField), tags: []string{"build-01", "db-primary"}} + inputTagDemos[state] = demo + return demo +} + +func (state *State) initializeInputTag() { inputTagDemoFor(state) } + +func (state *State) paintInputTag(canvas *gfx.Canvas, theme gfx.Theme, size gfx.Size) { + demo := inputTagDemoFor(state) + if state.editing && state.editor != nil && !demo.bound { + demo.bound = true + demo.t.Field().Bind(state.editor) + } + state.drawPage(canvas, theme, size, 440, state.Text("Input Tag · 标签输入", "Input Tag"), func(c ui.C) { + demo.t.View(c, state.Text("允许的主机", "Allowed hosts"), demo.tags, inputtag.Spec{ + Placeholder: state.Text("添加主机", "Add a host"), MaxTags: 6, RemoveLabel: state.Text("移除", "Remove"), + }).FillWidth() + if value, ok := demo.t.Added(); ok { + demo.tags = append(demo.tags, value) + } + if i, ok := demo.t.Removed(); ok { + demo.tags = slices.Delete(demo.tags, i, i+1) + } + }) +} diff --git a/internal/componentdemo/page_usage.go b/internal/componentdemo/page_usage.go index ca262e22a..d0b8d8192 100644 --- a/internal/componentdemo/page_usage.go +++ b/internal/componentdemo/page_usage.go @@ -26,6 +26,10 @@ var pageUsage = map[string]string{ "image-preview": `m.preview.View(c, imagepreview.Spec{Bitmap: m.bitmap, Title: "Screenshot"})`, "mentions": `m.mentions.View(c, &m.message, "Message", "", mentions.Spec{Options: m.people}).FillWidth()`, "tour": `m.tour.View(c, tour.Spec{Steps: m.steps})`, + "statistic": `m.sessions.View(c, statistic.Spec{Title: "Active sessions", Value: m.count, Group: true})`, + "input-tag": `m.hosts.View(c, "Allowed hosts", m.allowed, inputtag.Spec{}).FillWidth()`, + "autocomplete": `m.host.View(c, &m.hostField, "Host", "", autocomplete.Spec{Options: m.known})`, + "indicator": `indicator.View(c, "Inbox", indicator.Spec{Count: m.unread}, func() { ui.Button(c, "Inbox") })`, "upload": `m.upload.View(c, "Attachments", upload.Spec{Items: m.files, Multiple: true})`, "toggle-group": `m.toggleGroup.View(c, "Text alignment")`, "empty": `empty.View(c, empty.Spec{Title: "No projects yet"}, nil).Fill()`, diff --git a/internal/componentdemo/statistic.go b/internal/componentdemo/statistic.go new file mode 100644 index 000000000..e80966add --- /dev/null +++ b/internal/componentdemo/statistic.go @@ -0,0 +1,48 @@ +package componentdemo + +import ( + "math" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/ui/statistic" +) + +var statisticComponent = Component{ + ID: "statistic", Title: "Statistic", Category: "Data Display", Summary: "统计数值:标题、大号数字,可设小数位、千分位、前后缀与状态色。", + Source: "ui/statistic/statistic.go", paint: (*State).paintStatistic, + Examples: []Example{ + {ID: "default", Title: "数值读数", Description: "只显示数字本身;Precision 定小数位,Group 加千分位,Status 着状态色,NaN 与无穷显示为破折号。", Snippet: `m.sessions = statistic.New() +m.sessions.View(c, statistic.Spec{Title: "Active sessions", Value: m.count, Group: true}) +m.latency.View(c, statistic.Spec{Title: "Latency", Value: m.ms, Precision: 1, Suffix: "ms"})`, PageSnippet: `m.sessions = statistic.New() +m.sessions.View(c, statistic.Spec{Title: "Active sessions", Value: m.count, Group: true}) +m.latency.View(c, statistic.Spec{Title: "Latency", Value: m.ms, Precision: 1, Suffix: "ms"})`, PageSnippetZh: `m.sessions = statistic.New() +m.sessions.View(c, statistic.Spec{Title: "Active sessions", Value: m.count, Group: true}) +m.latency.View(c, statistic.Spec{Title: "Latency", Value: m.ms, Precision: 1, Suffix: "ms"})`}, + }, +} + +type statisticDemo struct{ sessions, latency, errors, missing *statistic.Statistic } + +var statisticDemos = map[*State]*statisticDemo{} + +func statisticDemoFor(state *State) *statisticDemo { + if demo := statisticDemos[state]; demo != nil { + return demo + } + demo := &statisticDemo{statistic.New(), statistic.New(), statistic.New(), statistic.New()} + statisticDemos[state] = demo + return demo +} + +func (state *State) paintStatistic(canvas *gfx.Canvas, theme gfx.Theme, size gfx.Size) { + demo := statisticDemoFor(state) + state.drawPage(canvas, theme, size, 520, state.Text("Statistic · 统计数值", "Statistic"), func(c ui.C) { + ui.Row(c).Gap(40).Children(func() { + demo.sessions.View(c, statistic.Spec{Title: state.Text("活跃会话", "Active sessions"), Value: 12840, Group: true}) + demo.latency.View(c, statistic.Spec{Title: state.Text("延迟", "Latency"), Value: 23.46, Precision: 1, Suffix: " ms", Status: ui.StatusSuccess}) + demo.errors.View(c, statistic.Spec{Title: state.Text("错误率", "Error rate"), Value: 4.2, Precision: 1, Suffix: "%", Status: ui.StatusDanger}) + demo.missing.View(c, statistic.Spec{Title: state.Text("无数据", "No data"), Value: math.NaN()}) + }) + }) +} diff --git a/internal/gallery/gallery_drive_test.go b/internal/gallery/gallery_drive_test.go index 2eded0c9a..94c224ac2 100644 --- a/internal/gallery/gallery_drive_test.go +++ b/internal/gallery/gallery_drive_test.go @@ -408,7 +408,7 @@ func TestEveryComponentPageSurvivesBeingOperated(t *testing.T) { // through the platform text service. The rest of the text-entry family is a // fixed snapshot; this list failing means one of them stopped (or started) // being editable and the gallery page should say so. -var editableComponents = []string{"code-diff", "code-editor", "code-merge", "field", "form", "input", "input-group", "input-number", "input-otp", "mentions", "pagination", "textarea"} +var editableComponents = []string{"code-diff", "code-editor", "code-merge", "field", "form", "input", "input-group", "input-number", "input-otp", "mentions", "autocomplete", "input-tag", "pagination", "textarea"} func editableHits(driver *app.Driver) []gfx.Hit { var fields []gfx.Hit diff --git a/text/editor.go b/text/editor.go index 60b6d899f..f1d664c19 100644 --- a/text/editor.go +++ b/text/editor.go @@ -68,6 +68,12 @@ type textChange struct { // thread, where native input and painting run. Read a string snapshot there // before starting background work; the returned string remains valid after edits. type Editor struct { + // OnDeleteAtEdge runs when DeleteBackward finds nothing before the caret to + // remove (forward false) or DeleteForward finds nothing after it (forward + // true): Backspace in an empty field, which a tag input takes as "remove the + // last tag". It runs on the event-loop thread; nil leaves the key a no-op. + OnDeleteAtEdge func(forward bool) + runes runeStore anchor int caret int @@ -442,6 +448,9 @@ func (editor *Editor) DeleteBackward() bool { editor.releaseCompositionHistory() caret := editor.caret if caret == 0 { + if editor.OnDeleteAtEdge != nil { + editor.OnDeleteAtEdge(false) + } return false } start := editor.runes.Prev(caret) @@ -466,6 +475,9 @@ func (editor *Editor) DeleteForward() bool { editor.releaseCompositionHistory() caret := editor.caret if caret == editor.runes.Len() { + if editor.OnDeleteAtEdge != nil { + editor.OnDeleteAtEdge(true) + } return false } end := editor.runes.Next(caret) diff --git a/text/editor_test.go b/text/editor_test.go index c25b3bd9b..8defae4cb 100644 --- a/text/editor_test.go +++ b/text/editor_test.go @@ -640,3 +640,22 @@ func TestArrowKeysAreMonotonicOnTheScreenInMixedText(t *testing.T) { } } } + +func TestDeleteAtTheEdgeIsReportedOnlyWhenNothingIsRemoved(t *testing.T) { + var editor Editor + var edges []bool + editor.OnDeleteAtEdge = func(forward bool) { edges = append(edges, forward) } + if editor.DeleteBackward() || editor.DeleteForward() { + t.Fatal("an empty editor deleted something") + } + if len(edges) != 2 || edges[0] || !edges[1] { + t.Fatalf("edges = %v, want [false true]", edges) + } + editor.Insert("ab") + editor.DeleteBackward() + editor.SetSelection(Range{Start: 0, End: 0}) + editor.DeleteForward() + if len(edges) != 2 { + t.Fatalf("a delete that removed text was reported as an edge: %v", edges) + } +} diff --git a/tools/docs/catalog_test.go b/tools/docs/catalog_test.go index c0ad678e7..e1b2a3e1f 100644 --- a/tools/docs/catalog_test.go +++ b/tools/docs/catalog_test.go @@ -486,6 +486,10 @@ func TestPageSnippetsHaveNoUndeclaredNames(t *testing.T) { "imagepreview": true, "mentions": true, "tour": true, + "statistic": true, + "inputtag": true, + "autocomplete": true, + "indicator": true, "questionnaire": true, "inputotp": true, "inputgroup": true, @@ -683,6 +687,10 @@ func TestModelFreePageSnippetsCompile(t *testing.T) { "imagepreview": "github.com/vivaui/viva/ui/imagepreview", "mentions": "github.com/vivaui/viva/ui/mentions", "tour": "github.com/vivaui/viva/ui/tour", + "statistic": "github.com/vivaui/viva/ui/statistic", + "inputtag": "github.com/vivaui/viva/ui/inputtag", + "autocomplete": "github.com/vivaui/viva/ui/autocomplete", + "indicator": "github.com/vivaui/viva/ui/indicator", "sidebar": "github.com/vivaui/viva/ui/sidebar", "multiselect": "github.com/vivaui/viva/ui/multiselect", "hierarchypicker": "github.com/vivaui/viva/ui/hierarchypicker", } diff --git a/ui/autocomplete/autocomplete.go b/ui/autocomplete/autocomplete.go new file mode 100644 index 000000000..b0d678fe7 --- /dev/null +++ b/ui/autocomplete/autocomplete.go @@ -0,0 +1,210 @@ +// Package autocomplete is the opt-in page control for a text field that suggests +// completions while the user types: a list of the options that contain what was +// typed opens under the field, and choosing one writes it into the field. Unlike a +// Combobox, the value stays free text: the user may type something that is in no +// option and keep it. A page keeps the field's value in a ui.Field and an +// Autocomplete in its model: +// +// m.host = autocomplete.New() +// // in the page: +// m.host.View(c, &m.hostField, "Host", "Hostname", autocomplete.Spec{Options: m.known}) +// if option, ok := m.host.Chosen(); ok { +// // the field already holds option +// } +// +// The list opens while the field has the keyboard and something is typed that at +// least one option contains, without regard to case, and an option equal to the +// text is not offered. Up and Down move through the options, Enter and Tab choose +// the highlighted one, and Escape closes the list until the text changes. Without +// a highlighted option Enter is left to the page, so it still submits a form. A +// press on an option chooses it without taking the keyboard from the field. +// +// It is a separate package so an application that does not import it pays +// nothing for it. Keep an Autocomplete in the model beside its field. Do not copy +// one after it has been declared. +package autocomplete + +import ( + "unicode" + "unicode/utf8" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/text" + "github.com/vivaui/viva/ui" +) + +// Spec declares the list. +type Spec struct { + // Options are the completions on offer, in the order the list shows the ones + // that match. Keep the slice in the model. + Options []string + // MaxRows is how many options the list shows at most; 6 when zero. + MaxRows int +} + +// Autocomplete is one field's list. +type Autocomplete struct { + open bool + matches []int + highlight int // the row highlighted, or -1 until a key moves it + typed string + dismissed string // the text Escape closed the list for + pending int // 1 + the option chosen since the last paint, or 0 + chosen int + spec Spec + field *ui.Field + id gfx.ID + fieldID gfx.ID + key func(gfx.KeyEvent) gfx.EventResult +} + +// New returns a closed list. +func New() *Autocomplete { + a := &Autocomplete{highlight: -1} + a.key = a.onKey + return a +} + +// FieldID names the field with an identity the application already holds, for a +// runner that resolves the platform text service by an application identity. +func (a *Autocomplete) FieldID(id gfx.ID) *Autocomplete { a.fieldID = id; return a } + +// Chosen reports the option the user chose since the paint before this one. +func (a *Autocomplete) Chosen() (string, bool) { + if a.chosen == 0 { + return "", false + } + return a.spec.Options[a.chosen-1], true +} + +// containsFold reports whether s has query in it, without regard to case. +func containsFold(s, query string) bool { + if query == "" { + return true + } + for i := range s { + rest, q := s[i:], query + for q != "" && rest != "" { + x, xs := utf8.DecodeRuneInString(rest) + y, ys := utf8.DecodeRuneInString(q) + if unicode.ToLower(x) != unicode.ToLower(y) { + break + } + rest, q = rest[xs:], q[ys:] + } + if q == "" { + return true + } + } + return false +} + +func (a *Autocomplete) refresh(c ui.C) bool { + a.matches = a.matches[:0] + editor := a.field.GetEditor() + if editor == nil || c.Canvas().Focused() != a.id { + return false + } + value := editor.String() + if value != a.typed { + a.typed, a.highlight, a.dismissed = value, -1, "" + } + if value == "" || value == a.dismissed { + return false + } + limit := a.spec.MaxRows + if limit <= 0 { + limit = 6 + } + for i, option := range a.spec.Options { + if len(a.matches) == limit { + break + } + if option != value && containsFold(option, value) { + a.matches = append(a.matches, i) + } + } + a.highlight = min(a.highlight, len(a.matches)-1) + return len(a.matches) > 0 +} + +func (a *Autocomplete) onKey(event gfx.KeyEvent) gfx.EventResult { + if !a.open || event.Release { + return gfx.EventResult{} + } + switch event.Key { + case gfx.KeyDown: + a.highlight = (a.highlight + 1) % len(a.matches) + return gfx.EventResult{Handled: true, Repaint: true} + case gfx.KeyUp: + if a.highlight <= 0 { + a.highlight = len(a.matches) - 1 + } else { + a.highlight-- + } + return gfx.EventResult{Handled: true, Repaint: true} + case gfx.KeyEnter, gfx.KeyTab: + if a.highlight < 0 { + return gfx.EventResult{} + } + a.choose(a.matches[a.highlight]) + return gfx.EventResult{Handled: true, Repaint: true} + case gfx.KeyEscape: + a.dismissed, a.open = a.typed, false + return gfx.EventResult{Handled: true, Repaint: true} + } + return gfx.EventResult{} +} + +// choose writes the option in place of the text. +func (a *Autocomplete) choose(index int) { + editor := a.field.GetEditor() + if editor == nil { + return + } + editor.SetSelection(text.Range{Start: 0, End: editor.RuneCount()}) + editor.Insert(a.spec.Options[index]) + a.pending, a.open = index+1, false +} + +// View declares the field and, while a completion is on offer, the list under it. +// label and placeholder are the field's. Declare the view on its own, not inside +// a Memo. +func (a *Autocomplete) View(c ui.C, field *ui.Field, label, placeholder string, spec Spec) ui.Box { + if a == nil { + panic("autocomplete: View needs its Autocomplete") + } + a.chosen, a.pending = a.pending, 0 + a.spec, a.field = spec, field + if a.id = a.fieldID; a.id.IsZero() { + a.id = ui.ID(c) + } + a.open = a.refresh(c) + box := ui.TextField(c, field, label, placeholder, ui.WithID(a.id)).OnKey(a.key) + if a.open { + ui.Popover(c, box, &a.open, ui.PopoverSpec{ + Align: ui.Start, Padding: 4, Instant: true, NoDismiss: true, KeepOpenOnAnchor: true, + }, func() { a.list(c) }) + } + return box +} + +func (a *Autocomplete) list(c ui.C) { + theme := c.Theme() + metrics := theme.Metrics + ui.Column(c).FillWidth().Children(func() { + for row, index := range a.matches { + item := c.KeyInt(index) + box := ui.Row(item).FillWidth().Items(ui.Center).Pad(metrics.GapItem).Radius(metrics.RadiusControl) + if row == a.highlight { + box = box.Background(theme.Accent) + } + box = box.HitWith(ui.ID(item), a.spec.Options[index], gfx.HitOptions{Role: gfx.RoleOption, SkipFocus: true}) + box.Hover(ui.Look{}.Background(theme.Hover)) + box.Children(func() { ui.Text(item, a.spec.Options[index]) }) + if box.Clicked() { + a.choose(index) + } + } + }) +} diff --git a/ui/autocomplete/autocomplete_test.go b/ui/autocomplete/autocomplete_test.go new file mode 100644 index 000000000..dc9d71900 --- /dev/null +++ b/ui/autocomplete/autocomplete_test.go @@ -0,0 +1,165 @@ +package autocomplete_test + +import ( + "testing" + + "github.com/vivaui/viva/app" + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/ui/autocomplete" +) + +var hosts = []string{"build-01", "build-02", "db-primary", "staging"} + +type model struct { + a *autocomplete.Autocomplete + field ui.Field + chosen []string + enters int +} + +func (m *model) page(c ui.C) { + ui.Column(c).Fill().Pad(16).Children(func() { + m.a.View(c, &m.field, "Host", "", autocomplete.Spec{Options: hosts}).FillWidth() + if v, ok := m.a.Chosen(); ok { + m.chosen = append(m.chosen, v) + } + }) +} + +type driver struct { + t *testing.T + *app.Driver +} + +func open(t *testing.T) (*model, driver) { + t.Helper() + m := &model{a: autocomplete.New()} + page := ui.NewPage(ui.PageConfig{View: m.page}) + d, err := app.NewDriver(ui.Configure(page, app.Config{Width: 400, Height: 320, Invalidator: new(app.Invalidator)}), nil) + if err != nil { + t.Fatal(err) + } + t.Cleanup(d.Close) + dr := driver{t, d} + dr.click("Host") + return m, dr +} + +func (d driver) click(label string) { + d.t.Helper() + hits := d.Snapshot().Hits + for i := len(hits) - 1; i >= 0; i-- { + if h := hits[i]; h.Label == label && !h.IsLabel && !h.ID.IsZero() { + if err := d.Click(h.Bounds.X+h.Bounds.Width/2, h.Bounds.Y+h.Bounds.Height/2); err != nil { + d.t.Fatal(err) + } + return + } + } + d.t.Fatalf("no control labeled %q", label) +} + +func (d driver) listed(label string) bool { + for _, h := range d.Snapshot().Hits { + if h.Label == label && h.Role == gfx.RoleOption { + return true + } + } + return false +} + +func (d driver) typ(s string) { + d.t.Helper() + if err := d.Type(s); err != nil { + d.t.Fatal(err) + } +} + +func (d driver) key(k gfx.Key) { + d.t.Helper() + if err := d.Key(k, 0); err != nil { + d.t.Fatal(err) + } +} + +func TestTypingListsTheOptionsThatContainIt(t *testing.T) { + _, d := open(t) + d.typ("BUILD") + if !d.listed("build-01") || !d.listed("build-02") || d.listed("staging") { + t.Fatal("the list does not follow what was typed") + } +} + +func TestAnOptionEqualToTheTextIsNotOffered(t *testing.T) { + _, d := open(t) + d.typ("staging") + if d.listed("staging") { + t.Fatal("the option the text already is was offered") + } +} + +func TestEnterWithoutAHighlightIsLeftToThePage(t *testing.T) { + m, d := open(t) + d.typ("bui") + d.key(gfx.KeyEnter) + if len(m.chosen) != 0 || m.field.GetEditor().String() != "bui" { + t.Fatalf("Enter chose something nobody highlighted: %v %q", m.chosen, m.field.GetEditor().String()) + } +} + +func TestArrowsAndEnterChoose(t *testing.T) { + m, d := open(t) + d.typ("build") + d.key(gfx.KeyDown) + d.key(gfx.KeyDown) + d.key(gfx.KeyUp) + d.key(gfx.KeyEnter) + if got := m.field.GetEditor().String(); got != "build-01" { + t.Fatalf("field = %q, want build-01", got) + } + if len(m.chosen) != 1 || m.chosen[0] != "build-01" { + t.Fatalf("chosen %v", m.chosen) + } +} + +func TestUpFromNothingGoesToTheLastOption(t *testing.T) { + m, d := open(t) + d.typ("build") + d.key(gfx.KeyUp) + d.key(gfx.KeyEnter) + if got := m.field.GetEditor().String(); got != "build-02" { + t.Fatalf("field = %q, want build-02", got) + } +} + +func TestPressingAnOptionChoosesIt(t *testing.T) { + m, d := open(t) + d.typ("db") + d.click("db-primary") + if got := m.field.GetEditor().String(); got != "db-primary" { + t.Fatalf("field = %q", got) + } +} + +func TestFreeTextIsKept(t *testing.T) { + m, d := open(t) + d.typ("elsewhere") + d.key(gfx.KeyEnter) + if got := m.field.GetEditor().String(); got != "elsewhere" { + t.Fatalf("field = %q", got) + } +} + +func TestEscapeClosesUntilTheTextChanges(t *testing.T) { + _, d := open(t) + d.typ("bu") + d.key(gfx.KeyEscape) + if d.listed("build-01") { + t.Fatal("Escape left the list open") + } + d.typ("i") + if !d.listed("build-01") { + t.Fatal("typing did not bring the list back") + } +} diff --git a/ui/facade.go b/ui/facade.go index d3593c32d..98f59cbfe 100644 --- a/ui/facade.go +++ b/ui/facade.go @@ -287,9 +287,9 @@ func TextField[T TextValue](c C, Value T, Label, placeholder string, opts ...Opt return base.TextField(c, Value, Label, placeholder, opts...) } -func TextFieldBase[T TextValue](c C, Value T, Label, placeholder string) Box { +func TextFieldBase[T TextValue](c C, Value T, Label, placeholder string, opts ...Option) Box { useField() - return base.TextFieldBase(c, Value, Label, placeholder) + return base.TextFieldBase(c, Value, Label, placeholder, opts...) } func TextArea[T TextValue](c C, Value T, Label, placeholder string, opts ...Option) Box { diff --git a/ui/indicator/indicator.go b/ui/indicator/indicator.go new file mode 100644 index 000000000..d65cf7195 --- /dev/null +++ b/ui/indicator/indicator.go @@ -0,0 +1,110 @@ +// Package indicator is the opt-in page layout for a count or a dot pinned to the +// corner of another control, the red mark of an unread count on an icon or an +// avatar. A page declares the control it marks inside Child, and says what the +// mark shows: +// +// indicator.View(c, "Inbox", indicator.Spec{Count: m.unread, Max: 99}, func() { +// ui.Button(c, "Inbox").Icon(inboxIcon).IconOnly().Ghost() +// }) +// +// A Count above zero shows the number, and above Max shows Max and a plus sign +// ("99+"); a Count of zero shows nothing unless ShowZero is set. Dot shows a plain +// dot in place of the number. Status colors the mark as an alert does, the danger +// color by default. The mark is pinned to the top right corner of the control, +// reaches outside it by half its size, and takes no room of its own, so adding it +// does not move the control. label names the group for assistive technology. +// +// Keep no state: the page gives the count each paint. Counts up to 99 and their capped +// forms have their words made once, so a warm paint allocates nothing. +// It is a separate package so an application that does not import it pays +// nothing for it. +package indicator + +import ( + "strconv" + + "github.com/vivaui/viva/ui" +) + +// Spec declares the mark. +type Spec struct { + // Count is the number shown. + Count int + // Max is the largest number shown as it is; above it the mark reads "Max+". 99 + // when zero. + Max int + // ShowZero shows the mark for a Count of zero. + ShowZero bool + // Dot shows a dot, whatever the count, while Count is above zero or ShowZero + // is set. + Dot bool + // Status colors the mark; the danger color by default. + Status ui.Status +} + +// texts are the words of the small counts, made once. +var texts = func() (t [100]string) { + for i := range t { + t[i] = strconv.Itoa(i) + } + return t +}() + +// pluses are the words of a capped count, made once. +var pluses = func() (t [100]string) { + for i := range t { + t[i] = strconv.Itoa(i) + "+" + } + return t +}() + +// text is the words of a count, cached for the small ones. +func text(count, max int) string { + if max <= 0 { + max = 99 + } + if count > max { + if max < len(pluses) { + return pluses[max] + } + return strconv.Itoa(max) + "+" + } + if count >= 0 && count < len(texts) { + return texts[count] + } + return strconv.Itoa(count) +} + +// View declares the control and its mark. child declares the control, one +// element. The result is the box that holds them. +func View(c ui.C, label string, spec Spec, child func()) ui.Box { + theme := c.Theme() + metrics := theme.Metrics + root := ui.Stack(c).Shrink(0).Label(label) + root.Children(func() { + child() + shown := spec.Count > 0 || spec.ShowZero + if !shown { + return + } + fill := theme.Danger + switch spec.Status { + case ui.StatusSuccess: + fill = theme.Success + case ui.StatusWarning: + fill = theme.WarningColor() + } + if spec.Dot { + ui.Row(c).Absolute().Top(-4).Right(-4).Size(10, 10).Radius(5).Background(fill).Border(2, theme.Background) + return + } + words := text(spec.Count, spec.Max) + size := metrics.FontSizeS + mark := ui.Row(c).Absolute().Top(-size*0.6).Right(-size*0.6).Height(size+6).Center().PadSides(0, 5, 0, 5) + mark = mark.Radius((size + 6) / 2).Background(fill) + mark.Children(func() { + ui.Text(c, words).FontSize(size).Color(theme.PrimaryForeground).Shrink(0) + }) + }) + return root +} diff --git a/ui/indicator/indicator_test.go b/ui/indicator/indicator_test.go new file mode 100644 index 000000000..9e413cc85 --- /dev/null +++ b/ui/indicator/indicator_test.go @@ -0,0 +1,95 @@ +package indicator_test + +import ( + "testing" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/ui/indicator" +) + +func texts(t *testing.T, spec indicator.Spec) (values map[string]bool, button gfx.Rect) { + t.Helper() + view := func(c ui.C) { + ui.Column(c).Fill().Pad(16).Children(func() { + indicator.View(c, "Inbox", spec, func() { ui.Button(c, "Inbox") }) + }) + } + theme := gfx.LightTheme() + page := ui.NewPage(ui.PageConfig{View: view, Theme: &theme}) + canvas := &gfx.Canvas{} + canvas.BeginFrame() + canvas.Reset() + page.Draw(canvas, gfx.Rect{Width: 320, Height: 200}, view) + canvas.EndFrame() + values = map[string]bool{} + for _, x := range canvas.Texts() { + values[x.Value] = true + } + for _, h := range canvas.Hits() { + if h.Label == "Inbox" && !h.IsLabel { + button = h.Bounds + } + } + return values, button +} + +func TestCountShowsAsNumberOrCapped(t *testing.T) { + for _, c := range []struct { + spec indicator.Spec + want string + }{ + {indicator.Spec{Count: 7}, "7"}, + {indicator.Spec{Count: 120}, "99+"}, + {indicator.Spec{Count: 12, Max: 9}, "9+"}, + {indicator.Spec{Count: 0, ShowZero: true}, "0"}, + {indicator.Spec{Count: 1234, Max: 1000}, "1000+"}, + } { + got, _ := texts(t, c.spec) + if !got[c.want] { + t.Errorf("%+v: %q is not shown (have %v)", c.spec, c.want, got) + } + } +} + +func TestNothingShownForZeroAndDotShowsNoNumber(t *testing.T) { + got, _ := texts(t, indicator.Spec{Count: 0}) + if len(got) != 1 { + t.Errorf("a zero count shows %v", got) + } + got, _ = texts(t, indicator.Spec{Count: 5, Dot: true}) + if got["5"] { + t.Error("a dot shows the number") + } +} + +func TestTheMarkTakesNoRoom(t *testing.T) { + _, plain := texts(t, indicator.Spec{}) + _, marked := texts(t, indicator.Spec{Count: 5}) + if plain != marked { + t.Fatalf("the control moved or resized: %+v then %+v", plain, marked) + } +} + +func TestWarmPaintDoesNotAllocate(t *testing.T) { + view := func(c ui.C) { + ui.Column(c).Fill().Pad(16).Children(func() { + indicator.View(c, "Inbox", indicator.Spec{Count: 12}, func() { ui.Button(c, "Inbox") }) + }) + } + theme := gfx.LightTheme() + page := ui.NewPage(ui.PageConfig{View: view, Theme: &theme}) + canvas := &gfx.Canvas{} + canvas.SetReduceMotion(true) + draw := func() { + canvas.BeginFrame() + canvas.Reset() + page.Draw(canvas, gfx.Rect{Width: 320, Height: 200}, view) + canvas.EndFrame() + } + draw() + draw() + if n := testing.AllocsPerRun(100, draw); n != 0 { + t.Fatalf("a warm paint allocates %v times", n) + } +} diff --git a/ui/inputtag/inputtag.go b/ui/inputtag/inputtag.go new file mode 100644 index 000000000..9ac780bfe --- /dev/null +++ b/ui/inputtag/inputtag.go @@ -0,0 +1,281 @@ +// Package inputtag is the opt-in page control for entering several short values +// as tags: the values entered so far are tags in a row, each with a close button, +// followed by a text field to type the next. A page keeps the values in its model +// and an InputTag beside them: +// +// m.hosts = inputtag.New() +// // in the page: +// m.hosts.View(c, "Allowed hosts", m.allowed, inputtag.Spec{Placeholder: "Add a host"}).FillWidth() +// if value, ok := m.hosts.Added(); ok { +// m.allowed = append(m.allowed, value) +// } +// if i, ok := m.hosts.Removed(); ok { +// m.allowed = slices.Delete(m.allowed, i, i+1) +// } +// +// Enter, or a typed Separator (a comma by default), adds what is in the field as +// a tag; Backspace in the empty field removes the last tag, and the close button +// of a tag removes that one. Empty or white-space-only entries are ignored, and a +// value already in the list is not added twice unless AllowDuplicates is set. The +// control reports what the user did and the page changes its list: the same +// answer as for an alert's close button, so the list stays the page's. +// +// MaxTags stops adding when the list is that long; Validate can refuse a value, +// and the field then keeps its text and shows the invalid look. Rejected reports +// the refusal. +// +// It is a separate package so an application that does not import it pays +// nothing for it. Keep an InputTag in the model. Do not copy one after it has been +// declared. +package inputtag + +import ( + "strings" + "unicode/utf8" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/text" + "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/ui/tag" +) + +// Spec declares the control. +type Spec struct { + // Placeholder is shown in the field while it and the list are empty. + Placeholder string + // Separator is the rune that adds the typed value; ',' when zero. NoSeparator + // leaves only Enter. + Separator rune + NoSeparator bool + // MaxTags is how many tags the list may have; zero is no limit. + MaxTags int + // AllowDuplicates lets a value be added that is already in the list. + AllowDuplicates bool + // Validate returns whether a value may be added; nil accepts every value. + Validate func(value string) bool + // Disabled leaves the field and the close buttons inert. + Disabled bool + // RemoveLabel is the accessible name of a close button, before the tag's text: + // "Remove" when empty. + RemoveLabel string +} + +// InputTag is one control's state: the text being typed and what was done. +type InputTag struct { + field ui.Field + added string + hasAdded bool + removed int // 1 + the index removed since the paint before, or 0 + rejected bool + invalid bool + // pending is what a key or a press did since the last paint, reported by the + // paint after it. + pending struct { + added string + hasAdded bool + removeLast bool + rejected bool + } + key func(gfx.KeyEvent) gfx.EventResult + deleteAtEdge func(forward bool) + spec Spec + tags []string + labels []name // "Remove ", kept while the tag stays + id gfx.ID + fieldID gfx.ID +} + +// New returns an empty control. +func New() *InputTag { + t := &InputTag{} + t.key = t.onKey + t.deleteAtEdge = t.onDeleteAtEdge + return t +} + +// FieldID names the field with an identity the application already holds, and +// Field is the text field behind the control, for a runner that binds the editor +// the platform edits to it with Field.Bind. A page needs neither. +func (t *InputTag) FieldID(id gfx.ID) *InputTag { t.fieldID = id; return t } + +// Field is the text field behind the control. +func (t *InputTag) Field() *ui.Field { return &t.field } + +// Added returns the value the user added since the paint before this one. +func (t *InputTag) Added() (string, bool) { return t.added, t.hasAdded } + +// Removed returns the index of the tag the user removed since the paint before +// this one. +func (t *InputTag) Removed() (int, bool) { return t.removed - 1, t.removed > 0 } + +// Rejected reports whether a value was refused (by Validate, MaxTags or as a +// duplicate) since the paint before this one. +func (t *InputTag) Rejected() bool { return t.rejected } + +func (s *Spec) separator() rune { + if s.NoSeparator { + return -1 + } + if s.Separator == 0 { + return ',' + } + return s.Separator +} + +// accepts says whether value may join the list, and records a refusal. +func (t *InputTag) accepts(value string) bool { + ok := value != "" + if ok && !t.spec.AllowDuplicates { + for _, existing := range t.tags { + if existing == value { + ok = false + break + } + } + } + if ok && t.spec.MaxTags > 0 && len(t.tags) >= t.spec.MaxTags { + ok = false + } + if ok && t.spec.Validate != nil && !t.spec.Validate(value) { + ok = false + } + return ok +} + +// commit takes the typed text as a tag, or refuses it. +func (t *InputTag) commit() { + editor := t.field.GetEditor() + if editor == nil { + return + } + value := strings.TrimSpace(editor.String()) + if value == "" { + return + } + if !t.accepts(value) { + t.pending.rejected, t.invalid = true, true + return + } + t.pending.added, t.pending.hasAdded, t.invalid = value, true, false + clear(editor) +} + +// clear empties the editor. +func clear(editor *text.Editor) { + editor.SetSelection(text.Range{Start: 0, End: editor.RuneCount()}) + editor.DeleteBackward() +} + +func (t *InputTag) onKey(event gfx.KeyEvent) gfx.EventResult { + if event.Release || t.spec.Disabled { + return gfx.EventResult{} + } + editor := t.field.GetEditor() + switch { + case event.Key == gfx.KeyEnter: + if editor != nil && strings.TrimSpace(editor.String()) != "" { + t.commit() + return gfx.EventResult{Handled: true, Repaint: true} + } + } + return gfx.EventResult{} +} + +// takeSeparated commits the text typed or pasted before a separator, and keeps +// what follows it in the field. +func (t *InputTag) takeSeparated() { + editor := t.field.GetEditor() + sep := t.spec.separator() + if editor == nil || sep < 0 { + return + } + value := editor.String() + i := strings.IndexRune(value, sep) + if i < 0 { + return + } + editor.SetSelection(text.Range{Start: 0, End: utf8.RuneCountInString(value[:i+utf8.RuneLen(sep)])}) + editor.DeleteBackward() + if value = strings.TrimSpace(value[:i]); value != "" { + if t.accepts(value) { + t.added, t.hasAdded, t.invalid = value, true, false + } else { + t.rejected, t.invalid = true, true + } + } +} + +// onDeleteAtEdge is Backspace in the empty field: it removes the last tag. +func (t *InputTag) onDeleteAtEdge(forward bool) { + if !forward && !t.spec.Disabled && len(t.tags) > 0 && t.field.GetEditor().RuneCount() == 0 { + t.pending.removeLast = true + } +} + +// View declares the tags and the field at c. tags are the values in the list, in +// order; keep the slice in the model. label names the field for assistive +// technology. Declare the view on its own, not inside a Memo. +func (t *InputTag) View(c ui.C, label string, tags []string, spec Spec) ui.Box { + if t == nil { + panic("inputtag: View needs its InputTag") + } + t.added, t.hasAdded, t.rejected, t.removed = t.pending.added, t.pending.hasAdded, t.pending.rejected, 0 + t.pending.added, t.pending.hasAdded, t.pending.rejected = "", false, false + if t.pending.removeLast { + t.pending.removeLast, t.removed = false, len(tags) + } + t.spec, t.tags = spec, tags + if editor := t.field.GetEditor(); editor != nil && editor.OnDeleteAtEdge == nil { + editor.OnDeleteAtEdge = t.deleteAtEdge + } + t.takeSeparated() + theme := c.Theme() + metrics := theme.Metrics + remove := spec.RemoveLabel + if remove == "" { + remove = "Remove" + } + for len(t.labels) < len(tags) { + t.labels = append(t.labels, name{}) + } + t.id = ui.ID(c) + if t.fieldID.IsZero() { + t.fieldID = ui.ID(c) + } + rim := theme.Input + if c.Canvas().Focused() == t.fieldID { + rim = theme.Primary + } + if t.invalid { + rim = theme.Danger + } + root := ui.Flow(c).Items(ui.Center).Gap(metrics.GapItem * 0.5).LineGap(metrics.GapItem * 0.5).Pad(metrics.GapItem) + root = root.Radius(metrics.RadiusControl).Border(1, rim) + root.Children(func() { + for i, value := range tags { + if n := &t.labels[i]; n.of != value || n.verb != remove { + n.of, n.verb, n.text = value, remove, remove+" "+value + } + key := c.Key(value) + if i < len(tags) && spec.AllowDuplicates { + key = c.KeyInt(i) + } + result := tag.View(key, value, tag.Spec{Closable: !spec.Disabled, CloseLabel: t.labels[i].text}) + if result.Closed { + t.removed = i + 1 + } + } + placeholder := "" + if len(tags) == 0 { + placeholder = spec.Placeholder + } + field := ui.TextFieldBase(c, &t.field, label, placeholder, ui.WithID(t.fieldID)).OnKey(t.key).Width(120).Grow(1) + if spec.Disabled { + field.Disabled(true) + } + }) + return root +} + +// name is the accessible name of one close button and what it was made from. +type name struct{ of, verb, text string } diff --git a/ui/inputtag/inputtag_test.go b/ui/inputtag/inputtag_test.go new file mode 100644 index 000000000..2595369bf --- /dev/null +++ b/ui/inputtag/inputtag_test.go @@ -0,0 +1,158 @@ +package inputtag_test + +import ( + "slices" + "testing" + + "github.com/vivaui/viva/app" + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/ui/inputtag" +) + +type model struct { + t *inputtag.InputTag + tags []string + spec inputtag.Spec + rej int +} + +func (m *model) page(c ui.C) { + ui.Column(c).Fill().Pad(16).Children(func() { + m.t.View(c, "Hosts", m.tags, m.spec).FillWidth() + if v, ok := m.t.Added(); ok { + m.tags = append(m.tags, v) + } + if i, ok := m.t.Removed(); ok { + m.tags = slices.Delete(m.tags, i, i+1) + } + if m.t.Rejected() { + m.rej++ + } + }) +} + +type driver struct { + t *testing.T + *app.Driver +} + +func open(t *testing.T, m *model) driver { + t.Helper() + m.t = inputtag.New() + page := ui.NewPage(ui.PageConfig{View: m.page}) + d, err := app.NewDriver(ui.Configure(page, app.Config{Width: 420, Height: 240, Invalidator: new(app.Invalidator)}), nil) + if err != nil { + t.Fatal(err) + } + t.Cleanup(d.Close) + dr := driver{t, d} + dr.click("Hosts") + return dr +} + +func (d driver) click(label string) { + d.t.Helper() + hits := d.Snapshot().Hits + for i := len(hits) - 1; i >= 0; i-- { + if h := hits[i]; h.Label == label && !h.IsLabel && !h.ID.IsZero() { + if err := d.Click(h.Bounds.X+h.Bounds.Width/2, h.Bounds.Y+h.Bounds.Height/2); err != nil { + d.t.Fatal(err) + } + return + } + } + d.t.Fatalf("no control labeled %q", label) +} + +func (d driver) typ(s string) { + d.t.Helper() + if err := d.Type(s); err != nil { + d.t.Fatal(err) + } +} + +func (d driver) key(k gfx.Key) { + d.t.Helper() + if err := d.Key(k, 0); err != nil { + d.t.Fatal(err) + } +} + +func TestEnterAddsATagAndBackspaceRemovesTheLast(t *testing.T) { + m := &model{} + d := open(t, m) + d.typ("alpha") + d.key(gfx.KeyEnter) + d.typ("beta") + d.key(gfx.KeyEnter) + if !slices.Equal(m.tags, []string{"alpha", "beta"}) { + t.Fatalf("tags %v", m.tags) + } + d.key(gfx.KeyBackspace) + if !slices.Equal(m.tags, []string{"alpha"}) { + t.Fatalf("after Backspace %v", m.tags) + } +} + +func TestBackspaceInANonEmptyFieldOnlyEdits(t *testing.T) { + m := &model{tags: []string{"alpha"}} + d := open(t, m) + d.typ("be") + d.key(gfx.KeyBackspace) + if !slices.Equal(m.tags, []string{"alpha"}) { + t.Fatalf("Backspace removed a tag while text was typed: %v", m.tags) + } +} + +func TestSeparatorAddsTheTypedValue(t *testing.T) { + m := &model{} + d := open(t, m) + d.typ("one,") + if !slices.Equal(m.tags, []string{"one"}) { + t.Fatalf("tags %v", m.tags) + } +} + +func TestDuplicatesBlankAndLimitAreRefused(t *testing.T) { + m := &model{tags: []string{"a"}, spec: inputtag.Spec{MaxTags: 2}} + d := open(t, m) + d.typ("a") + d.key(gfx.KeyEnter) + if len(m.tags) != 1 || m.rej == 0 { + t.Fatalf("a duplicate was added or not reported: %v rej %d", m.tags, m.rej) + } + d.key(gfx.KeyBackspace) // removes nothing of the typed text, which is still "a" + d.key(gfx.KeyEnter) + if len(m.tags) != 1 { + t.Fatalf("tags %v", m.tags) + } +} + +func TestCloseButtonRemovesThatTag(t *testing.T) { + m := &model{tags: []string{"a", "b", "c"}} + d := open(t, m) + d.click("Remove b") + if !slices.Equal(m.tags, []string{"a", "c"}) { + t.Fatalf("tags %v", m.tags) + } +} + +func TestWarmPaintDoesNotAllocate(t *testing.T) { + m := &model{t: inputtag.New(), tags: []string{"a", "b"}} + theme := gfx.LightTheme() + page := ui.NewPage(ui.PageConfig{View: m.page, Theme: &theme}) + canvas := &gfx.Canvas{} + canvas.SetReduceMotion(true) + draw := func() { + canvas.BeginFrame() + canvas.Reset() + page.Draw(canvas, gfx.Rect{Width: 420, Height: 240}, m.page) + canvas.EndFrame() + } + draw() + draw() + if n := testing.AllocsPerRun(100, draw); n != 0 { + t.Fatalf("a warm paint allocates %v times", n) + } +} diff --git a/ui/statistic/statistic.go b/ui/statistic/statistic.go new file mode 100644 index 000000000..1822fa54e --- /dev/null +++ b/ui/statistic/statistic.go @@ -0,0 +1,153 @@ +// Package statistic is the opt-in page control for one number shown as a +// reading: a muted title, then the value in a large size with its prefix and +// suffix, formatted to a number of decimals with digit groups. A page keeps a +// Statistic in its model and gives it the number each paint: +// +// m.sessions = statistic.New() +// // in the page: +// m.sessions.View(c, statistic.Spec{Title: "Active sessions", Value: m.count, Group: true}) +// m.latency.View(c, statistic.Spec{Title: "Latency", Value: m.ms, Precision: 1, Suffix: "ms"}) +// +// Precision is the number of decimals; Group puts a comma between thousands +// (GroupSeparator changes it). Status colors the value as an alert or a tag +// does: success, warning or danger take the theme's color for it. NaN and the +// infinities are shown as an em dash, the usual mark of a reading that is not +// there. +// +// Unlike metriccard, which is a card with a trend and a description, this is the +// number alone, to place in a row, a toolbar or a card of the page's own. The +// formatted text is made again only when the number or its format changes, so a +// warm paint of an unchanged reading allocates nothing. Keep a Statistic in the +// model; do not copy one after it has been declared. +package statistic + +import ( + "math" + "strconv" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" +) + +// Spec declares one reading. +type Spec struct { + // Title is the muted caption above the value; not drawn when empty. + Title string + // Value is the number. + Value float64 + // Precision is the number of decimals shown. + Precision int + // Group puts GroupSeparator between the thousands of the integer part. + Group bool + // GroupSeparator is the rune between groups; ',' when zero. + GroupSeparator rune + // Prefix and Suffix are written around the number, such as a currency sign or a + // unit. They take the value's color. + Prefix, Suffix string + // Status colors the value; the zero value keeps the foreground. + Status ui.Status + // ValueSize is the value's font size; 24 when zero. + ValueSize float32 +} + +// Statistic is one reading and the text made from it. +type Statistic struct { + last Spec + text string + label string // the title and the text, the reading's name for assistive technology + made bool +} + +// New returns a reading. +func New() *Statistic { return &Statistic{} } + +// Format writes value with precision decimals, and with sep between groups of +// three digits of the integer part when sep is not zero. NaN and infinities are +// an em dash. +func Format(value float64, precision int, sep rune) string { + if math.IsNaN(value) || math.IsInf(value, 0) { + return "—" + } + precision = max(precision, 0) + digits := strconv.FormatFloat(math.Abs(value), 'f', precision, 64) + whole, fraction := digits, "" + for i := 0; i < len(digits); i++ { + if digits[i] == '.' { + whole, fraction = digits[:i], digits[i:] + break + } + } + out := make([]byte, 0, len(digits)+len(digits)/3+2) + // A value that rounds to zero is not negative. + if value < 0 && (precision == 0 && math.Round(value) != 0 || precision > 0 && !allZero(digits)) { + out = append(out, '-') + } + for i := 0; i < len(whole); i++ { + if sep != 0 && i > 0 && (len(whole)-i)%3 == 0 { + out = append(out, string(sep)...) + } + out = append(out, whole[i]) + } + return string(append(out, fraction...)) +} + +func allZero(digits string) bool { + for i := 0; i < len(digits); i++ { + if digits[i] != '0' && digits[i] != '.' { + return false + } + } + return true +} + +// Text is the number as View shows it, with the prefix and suffix. +func (s *Statistic) Text(spec Spec) string { + if s.made && s.last.Value == spec.Value && s.last.Precision == spec.Precision && s.last.Group == spec.Group && + s.last.GroupSeparator == spec.GroupSeparator && s.last.Prefix == spec.Prefix && s.last.Suffix == spec.Suffix && s.last.Title == spec.Title || + s.made && math.IsNaN(spec.Value) && math.IsNaN(s.last.Value) && s.last.Precision == spec.Precision && + s.last.Prefix == spec.Prefix && s.last.Suffix == spec.Suffix && s.last.Title == spec.Title { + return s.text + } + var sep rune + if spec.Group { + if sep = spec.GroupSeparator; sep == 0 { + sep = ',' + } + } + s.text = spec.Prefix + Format(spec.Value, spec.Precision, sep) + spec.Suffix + s.label = spec.Title + " " + s.text + s.last, s.made = spec, true + return s.text +} + +// View declares the reading at c. The reading is as wide as its text and as tall +// as its title and value. Declare it on its own, not inside a Memo. +func (s *Statistic) View(c ui.C, spec Spec) ui.Box { + if s == nil { + panic("statistic: View needs its Statistic") + } + text := s.Text(spec) + theme := c.Theme() + metrics := theme.Metrics + size := spec.ValueSize + if size <= 0 { + size = 24 + } + ink := theme.Foreground + switch spec.Status { + case ui.StatusSuccess: + ink = theme.Success + case ui.StatusWarning: + ink = theme.WarningColor() + case ui.StatusDanger: + ink = theme.Danger + } + root := ui.Column(c).Gap(4).HitWith(ui.ID(c), s.label, gfx.HitOptions{Role: gfx.RoleStatus, SkipFocus: true}) + root.Children(func() { + if spec.Title != "" { + ui.Text(c, spec.Title).FontSize(metrics.FontSizeS).Muted() + } + ui.Text(c, text).FontSize(size).Weight(gfx.WeightMedium).Color(ink) + }) + return root +} diff --git a/ui/statistic/statistic_test.go b/ui/statistic/statistic_test.go new file mode 100644 index 000000000..f48f10d6b --- /dev/null +++ b/ui/statistic/statistic_test.go @@ -0,0 +1,71 @@ +package statistic_test + +import ( + "math" + "testing" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/ui/statistic" +) + +func TestFormat(t *testing.T) { + for _, c := range []struct { + v float64 + prec int + sep rune + want string + }{ + {0, 0, 0, "0"}, {1234567, 0, ',', "1,234,567"}, {999, 0, ',', "999"}, {1000, 0, ',', "1,000"}, + {-1234.5, 1, ',', "-1,234.5"}, {3.14159, 2, 0, "3.14"}, {2, 2, 0, "2.00"}, {-0.001, 2, 0, "0.00"}, + {12345.678, 1, '.', "12.345.7"}, {math.NaN(), 0, 0, "—"}, {math.Inf(1), 0, 0, "—"}, {-4, -3, 0, "-4"}, + } { + if got := statistic.Format(c.v, c.prec, c.sep); got != c.want { + t.Errorf("Format(%v, %d, %q) = %q, want %q", c.v, c.prec, c.sep, got, c.want) + } + } +} + +func TestTextAddsPrefixAndSuffixAndKeepsItWhileUnchanged(t *testing.T) { + s := statistic.New() + spec := statistic.Spec{Value: 1234.5, Precision: 1, Group: true, Prefix: "$", Suffix: " ms"} + if got := s.Text(spec); got != "$1,234.5 ms" { + t.Fatalf("Text = %q", got) + } + nan := statistic.Spec{Value: math.NaN()} + s.Text(nan) + if n := testing.AllocsPerRun(100, func() { s.Text(nan) }); n != 0 { + t.Fatalf("an unchanged NaN reading allocates %v times", n) + } +} + +func TestWarmPaintDoesNotAllocate(t *testing.T) { + s := statistic.New() + view := func(c ui.C) { + ui.Column(c).Fill().Pad(16).Children(func() { + s.View(c, statistic.Spec{Title: "Sessions", Value: 12840, Group: true, Status: ui.StatusSuccess}) + }) + } + theme := gfx.LightTheme() + page := ui.NewPage(ui.PageConfig{View: view, Theme: &theme}) + canvas := &gfx.Canvas{} + canvas.SetReduceMotion(true) + draw := func() { + canvas.BeginFrame() + canvas.Reset() + page.Draw(canvas, gfx.Rect{Width: 320, Height: 200}, view) + canvas.EndFrame() + } + draw() + draw() + if n := testing.AllocsPerRun(100, draw); n != 0 { + t.Fatalf("a warm paint allocates %v times", n) + } +} + +func BenchmarkFormat(b *testing.B) { + b.ReportAllocs() + for i := 0; i < b.N; i++ { + statistic.Format(1234567.891, 2, ',') + } +} diff --git a/website/content/guides/en/components.md b/website/content/guides/en/components.md index a6eaca8c7..23f7f4681 100644 --- a/website/content/guides/en/components.md +++ b/website/content/guides/en/components.md @@ -27,7 +27,7 @@ A page control for a heavy or stateful component lives in its own package under - Editors and visuals: `ui/codeeditor`, `ui/textview`, `ui/chart`, `ui/markdown`, `ui/image`, `ui/calendar`, `ui/carousel`, `ui/columnresize`, `ui/reordergrid` - Navigation and overlays: `ui/command`, `ui/menubar`, `ui/navigationmenu`, `ui/sidebar`, `ui/hovercard` -- Data and inputs: `ui/avatar`, `ui/avatareditor`, `ui/attachment`, `ui/metriccard`, `ui/marker`, `ui/skeleton`, `ui/aspectratio`, `ui/questionnaire`, `ui/messagescroller`, `ui/message`, `ui/inputgroup`, `ui/inputotp`, `ui/multiselect`, `ui/hierarchypicker`, `ui/buttongroup`, `ui/togglegroup`, `ui/steps`, `ui/descriptions`, `ui/timeline`, `ui/rate`, `ui/inputnumber`, `ui/datepicker`, `ui/timepicker`, `ui/transfer`, `ui/alert`, `ui/tag`, `ui/breadcrumb`, `ui/card`, `ui/empty`, `ui/result`, `ui/pagination`, `ui/editabletabs`, `ui/popconfirm`, `ui/divider`, `ui/typography`, `ui/validate`, `ui/upload`, `ui/anchor`, `ui/comment`, `ui/imagepreview`, `ui/mentions`, `ui/tour`, `ui/steps`, `ui/descriptions`, `ui/timeline`, `ui/rate`, `ui/inputnumber`, `ui/datepicker`, `ui/timepicker`, `ui/transfer` +- Data and inputs: `ui/avatar`, `ui/avatareditor`, `ui/attachment`, `ui/metriccard`, `ui/marker`, `ui/skeleton`, `ui/aspectratio`, `ui/questionnaire`, `ui/messagescroller`, `ui/message`, `ui/inputgroup`, `ui/inputotp`, `ui/multiselect`, `ui/hierarchypicker`, `ui/buttongroup`, `ui/togglegroup`, `ui/steps`, `ui/descriptions`, `ui/timeline`, `ui/rate`, `ui/inputnumber`, `ui/datepicker`, `ui/timepicker`, `ui/transfer`, `ui/alert`, `ui/tag`, `ui/breadcrumb`, `ui/card`, `ui/empty`, `ui/result`, `ui/pagination`, `ui/editabletabs`, `ui/popconfirm`, `ui/divider`, `ui/typography`, `ui/validate`, `ui/upload`, `ui/anchor`, `ui/comment`, `ui/imagepreview`, `ui/mentions`, `ui/tour`, `ui/statistic`, `ui/inputtag`, `ui/autocomplete`, `ui/indicator`, `ui/steps`, `ui/descriptions`, `ui/timeline`, `ui/rate`, `ui/inputnumber`, `ui/datepicker`, `ui/timepicker`, `ui/transfer` `ui/textview` displays read-only text that the user can select and copy, such as logs and process output. Keep a `textview.View` in the model and call `m.output.Declare(c, textview.Spec{Source: lines, Scroll: true})`; `textview.Strings` adapts a string slice. The caller owns the lines, styles and actions. The view owns selection and drawing without an editing or undo model. diff --git a/website/content/guides/zh/components.md b/website/content/guides/zh/components.md index c33368507..02e0a627e 100644 --- a/website/content/guides/zh/components.md +++ b/website/content/guides/zh/components.md @@ -27,7 +27,7 @@ components.BeginButton(canvas, theme, hitSave, bounds).Outline("Save") - 编辑器与可视化:`ui/codeeditor`、`ui/textview`、`ui/chart`、`ui/markdown`、`ui/image`、`ui/calendar`、`ui/carousel`、`ui/columnresize`、`ui/reordergrid` - 导航与浮层:`ui/command`、`ui/menubar`、`ui/navigationmenu`、`ui/sidebar`、`ui/hovercard` -- 数据与输入:`ui/avatar`、`ui/avatareditor`、`ui/attachment`、`ui/metriccard`、`ui/marker`、`ui/skeleton`、`ui/aspectratio`、`ui/questionnaire`、`ui/messagescroller`、`ui/message`、`ui/inputgroup`、`ui/inputotp`、`ui/multiselect`、`ui/hierarchypicker`、`ui/buttongroup`、`ui/togglegroup`、`ui/steps`、`ui/descriptions`、`ui/timeline`、`ui/rate`、`ui/inputnumber`、`ui/datepicker`、`ui/timepicker`、`ui/transfer`、`ui/alert`、`ui/tag`、`ui/breadcrumb`、`ui/card`、`ui/empty`、`ui/result`、`ui/pagination`、`ui/editabletabs`、`ui/popconfirm`、`ui/divider`、`ui/typography`, `ui/validate`, `ui/upload`, `ui/anchor`, `ui/comment`, `ui/imagepreview`, `ui/mentions`, `ui/tour` +- 数据与输入:`ui/avatar`、`ui/avatareditor`、`ui/attachment`、`ui/metriccard`、`ui/marker`、`ui/skeleton`、`ui/aspectratio`、`ui/questionnaire`、`ui/messagescroller`、`ui/message`、`ui/inputgroup`、`ui/inputotp`、`ui/multiselect`、`ui/hierarchypicker`、`ui/buttongroup`、`ui/togglegroup`、`ui/steps`、`ui/descriptions`、`ui/timeline`、`ui/rate`、`ui/inputnumber`、`ui/datepicker`、`ui/timepicker`、`ui/transfer`、`ui/alert`、`ui/tag`、`ui/breadcrumb`、`ui/card`、`ui/empty`、`ui/result`、`ui/pagination`、`ui/editabletabs`、`ui/popconfirm`、`ui/divider`、`ui/typography`, `ui/validate`, `ui/upload`, `ui/anchor`, `ui/comment`, `ui/imagepreview`, `ui/mentions`, `ui/tour`, `ui/statistic`, `ui/inputtag`, `ui/autocomplete`, `ui/indicator` `ui/textview` 用来显示可选择、可复制的只读文本,例如日志和进程输出。在 model 中保留 `textview.View`,调用 `m.output.Declare(c, textview.Spec{Source: lines, Scroll: true})`;`textview.Strings` 可以把字符串切片适配成数据源。调用方拥有文本、样式和动作,视图负责选择与绘制,不带编辑或撤销模型。 diff --git a/website/src/lib/i18n.ts b/website/src/lib/i18n.ts index db433dbd8..500967ca2 100644 --- a/website/src/lib/i18n.ts +++ b/website/src/lib/i18n.ts @@ -187,6 +187,10 @@ const chineseComponentNames: Record = { 'image-preview': '图片预览', mentions: '提及', tour: '引导', + statistic: '统计数值', + 'input-tag': '标签输入', + autocomplete: '自动补全', + indicator: '角标', 'labeled-divider': '带文字分隔线', 'editable-tabs': '可编辑标签页', steps: '步骤条', @@ -326,6 +330,18 @@ const englishComponents: Record Date: Thu, 26 Nov 2026 16:13:09 +0800 Subject: [PATCH 02/16] feat(ui/overflowlist): add a toolbar row that folds into a More menu Shows as many icon actions as the width allows and puts the rest, from the end, in a More menu with their disabled state kept; Min keeps a floor. The count is measured from the container's laid-out width with the page's container queries, so it follows a resize without polling. --- cmd/viva/initfiles/AGENTS.md.txt | 4 +- docs/maintaining-controls.md | 2 +- docs/skills/building-with-viva/SKILL.md | 4 +- internal/componentdemo/catalog_d.go | 1 + internal/componentdemo/overflow_list.go | 60 ++++++++ internal/componentdemo/page_usage.go | 1 + tools/docs/catalog_test.go | 2 + ui/overflowlist/overflowlist.go | 144 ++++++++++++++++++ ui/overflowlist/overflowlist_test.go | 189 ++++++++++++++++++++++++ website/content/guides/en/components.md | 2 +- website/content/guides/zh/components.md | 2 +- website/src/lib/i18n.ts | 4 + 12 files changed, 408 insertions(+), 7 deletions(-) create mode 100644 internal/componentdemo/overflow_list.go create mode 100644 ui/overflowlist/overflowlist.go create mode 100644 ui/overflowlist/overflowlist_test.go diff --git a/cmd/viva/initfiles/AGENTS.md.txt b/cmd/viva/initfiles/AGENTS.md.txt index 63c0f683c..4076ce2d5 100644 --- a/cmd/viva/initfiles/AGENTS.md.txt +++ b/cmd/viva/initfiles/AGENTS.md.txt @@ -234,7 +234,7 @@ func (m *model) page(c ui.C) { `ui/marker`, `ui/skeleton`, `ui/aspectratio`, `ui/questionnaire`, `ui/messagescroller`, `ui/message`, `ui/inputgroup`, `ui/inputotp`, `ui/multiselect`, `ui/hierarchypicker`, `ui/buttongroup`, `ui/togglegroup`, `ui/steps`, `ui/descriptions`, `ui/timeline`, `ui/rate`, `ui/inputnumber`, `ui/datepicker`, `ui/timepicker`, - `ui/transfer`, `ui/alert`, `ui/tag`, `ui/breadcrumb`, `ui/card`, `ui/empty`, `ui/result`, `ui/pagination`, `ui/editabletabs`, `ui/popconfirm`, `ui/divider`, `ui/typography`, `ui/validate`, `ui/upload`, `ui/anchor`, `ui/comment`, `ui/imagepreview`, `ui/mentions`, `ui/tour`, `ui/statistic`, `ui/inputtag`, `ui/autocomplete`, `ui/indicator`. + `ui/transfer`, `ui/alert`, `ui/tag`, `ui/breadcrumb`, `ui/card`, `ui/empty`, `ui/result`, `ui/pagination`, `ui/editabletabs`, `ui/popconfirm`, `ui/divider`, `ui/typography`, `ui/validate`, `ui/upload`, `ui/anchor`, `ui/comment`, `ui/imagepreview`, `ui/mentions`, `ui/tour`, `ui/overflowlist`, `ui/statistic`, `ui/inputtag`, `ui/autocomplete`, `ui/indicator`. - For read-only selectable output, keep a `textview.View` in the model and call `m.output.Declare(c, textview.Spec{Source: lines, Scroll: true})`. The caller owns the lines, spans and actions; `ui/textview` owns selection and drawing without an editing model. @@ -320,7 +320,7 @@ func (m *model) page(c ui.C) { model: `m.drop.Over()` paints the highlight while files are over it, and `m.drop.Dropped()` returns the files (and their paths, empty in a browser) once. `ui.OpenFiles(c, options, done)` is the system's picker, answering with files that read the same way; `ui.FilePath(file)` is a file's path where there is one. For a whole upload - area with a file list, use `ui/upload`, `ui/anchor`, `ui/comment`, `ui/imagepreview`, `ui/mentions`, `ui/tour`, `ui/statistic`, `ui/inputtag`, `ui/autocomplete`, `ui/indicator`. + area with a file list, use `ui/upload`, `ui/anchor`, `ui/comment`, `ui/imagepreview`, `ui/mentions`, `ui/tour`, `ui/overflowlist`, `ui/statistic`, `ui/inputtag`, `ui/autocomplete`, `ui/indicator`. - For a divider between two panes, use `ui.Splitter` (see "Keys, drag and the mouse"), not a `DragState`. ## Mistakes that compile (and how each is reported) diff --git a/docs/maintaining-controls.md b/docs/maintaining-controls.md index be9560cfd..e53520591 100644 --- a/docs/maintaining-controls.md +++ b/docs/maintaining-controls.md @@ -53,7 +53,7 @@ Opt-in page packages live under `ui/` (`ui/codeeditor`, `ui/textview`, `ui `ui/metriccard`, `ui/marker`, `ui/sidebar`, `ui/buttongroup`, `ui/togglegroup`, `ui/multiselect`, `ui/hierarchypicker`, `ui/steps`, `ui/descriptions`, `ui/timeline`, `ui/rate`, -`ui/inputnumber`, `ui/datepicker`, `ui/timepicker`, `ui/transfer`, `ui/alert`, `ui/tag`, `ui/breadcrumb`, `ui/card`, `ui/empty`, `ui/result`, `ui/pagination`, `ui/editabletabs`, `ui/popconfirm`, `ui/divider`, `ui/typography`, `ui/validate`, `ui/upload`, `ui/anchor`, `ui/comment`, `ui/imagepreview`, `ui/mentions`, `ui/tour`, `ui/statistic`, `ui/inputtag`, `ui/autocomplete`, `ui/indicator`). +`ui/inputnumber`, `ui/datepicker`, `ui/timepicker`, `ui/transfer`, `ui/alert`, `ui/tag`, `ui/breadcrumb`, `ui/card`, `ui/empty`, `ui/result`, `ui/pagination`, `ui/editabletabs`, `ui/popconfirm`, `ui/divider`, `ui/typography`, `ui/validate`, `ui/upload`, `ui/anchor`, `ui/comment`, `ui/imagepreview`, `ui/mentions`, `ui/tour`, `ui/overflowlist`, `ui/statistic`, `ui/inputtag`, `ui/autocomplete`, `ui/indicator`). They import only the public `base`, `components`, `gfx`, `ui` and `window` packages, plus the focused `text` editor for editor-like controls and the root `markdown` parser for the Markdown view. They own stable handlers, and are never diff --git a/docs/skills/building-with-viva/SKILL.md b/docs/skills/building-with-viva/SKILL.md index 1d7f5b2ea..9d180cfeb 100644 --- a/docs/skills/building-with-viva/SKILL.md +++ b/docs/skills/building-with-viva/SKILL.md @@ -89,7 +89,7 @@ func (m *model) page(c ui.C) { ### Optional page packages and custom surfaces - A heavy or stateful page control lives in an opt-in package under `ui/`; import it only when the page uses it. -- Editors and visuals: `ui/codeeditor`, `ui/textview`, `ui/chart`, `ui/markdown`, `ui/image`, `ui/calendar`, `ui/carousel`, `ui/columnresize`, `ui/reordergrid`. Navigation and overlays: `ui/command`, `ui/menubar`, `ui/navigationmenu`, `ui/sidebar`, `ui/hovercard`. Data and inputs: `ui/avatar`, `ui/avatareditor`, `ui/attachment`, `ui/metriccard`, `ui/marker`, `ui/skeleton`, `ui/aspectratio`, `ui/questionnaire`, `ui/messagescroller`, `ui/message`, `ui/inputgroup`, `ui/inputotp`, `ui/multiselect`, `ui/hierarchypicker`, `ui/buttongroup`, `ui/togglegroup`, `ui/steps`, `ui/descriptions`, `ui/timeline`, `ui/rate`, `ui/inputnumber`, `ui/datepicker`, `ui/timepicker`, `ui/transfer`, `ui/alert`, `ui/tag`, `ui/breadcrumb`, `ui/card`, `ui/empty`, `ui/result`, `ui/pagination`, `ui/editabletabs`, `ui/popconfirm`, `ui/divider`, `ui/typography`, `ui/validate`, `ui/upload`, `ui/anchor`, `ui/comment`, `ui/imagepreview`, `ui/mentions`, `ui/tour`, `ui/statistic`, `ui/inputtag`, `ui/autocomplete`, `ui/indicator`. +- Editors and visuals: `ui/codeeditor`, `ui/textview`, `ui/chart`, `ui/markdown`, `ui/image`, `ui/calendar`, `ui/carousel`, `ui/columnresize`, `ui/reordergrid`. Navigation and overlays: `ui/command`, `ui/menubar`, `ui/navigationmenu`, `ui/sidebar`, `ui/hovercard`. Data and inputs: `ui/avatar`, `ui/avatareditor`, `ui/attachment`, `ui/metriccard`, `ui/marker`, `ui/skeleton`, `ui/aspectratio`, `ui/questionnaire`, `ui/messagescroller`, `ui/message`, `ui/inputgroup`, `ui/inputotp`, `ui/multiselect`, `ui/hierarchypicker`, `ui/buttongroup`, `ui/togglegroup`, `ui/steps`, `ui/descriptions`, `ui/timeline`, `ui/rate`, `ui/inputnumber`, `ui/datepicker`, `ui/timepicker`, `ui/transfer`, `ui/alert`, `ui/tag`, `ui/breadcrumb`, `ui/card`, `ui/empty`, `ui/result`, `ui/pagination`, `ui/editabletabs`, `ui/popconfirm`, `ui/divider`, `ui/typography`, `ui/validate`, `ui/upload`, `ui/anchor`, `ui/comment`, `ui/imagepreview`, `ui/mentions`, `ui/tour`, `ui/overflowlist`, `ui/statistic`, `ui/inputtag`, `ui/autocomplete`, `ui/indicator`. - For read-only selectable output, keep a `textview.View` in the model and call `m.output.Declare(c, textview.Spec{Source: lines, Scroll: true})`. The caller owns lines, spans and actions; `ui/textview` owns selection and drawing without an editing model. - The package name is the capability, never a `view` suffix. Name its state type by role, not by repeating the package: `calendar.State`, `message.Row`, `attachment.Card`, `hovercard.Card`. Keep locals out of the package name (`cal`, `msg`, `pic`); a model field may keep the domain noun (`m.calendar`). - Some packages expose `pkg.View(c, label, &state)` (`calendar.View`, `markdown.View`); others expose a method on the state (`avatar.New().View(c, label)`, `questionnaire.New().View(c, label)`). `go doc github.com/vivaui/viva/ui/` shows which. @@ -107,7 +107,7 @@ func (m *model) page(c ui.C) { - A control you paint is `ui.Control(c, label, &m.handlers).Grow(1).Draw(m.draw)`. `ui.Handlers` receives keys, pointer, wheel and, with `gfx.RoleTextField` or `gfx.RoleTerminal`, typing and IME through `Text`. Its parts are declared in `Draw` with `d.Canvas.Hit(part, r)`; an event on a part reaches the same handlers with the part as its target. - Custom layout: `ui.CustomLayout(c, &m.layout).Children(...)` with `ui.Layout`'s `MeasureWidth`, `PlaceWidth`, `MeasureHeight`, `PlaceHeight`. The page keeps identity, focus and hits; the layout owns the children's geometry. - Drag and drop: a `ui.DragState` in the model, `.DragSource(&m.drag)` and `.DropTarget(&m.drag, accept, drop)` on `Hit` boxes, or `d.DragSource`/`d.DropTarget` inside a `Draw`. The page routes the pointer; `Dragging()`, `Source()`, `Target()`, `At()` paint the gesture. A press that does not move is still a click. A split pane is `ui.Splitter(c, &m.split)` with a `ui.SplitterState`, not a drag. -- Files from the system: `.DropFiles(&m.drop)` with a `ui.FileDropState` makes a box take files dragged onto it (`Over()` for the highlight, `Dropped()` for the files, once); `ui.OpenFiles(c, options, done)` is the system's picker and `ui.FilePath(file)` a file's path where it has one. `ui/upload`, `ui/anchor`, `ui/comment`, `ui/imagepreview`, `ui/mentions`, `ui/tour`, `ui/statistic`, `ui/inputtag`, `ui/autocomplete`, `ui/indicator` is the whole area with its file list. +- Files from the system: `.DropFiles(&m.drop)` with a `ui.FileDropState` makes a box take files dragged onto it (`Over()` for the highlight, `Dropped()` for the files, once); `ui.OpenFiles(c, options, done)` is the system's picker and `ui.FilePath(file)` a file's path where it has one. `ui/upload`, `ui/anchor`, `ui/comment`, `ui/imagepreview`, `ui/mentions`, `ui/tour`, `ui/overflowlist`, `ui/statistic`, `ui/inputtag`, `ui/autocomplete`, `ui/indicator` is the whole area with its file list. - Painting your own thing: `ui.Slot(c).Draw(func(d *ui.DrawContext) { ... })`, with `d.Canvas.Fill`, `Rounded`, `Border`, `RoundedBorder`, `Elevate`, `DrawPath`, `Label`, `LabelCenter`, `d.Fade`, `d.DashedBorder`. A circle is a `Rounded` square. `Box.Rect()` is only valid in the paint that declared it. - A shortcut is declared where it acts: `if ui.Shortcut(c, ui.Primary, "s") { m.save() }`; `box.Shortcut(0, "delete")` acts while the focus is inside that element. Plain keys stay with a field being typed in. diff --git a/internal/componentdemo/catalog_d.go b/internal/componentdemo/catalog_d.go index 209f60c39..38fcc80af 100644 --- a/internal/componentdemo/catalog_d.go +++ b/internal/componentdemo/catalog_d.go @@ -27,6 +27,7 @@ var groupDComponents = []Component{ imagePreviewComponent, mentionsComponent, tourComponent, + overflowListComponent, statisticComponent, inputTagComponent, autocompleteComponent, diff --git a/internal/componentdemo/overflow_list.go b/internal/componentdemo/overflow_list.go new file mode 100644 index 000000000..f6caf3842 --- /dev/null +++ b/internal/componentdemo/overflow_list.go @@ -0,0 +1,60 @@ +package componentdemo + +import ( + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/ui/overflowlist" +) + +var overflowListComponent = Component{ + ID: "overflow-list", Title: "Overflow List", Category: "Navigation", Summary: "折叠列表:工具栏放不下时,末尾的操作自动收进「更多」菜单。", + Source: "ui/overflowlist/overflowlist.go", paint: (*State).paintOverflowList, + Examples: []Example{ + {ID: "default", Title: "随宽度折叠", Description: "同一组操作放在三种宽度里:放得下的留在行内,放不下的从末尾起进「更多」菜单,禁用状态保持;Min 保证至少留几个。", Snippet: `m.tools = overflowlist.New() +m.tools.View(c, "Actions", overflowlist.Spec{Items: m.actions}).FillWidth() +if i, ok := m.tools.Clicked(); ok { + m.run(m.actions[i]) +}`, PageSnippet: `m.tools = overflowlist.New() +m.tools.View(c, "Actions", overflowlist.Spec{Items: m.actions}).FillWidth() +if i, ok := m.tools.Clicked(); ok { + m.run(m.actions[i]) +}`, PageSnippetZh: `m.tools = overflowlist.New() +m.tools.View(c, "Actions", overflowlist.Spec{Items: m.actions}).FillWidth() +if i, ok := m.tools.Clicked(); ok { + m.run(m.actions[i]) +}`}, + }, +} + +type overflowListDemo struct { + rows [3]*overflowlist.OverflowList + items []overflowlist.Item +} + +var overflowListDemos = map[*State]*overflowListDemo{} + +func overflowListDemoFor(state *State) *overflowListDemo { + if demo := overflowListDemos[state]; demo != nil { + return demo + } + icon := gfx.Icon{ViewBox: 24, Stroke: 2, Cap: gfx.CapRound, Join: gfx.JoinRound, Commands: []gfx.PathCommand{ + gfx.MoveTo(12, 5), gfx.LineTo(12, 19), gfx.MoveTo(5, 12), gfx.LineTo(19, 12), + }} + demo := &overflowListDemo{rows: [3]*overflowlist.OverflowList{overflowlist.New(), overflowlist.New(), overflowlist.New()}} + for _, name := range []string{"Upload", "New file", "New folder", "Refresh", "Follow", "Download", "Delete"} { + demo.items = append(demo.items, overflowlist.Item{Label: name, Icon: icon, Disabled: name == "Delete"}) + } + overflowListDemos[state] = demo + return demo +} + +func (state *State) paintOverflowList(canvas *gfx.Canvas, theme gfx.Theme, size gfx.Size) { + demo := overflowListDemoFor(state) + state.drawPage(canvas, theme, size, 440, state.Text("Overflow List · 折叠列表", "Overflow List"), func(c ui.C) { + ui.Column(c).Gap(14).Children(func() { + for i, width := range [3]float32{340, 220, 130} { + demo.rows[i].View(c.KeyInt(i), state.Text("操作", "Actions"), overflowlist.Spec{Items: demo.items, MoreLabel: state.Text("更多", "More")}).Width(width) + } + }) + }) +} diff --git a/internal/componentdemo/page_usage.go b/internal/componentdemo/page_usage.go index d0b8d8192..95ee77c0a 100644 --- a/internal/componentdemo/page_usage.go +++ b/internal/componentdemo/page_usage.go @@ -30,6 +30,7 @@ var pageUsage = map[string]string{ "input-tag": `m.hosts.View(c, "Allowed hosts", m.allowed, inputtag.Spec{}).FillWidth()`, "autocomplete": `m.host.View(c, &m.hostField, "Host", "", autocomplete.Spec{Options: m.known})`, "indicator": `indicator.View(c, "Inbox", indicator.Spec{Count: m.unread}, func() { ui.Button(c, "Inbox") })`, + "overflow-list": `m.tools.View(c, "Actions", overflowlist.Spec{Items: m.actions}).FillWidth()`, "upload": `m.upload.View(c, "Attachments", upload.Spec{Items: m.files, Multiple: true})`, "toggle-group": `m.toggleGroup.View(c, "Text alignment")`, "empty": `empty.View(c, empty.Spec{Title: "No projects yet"}, nil).Fill()`, diff --git a/tools/docs/catalog_test.go b/tools/docs/catalog_test.go index e1b2a3e1f..4215abb5c 100644 --- a/tools/docs/catalog_test.go +++ b/tools/docs/catalog_test.go @@ -486,6 +486,7 @@ func TestPageSnippetsHaveNoUndeclaredNames(t *testing.T) { "imagepreview": true, "mentions": true, "tour": true, + "overflowlist": true, "statistic": true, "inputtag": true, "autocomplete": true, @@ -687,6 +688,7 @@ func TestModelFreePageSnippetsCompile(t *testing.T) { "imagepreview": "github.com/vivaui/viva/ui/imagepreview", "mentions": "github.com/vivaui/viva/ui/mentions", "tour": "github.com/vivaui/viva/ui/tour", + "overflowlist": "github.com/vivaui/viva/ui/overflowlist", "statistic": "github.com/vivaui/viva/ui/statistic", "inputtag": "github.com/vivaui/viva/ui/inputtag", "autocomplete": "github.com/vivaui/viva/ui/autocomplete", diff --git a/ui/overflowlist/overflowlist.go b/ui/overflowlist/overflowlist.go new file mode 100644 index 000000000..2dcda3fe1 --- /dev/null +++ b/ui/overflowlist/overflowlist.go @@ -0,0 +1,144 @@ +// Package overflowlist is the opt-in page control for a row of icon actions that +// shows as many as fit and puts the rest in a "More" menu: a toolbar that keeps +// working when its window or panel is narrowed. A page keeps an OverflowList in +// its model and gives it the actions each paint: +// +// m.tools = overflowlist.New() +// // in the page: +// m.tools.View(c, "Actions", overflowlist.Spec{Items: m.actions}).FillWidth() +// if i, ok := m.tools.Clicked(); ok { +// m.run(m.actions[i]) +// } +// +// An Item is an icon, the label that names it (its tooltip and accessible name +// when shown, its words in the menu when not) and whether it is Disabled. Items +// leave the row from the end, last first, and appear in the menu in their own +// order; a Disabled item stays disabled in the menu. When every item fits there is +// no menu button. Min keeps at least that many items in the row however narrow it +// gets, and the row never leaves room for fewer than one button besides More. +// +// The number that fit is measured from the width the control is placed in, never +// from what it holds, so it settles in the paint that first sees the width and +// again as the window is resized; it asks for nothing between resizes. +// +// It is a separate package so an application that does not import it pays +// nothing for it. Keep an OverflowList in the model: its menu state is made once. +// Do not copy one after it has been declared. +package overflowlist + +import ( + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" +) + +var moreIcon = gfx.Icon{ViewBox: 24, Stroke: 2, Cap: gfx.CapRound, Join: gfx.JoinRound, Commands: []gfx.PathCommand{ + gfx.MoveTo(5, 12), gfx.LineTo(5.01, 12), gfx.MoveTo(12, 12), gfx.LineTo(12.01, 12), gfx.MoveTo(19, 12), gfx.LineTo(19.01, 12), +}} + +// Item is one action. +type Item struct { + // Label names the action: its accessible name and tooltip in the row, its + // words in the menu. + Label string + // Icon is the glyph of the action's button. + Icon gfx.Icon + // Disabled leaves the action inert, in the row and in the menu. + Disabled bool +} + +// Spec declares the row. +type Spec struct { + // Items are the actions, in order. Keep the slice in the model. + Items []Item + // Min is how many items stay in the row however narrow it gets; one when + // zero. + Min int + // Gap is the space between buttons; the theme's item gap when zero. + Gap float32 + // MoreLabel is the accessible name of the menu button, "More" when empty. + MoreLabel string +} + +// OverflowList is one row and its menu. +type OverflowList struct { + open bool + clicked int // 1 + the item pressed in the paint being declared, or 0 +} + +// New returns a row. +func New() *OverflowList { return &OverflowList{} } + +// Clicked reports which action the user chose in the paint just made, from the row +// or from the menu. +func (o *OverflowList) Clicked() (int, bool) { return o.clicked - 1, o.clicked > 0 } + +// View declares the row at c. label names it for assistive technology. The row is +// one button high and as wide as the room it is given; give it FillWidth. Declare +// the view on its own, not inside a Memo. +func (o *OverflowList) View(c ui.C, label string, spec Spec) ui.Box { + if o == nil { + panic("overflowlist: View needs its OverflowList") + } + o.clicked = 0 + theme := c.Theme() + gap := spec.Gap + if gap <= 0 { + gap = theme.Metrics.GapItem + } + button := theme.Metrics.ControlHeight + more := spec.MoreLabel + if more == "" { + more = "More" + } + n := len(spec.Items) + root := ui.Container(c).FillWidth().Label(label) + root.Children(func() { + shown := n + // The widest row that fits: all of the items, or as many as leave room for the + // menu button. Each question is answered from the width the container had in the + // last layout. + if n > 0 && !c.AtLeast(ui.Width(span(n, button, gap))) { + floor := max(min(max(spec.Min, 1), n), 1) + shown = floor + for k := n - 1; k > floor; k-- { + if c.AtLeast(ui.Width(span(k+1, button, gap))) { + shown = k + break + } + } + } + ui.Row(c).FillWidth().Items(ui.Center).Gap(gap).Children(func() { + for i := 0; i < shown; i++ { + item := &spec.Items[i] + b := ui.Button(c.KeyInt(i), item.Label).Icon(item.Icon).IconOnly().Ghost().Disabled(item.Disabled).Shrink(0) + if b.Clicked() { + o.clicked = i + 1 + } + } + if shown < n { + ui.Spacer(c).Grow(1) + trigger := ui.Button(c, more).Icon(moreIcon).IconOnly().Ghost().Shrink(0) + if trigger.Clicked() { + o.open = !o.open + } + ui.Menu(c, trigger, &o.open, func(menu *ui.MenuItems) { + for i := shown; i < n; i++ { + entry := menu.Item(spec.Items[i].Label) + if spec.Items[i].Disabled { + entry.Disabled(true) + } + if entry.Clicked() { + o.clicked = i + 1 + } + } + }) + } + }) + }) + return root +} + +// span is the width of count buttons with a gap between each. +func span(count int, button, gap float32) float32 { + return float32(count)*button + float32(max(count-1, 0))*gap +} diff --git a/ui/overflowlist/overflowlist_test.go b/ui/overflowlist/overflowlist_test.go new file mode 100644 index 000000000..17fb5e6b4 --- /dev/null +++ b/ui/overflowlist/overflowlist_test.go @@ -0,0 +1,189 @@ +package overflowlist_test + +import ( + "fmt" + "testing" + + "github.com/vivaui/viva/app" + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/ui/overflowlist" +) + +var glyph = gfx.Icon{ViewBox: 24, Stroke: 2, Commands: []gfx.PathCommand{gfx.MoveTo(4, 12), gfx.LineTo(20, 12)}} + +type model struct { + o *overflowlist.OverflowList + items []overflowlist.Item + min int + clicked []int +} + +func newModel(n int) *model { + m := &model{o: overflowlist.New()} + for i := 0; i < n; i++ { + m.items = append(m.items, overflowlist.Item{Label: fmt.Sprintf("Tool %d", i), Icon: glyph}) + } + return m +} + +func (m *model) page(c ui.C) { + ui.Column(c).Fill().Pad(8).Children(func() { + m.o.View(c, "Actions", overflowlist.Spec{Items: m.items, Min: m.min}).FillWidth() + if i, ok := m.o.Clicked(); ok { + m.clicked = append(m.clicked, i) + } + }) +} + +type driver struct { + t *testing.T + *app.Driver +} + +func open(t *testing.T, m *model, width int) driver { + t.Helper() + page := ui.NewPage(ui.PageConfig{View: m.page}) + d, err := app.NewDriver(ui.Configure(page, app.Config{Width: width, Height: 200, Invalidator: new(app.Invalidator)}), nil) + if err != nil { + t.Fatal(err) + } + t.Cleanup(d.Close) + return driver{t, d} +} + +// row is the tool buttons in the row, left to right, and whether More is there. +func (d driver) row() (tools []string, more bool) { + for _, h := range d.Snapshot().Hits { + if h.IsLabel || h.Role != gfx.RoleButton { + continue + } + if h.Label == "More" { + more = true + } else { + tools = append(tools, h.Label) + } + } + return tools, more +} + +func (d driver) click(label string) { + d.t.Helper() + hits := d.Snapshot().Hits + for i := len(hits) - 1; i >= 0; i-- { + if h := hits[i]; h.Label == label && !h.IsLabel && !h.ID.IsZero() { + if err := d.Click(h.Bounds.X+h.Bounds.Width/2, h.Bounds.Y+h.Bounds.Height/2); err != nil { + d.t.Fatal(err) + } + return + } + } + d.t.Fatalf("no control labeled %q", label) +} + +func TestEverythingFitsThenThereIsNoMore(t *testing.T) { + m := newModel(4) + d := open(t, m, 600) + tools, more := d.row() + if len(tools) != 4 || more { + t.Fatalf("tools %v more %v", tools, more) + } +} + +func TestNarrowingMovesTheLastItemsIntoMoreAndWideningBringsThemBack(t *testing.T) { + m := newModel(6) + d := open(t, m, 600) + previous := 6 + for _, width := range []int{240, 180, 120, 80} { + if err := d.Resize(width, 200); err != nil { + t.Fatal(err) + } + if err := d.Pump(); err != nil { + t.Fatal(err) + } + tools, more := d.row() + if len(tools) >= 6 || !more { + t.Fatalf("width %d: %d tools, more %v; want fewer than all and a menu", width, len(tools), more) + } + if len(tools) > previous { + t.Fatalf("width %d: %d tools, more than at the wider width (%d)", width, len(tools), previous) + } + for i, label := range tools { + if want := fmt.Sprintf("Tool %d", i); label != want { + t.Fatalf("width %d: row has %v; items must leave from the end", width, tools) + } + } + previous = len(tools) + } + if err := d.Resize(600, 200); err != nil { + t.Fatal(err) + } + if err := d.Pump(); err != nil { + t.Fatal(err) + } + if tools, more := d.row(); len(tools) != 6 || more { + t.Fatalf("widened: %v more %v", tools, more) + } +} + +func TestNeverFewerThanTheMinimum(t *testing.T) { + m := newModel(6) + m.min = 3 + d := open(t, m, 40) + if tools, _ := d.row(); len(tools) < 3 { + t.Fatalf("only %d tools in a row that keeps at least 3", len(tools)) + } +} + +func TestAnOverflowedItemIsChosenFromTheMenuAndKeepsItsDisabledState(t *testing.T) { + m := newModel(6) + m.items[5].Disabled = true + d := open(t, m, 160) + tools, more := d.row() + if !more || len(tools) >= 6 { + t.Fatalf("not overflowed: %v %v", tools, more) + } + d.click("More") + var hidden, disabled bool + for _, h := range d.Snapshot().Hits { + if h.Label == "Tool 5" && !h.IsLabel { + hidden, disabled = true, h.Disabled + } + } + if !hidden || !disabled { + t.Fatalf("the last item in the menu: present %v disabled %v", hidden, disabled) + } + d.click("Tool 4") + if len(m.clicked) != 1 || m.clicked[0] != 4 { + t.Fatalf("clicked %v, want [4]", m.clicked) + } +} + +func TestClickingARowButtonReportsIt(t *testing.T) { + m := newModel(3) + d := open(t, m, 600) + d.click("Tool 1") + if len(m.clicked) != 1 || m.clicked[0] != 1 { + t.Fatalf("clicked %v", m.clicked) + } +} + +func TestWarmPaintDoesNotAllocate(t *testing.T) { + m := newModel(6) + theme := gfx.LightTheme() + page := ui.NewPage(ui.PageConfig{View: m.page, Theme: &theme}) + canvas := &gfx.Canvas{} + canvas.SetReduceMotion(true) + draw := func() { + canvas.BeginFrame() + canvas.Reset() + page.Draw(canvas, gfx.Rect{Width: 180, Height: 200}, m.page) + canvas.EndFrame() + } + draw() + draw() + draw() + if n := testing.AllocsPerRun(100, draw); n != 0 { + t.Fatalf("a warm paint allocates %v times", n) + } +} diff --git a/website/content/guides/en/components.md b/website/content/guides/en/components.md index 23f7f4681..d382a412a 100644 --- a/website/content/guides/en/components.md +++ b/website/content/guides/en/components.md @@ -27,7 +27,7 @@ A page control for a heavy or stateful component lives in its own package under - Editors and visuals: `ui/codeeditor`, `ui/textview`, `ui/chart`, `ui/markdown`, `ui/image`, `ui/calendar`, `ui/carousel`, `ui/columnresize`, `ui/reordergrid` - Navigation and overlays: `ui/command`, `ui/menubar`, `ui/navigationmenu`, `ui/sidebar`, `ui/hovercard` -- Data and inputs: `ui/avatar`, `ui/avatareditor`, `ui/attachment`, `ui/metriccard`, `ui/marker`, `ui/skeleton`, `ui/aspectratio`, `ui/questionnaire`, `ui/messagescroller`, `ui/message`, `ui/inputgroup`, `ui/inputotp`, `ui/multiselect`, `ui/hierarchypicker`, `ui/buttongroup`, `ui/togglegroup`, `ui/steps`, `ui/descriptions`, `ui/timeline`, `ui/rate`, `ui/inputnumber`, `ui/datepicker`, `ui/timepicker`, `ui/transfer`, `ui/alert`, `ui/tag`, `ui/breadcrumb`, `ui/card`, `ui/empty`, `ui/result`, `ui/pagination`, `ui/editabletabs`, `ui/popconfirm`, `ui/divider`, `ui/typography`, `ui/validate`, `ui/upload`, `ui/anchor`, `ui/comment`, `ui/imagepreview`, `ui/mentions`, `ui/tour`, `ui/statistic`, `ui/inputtag`, `ui/autocomplete`, `ui/indicator`, `ui/steps`, `ui/descriptions`, `ui/timeline`, `ui/rate`, `ui/inputnumber`, `ui/datepicker`, `ui/timepicker`, `ui/transfer` +- Data and inputs: `ui/avatar`, `ui/avatareditor`, `ui/attachment`, `ui/metriccard`, `ui/marker`, `ui/skeleton`, `ui/aspectratio`, `ui/questionnaire`, `ui/messagescroller`, `ui/message`, `ui/inputgroup`, `ui/inputotp`, `ui/multiselect`, `ui/hierarchypicker`, `ui/buttongroup`, `ui/togglegroup`, `ui/steps`, `ui/descriptions`, `ui/timeline`, `ui/rate`, `ui/inputnumber`, `ui/datepicker`, `ui/timepicker`, `ui/transfer`, `ui/alert`, `ui/tag`, `ui/breadcrumb`, `ui/card`, `ui/empty`, `ui/result`, `ui/pagination`, `ui/editabletabs`, `ui/popconfirm`, `ui/divider`, `ui/typography`, `ui/validate`, `ui/upload`, `ui/anchor`, `ui/comment`, `ui/imagepreview`, `ui/mentions`, `ui/tour`, `ui/overflowlist`, `ui/statistic`, `ui/inputtag`, `ui/autocomplete`, `ui/indicator`, `ui/steps`, `ui/descriptions`, `ui/timeline`, `ui/rate`, `ui/inputnumber`, `ui/datepicker`, `ui/timepicker`, `ui/transfer` `ui/textview` displays read-only text that the user can select and copy, such as logs and process output. Keep a `textview.View` in the model and call `m.output.Declare(c, textview.Spec{Source: lines, Scroll: true})`; `textview.Strings` adapts a string slice. The caller owns the lines, styles and actions. The view owns selection and drawing without an editing or undo model. diff --git a/website/content/guides/zh/components.md b/website/content/guides/zh/components.md index 02e0a627e..89580825c 100644 --- a/website/content/guides/zh/components.md +++ b/website/content/guides/zh/components.md @@ -27,7 +27,7 @@ components.BeginButton(canvas, theme, hitSave, bounds).Outline("Save") - 编辑器与可视化:`ui/codeeditor`、`ui/textview`、`ui/chart`、`ui/markdown`、`ui/image`、`ui/calendar`、`ui/carousel`、`ui/columnresize`、`ui/reordergrid` - 导航与浮层:`ui/command`、`ui/menubar`、`ui/navigationmenu`、`ui/sidebar`、`ui/hovercard` -- 数据与输入:`ui/avatar`、`ui/avatareditor`、`ui/attachment`、`ui/metriccard`、`ui/marker`、`ui/skeleton`、`ui/aspectratio`、`ui/questionnaire`、`ui/messagescroller`、`ui/message`、`ui/inputgroup`、`ui/inputotp`、`ui/multiselect`、`ui/hierarchypicker`、`ui/buttongroup`、`ui/togglegroup`、`ui/steps`、`ui/descriptions`、`ui/timeline`、`ui/rate`、`ui/inputnumber`、`ui/datepicker`、`ui/timepicker`、`ui/transfer`、`ui/alert`、`ui/tag`、`ui/breadcrumb`、`ui/card`、`ui/empty`、`ui/result`、`ui/pagination`、`ui/editabletabs`、`ui/popconfirm`、`ui/divider`、`ui/typography`, `ui/validate`, `ui/upload`, `ui/anchor`, `ui/comment`, `ui/imagepreview`, `ui/mentions`, `ui/tour`, `ui/statistic`, `ui/inputtag`, `ui/autocomplete`, `ui/indicator` +- 数据与输入:`ui/avatar`、`ui/avatareditor`、`ui/attachment`、`ui/metriccard`、`ui/marker`、`ui/skeleton`、`ui/aspectratio`、`ui/questionnaire`、`ui/messagescroller`、`ui/message`、`ui/inputgroup`、`ui/inputotp`、`ui/multiselect`、`ui/hierarchypicker`、`ui/buttongroup`、`ui/togglegroup`、`ui/steps`、`ui/descriptions`、`ui/timeline`、`ui/rate`、`ui/inputnumber`、`ui/datepicker`、`ui/timepicker`、`ui/transfer`、`ui/alert`、`ui/tag`、`ui/breadcrumb`、`ui/card`、`ui/empty`、`ui/result`、`ui/pagination`、`ui/editabletabs`、`ui/popconfirm`、`ui/divider`、`ui/typography`, `ui/validate`, `ui/upload`, `ui/anchor`, `ui/comment`, `ui/imagepreview`, `ui/mentions`, `ui/tour`, `ui/overflowlist`, `ui/statistic`, `ui/inputtag`, `ui/autocomplete`, `ui/indicator` `ui/textview` 用来显示可选择、可复制的只读文本,例如日志和进程输出。在 model 中保留 `textview.View`,调用 `m.output.Declare(c, textview.Spec{Source: lines, Scroll: true})`;`textview.Strings` 可以把字符串切片适配成数据源。调用方拥有文本、样式和动作,视图负责选择与绘制,不带编辑或撤销模型。 diff --git a/website/src/lib/i18n.ts b/website/src/lib/i18n.ts index 500967ca2..fe33c7084 100644 --- a/website/src/lib/i18n.ts +++ b/website/src/lib/i18n.ts @@ -187,6 +187,7 @@ const chineseComponentNames: Record = { 'image-preview': '图片预览', mentions: '提及', tour: '引导', + 'overflow-list': '折叠列表', statistic: '统计数值', 'input-tag': '标签输入', autocomplete: '自动补全', @@ -342,6 +343,9 @@ const englishComponents: Record Date: Thu, 26 Nov 2026 16:54:24 +0800 Subject: [PATCH 03/16] fix(windows): draw fallbacks from registered fonts The DirectWrite fallback builder searched the system font collection, which never holds a font registered with RegisterFont, so a face that named such a family as a fallback drew .notdef while the same family as the primary drew its glyphs. Build the fallback against the collection text formats are made from, the system's fonts and the application's, and key the cached fallback by that collection's revision. Companion: Motty's bundled icon font (t8y2/motty#1629). Refs: t8y2/motty#1629 --- .../font_fallback_registered_windows_test.go | 62 +++++++++++++++++++ .../platform/windows/font_fallback_windows.go | 19 +++++- 2 files changed, 78 insertions(+), 3 deletions(-) create mode 100644 internal/platform/windows/font_fallback_registered_windows_test.go diff --git a/internal/platform/windows/font_fallback_registered_windows_test.go b/internal/platform/windows/font_fallback_registered_windows_test.go new file mode 100644 index 000000000..4078337e4 --- /dev/null +++ b/internal/platform/windows/font_fallback_registered_windows_test.go @@ -0,0 +1,62 @@ +package windows + +import ( + "bytes" + "runtime" + "testing" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/internal/platform" +) + +// A font registered at run time is not in DirectWrite's system collection. A face +// that names it as a fallback therefore used to draw .notdef, as if the family +// were not installed, while the same family as the primary drew its glyphs. The +// fallback has to search the collection the text format is made from. +func TestRegisteredFontDrawsFallbackCharacters(t *testing.T) { + runtime.LockOSThread() + defer runtime.UnlockOSThread() + engine, err := theTextEngine() + if err != nil { + t.Skipf("no DirectWrite: %v", err) + } + family, unregister, err := engine.RegisterFont(testIconsFont) + if err != nil { + t.Fatalf("register the test font: %v", err) + } + defer unregister() + rasterizer, err := newDirectRasterizer() + if err != nil { + t.Skipf("no DirectWrite: %v", err) + } + defer rasterizer.close() + + white := gfx.Color{Red: 1, Green: 1, Blue: 1, Alpha: 1} + draw := func(face gfx.MonoFace, value string, cells int32) []byte { + runs := []gfx.TextRun{{Bytes: int32(len(value)), Cells: cells, Color: white}} + label := platform.TextLabel{Value: value, Width: 48, Height: 32, FontSize: 20, CellWidth: 12, Mono: true, MonoFace: face, Runs: runs} + pixels, _, err := rasterizer.rasterize(label, 1, 48, 32, false, 0) + if err != nil { + t.Fatal(err) + } + return append([]byte(nil), pixels...) + } + base := gfx.MonoFamily("Consolas") + // A code point in a private-use plane the test font does not map: every + // family in the test draws it as the last-resort box. + boxed := draw(base, "\U0010FFFE", 1) + if bytes.Equal(draw(gfx.MonoFamily(family), testIcon, 1), boxed) { + t.Fatal("the registered family as the primary drew the box") + } + stacked := draw(gfx.MonoStack(base, family), testIcon, 1) + if bytes.Equal(stacked, boxed) { + t.Fatal("the registered family as a fallback drew the box") + } + if bytes.Equal(stacked, draw(base, testIcon, 1)) { + t.Fatal("the registered fallback changed no pixels") + } + // What the primary draws must not change because of the fallback. + if !bytes.Equal(draw(gfx.MonoStack(base, family), "abc", 3), draw(base, "abc", 3)) { + t.Fatal("the fallback changed how the primary draws the characters it has") + } +} diff --git a/internal/platform/windows/font_fallback_windows.go b/internal/platform/windows/font_fallback_windows.go index 0664ce5d0..ff193f312 100644 --- a/internal/platform/windows/font_fallback_windows.go +++ b/internal/platform/windows/font_fallback_windows.go @@ -15,6 +15,7 @@ type unicodeRange struct{ first, last uint32 } // faceFallback is the font fallback a face draws the characters its family lacks with. type faceFallback struct { face gfx.MonoFace + fonts uint32 // customFonts.revision the fallback was built against fallback uintptr // an IDWriteFontFallback; 0 when it could not be made } @@ -28,13 +29,18 @@ func (rasterizer *directRasterizer) fontFallback(face gfx.MonoFace) uintptr { if len(names) == 0 { return 0 } + customFonts.RLock() + fonts := customFonts.revision + customFonts.RUnlock() for _, known := range rasterizer.fallbacks { - if known.face == face { + if known.face == face && known.fonts == fonts { return known.fallback } } fallback := rasterizer.buildFontFallback(names) - rasterizer.fallbacks = append(rasterizer.fallbacks, faceFallback{face: face, fallback: fallback}) + // An older revision stays until the rasterizer closes: a text format made + // earlier may hold it, and fonts are registered before the first paint. + rasterizer.fallbacks = append(rasterizer.fallbacks, faceFallback{face: face, fonts: fonts, fallback: fallback}) return fallback } @@ -68,7 +74,14 @@ func (rasterizer *directRasterizer) buildFontFallback(names []string) uintptr { // of its own kind. var addMapping func(this uintptr, ranges *unicodeRange, rangesCount uint32, names **uint16, namesCount uint32, collection uintptr, locale, base *uint16, scale float32) uintptr purego.RegisterFunc(&addMapping, vtable(builder, writeBuilderAddMapping)) - status := addMapping(builder, &everything, 1, &targets[0], uint32(len(targets)), 0, nil, nil, 1) + // The collection a text format is made from, the system's and the fonts the + // application registered, or the system's alone. A registered family is not + // in the system collection, so the fallback has to search this one or it is + // skipped as if it were not installed. + customFonts.RLock() + defer customFonts.RUnlock() + collection := customFonts.collection + status := addMapping(builder, &everything, 1, &targets[0], uint32(len(targets)), collection, nil, nil, 1) runtime.KeepAlive(targets) if hresult(status) != nil { return 0 From 40c51dd12cb60e94a636f2efe138d143c1d033a8 Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Thu, 26 Nov 2026 19:07:28 +0800 Subject: [PATCH 04/16] perf(app): diff each paint's hits against the published ones once The focus settling, the publish and the semantic mirror each compared the painted hits with the published ones, on different field subsets: the whole hit, the region fields, and again the whole hit to collect dirty ids. A repaint that changed one label walked the 4k-hit list three times. diffHits now makes one pass per paint and answers all three; once too many hits changed to patch the mirror, the rest of the list compares the region fields only. publish no longer asks again what settleFocus decided for the same paint: the decision is unsettled, synced or reused, and only an unsettled one (a canvas painted outside repaint) is decided in publish. Hits are compared as bytes first and by value when the bytes differ. The published list keeps the previous frame's strings reachable, so equal bytes are equal hits; a label formatted again with the same words still compares equal by value. M2 Pro, interleaved: LabelledPage 4k 315 -> 227 us, OneChanged 4k -42%, Changed 4k -12%; still zero allocations. --- app/hit_gate_test.go | 29 ++++-- app/painter.go | 207 +++++++++++++++++++++++++++---------------- 2 files changed, 151 insertions(+), 85 deletions(-) diff --git a/app/hit_gate_test.go b/app/hit_gate_test.go index c02ce3405..d5a5c91b7 100644 --- a/app/hit_gate_test.go +++ b/app/hit_gate_test.go @@ -185,16 +185,29 @@ func TestRepaintReleasesFocusWhenThePaintAsksWithoutChangingHits(t *testing.T) { // A page that formats its labels every frame declares the same text in a new // allocation each time: that is an unchanged hit list, which keeps the repaint on -// the path that skips the semantic mirror. -func TestSameHitsComparesLabelsByText(t *testing.T) { +// the path that skips the semantic mirror. Changed words still reach it. +func TestRepaintComparesLabelsByText(t *testing.T) { + page := &hitGatePage{label: "Clicked 3 times", bounds: gfx.Rect{Width: 80, Height: 20}} fresh := func(text string) string { return string([]byte(text)) } - published := []gfx.Hit{{ID: gfx.Item(1), Label: fresh("Clicked 3 times"), Value: fresh("3")}} - current := []gfx.Hit{{ID: gfx.Item(1), Label: fresh("Clicked 3 times"), Value: fresh("3")}} - if !sameHits(published, current) { - t.Fatal("the same labels in new allocations compared as a change") + config := Config{Title: "gate", Width: 200, Height: 80, Paint: page.paint} + var canvas gfx.Canvas + painter := newTestPainter(t, &canvas, config) + + page.label = fresh("Clicked 3 times") + frame, err := painter.repaint() + if err != nil { + t.Fatal(err) + } + if frame.Accessibility != nil { + t.Fatal("the same label in a new allocation republished the accessibility payload") + } + + page.label = fresh("Clicked 4 times") + frame, err = painter.repaint() + if err != nil { + t.Fatal(err) } - current[0].Label = fresh("Clicked 4 times") - if sameHits(published, current) { + if frame.Accessibility == nil || painter.accessibility[0].Label != "Clicked 4 times" { t.Fatal("a changed label compared as unchanged") } } diff --git a/app/painter.go b/app/painter.go index 3f5df4bcd..a210317b6 100644 --- a/app/painter.go +++ b/app/painter.go @@ -1,12 +1,14 @@ package app import ( + "bytes" "errors" "fmt" "math" "slices" "time" "unicode" + "unsafe" "github.com/vivaui/viva/gfx" "github.com/vivaui/viva/internal/framebuild" @@ -85,7 +87,6 @@ type painter struct { // allocations alive, so equal pointers mean equal bytes) lets a repaint that // declared the same hits reuse both instead of mirroring the list again. publishedHits []gfx.Hit - semanticDirty []gfx.ID publishedFocus gfx.ID publishedTrap gfx.ID publishedInitial gfx.ID @@ -98,13 +99,13 @@ type painter struct { publishedComposing bool publishedTextField bool hitsPublished bool - // hitsSame remembers, for the canvas as painted, whether its hits equal - // publishedHits (0 unknown, 1 equal, 2 different), so the focus settling - // and the publish of one paint compare the list once. - hitsSame uint8 - // focusSynced says the focus was synced with the canvas as painted, so the - // publish need not sync it again. - focusSynced bool + // hitChanges is how the canvas as painted differs from publishedHits, + // worked out once per paint for the focus settling, the publish and the + // semantic mirror (see diffHits). + hitChanges hitDiff + // focusSettled is what was decided about the focus for the canvas as + // painted, so the publish of a repaint does not decide it again. + focusSettled focusSettlement labelNames map[gfx.ID]string labelNamePeak int // controls draws the window buttons of a custom titlebar, on platforms where @@ -1042,6 +1043,17 @@ func (painter *painter) titlebarInsets() (leading, trailing float32) { return platformTitlebarInsets() } +// focusSettlement is what a paint decided about the focus: nothing yet, synced +// with the canvas, or kept because the canvas asks for nothing the focus and the +// input regions do not already reflect. +type focusSettlement uint8 + +const ( + focusUnsettled focusSettlement = iota + focusSynced + focusReused +) + // maxFocusPasses bounds the paints settleFocus adds to one frame: a page whose // every paint moves the focus somewhere new shows the last move. const maxFocusPasses = 2 @@ -1056,11 +1068,12 @@ func (painter *painter) settleFocus() { } for range maxFocusPasses { if !painter.regionsNeedSync() { + painter.focusSettled = focusReused return } before, beforeVisible := painter.focus.Focused(), painter.focus.KeyboardFocus() painter.focus.Sync(painter.canvas) - painter.focusSynced = true + painter.focusSettled = focusSynced if painter.focus.Focused() == before && painter.focus.KeyboardFocus() == beforeVisible { return } @@ -1081,7 +1094,7 @@ func (painter *painter) regionsNeedSync() bool { } func (painter *painter) paintCanvas() { - painter.hitsSame, painter.focusSynced = 0, false + painter.hitChanges.known, painter.focusSettled = false, focusUnsettled if painter.paint == nil { return } @@ -1131,10 +1144,14 @@ func (painter *painter) publish() (platform.Frame, error) { // A repaint settled the focus already; a publish of a canvas painted outside // repaint syncs it here. hitStructuresUnchanged := painter.hitStructuresUnchanged() - if !painter.focusSynced && painter.regionsNeedSync() { - painter.focus.Sync(painter.canvas) - painter.focusSynced = true - } else if !painter.focusSynced { + if painter.focusSettled == focusUnsettled { + painter.focusSettled = focusReused + if painter.regionsNeedSync() { + painter.focus.Sync(painter.canvas) + painter.focusSettled = focusSynced + } + } + if painter.focusSettled == focusReused { painter.reusedHits++ } if err := painter.syncCursor(); err != nil { @@ -1235,7 +1252,7 @@ func (painter *painter) trim() { framebuild.ReleaseTail(painter.accessibility, &painter.tails.accessibility) painter.hitScratch = framebuild.TrimCapacity(painter.hitScratch) painter.publishedHits = framebuild.TrimCapacity(painter.publishedHits) - painter.semanticDirty = framebuild.TrimCapacity(painter.semanticDirty) + painter.hitChanges.dirty = framebuild.TrimCapacity(painter.hitChanges.dirty) painter.publishedReturns = framebuild.TrimCapacity(painter.publishedReturns) painter.accessibility = framebuild.TrimCapacity(painter.accessibility) if painter.labelNamePeak > 4096 && len(painter.labelNames)*4 < painter.labelNamePeak { @@ -1597,13 +1614,7 @@ func (painter *painter) hitStructuresUnchanged() bool { if !painter.structuresUnchanged() { return false } - if painter.hitsSame == 0 { - painter.hitsSame = 2 - if hits := painter.canvas.Hits(); len(hits) == len(painter.publishedHits) && sameHits(painter.publishedHits, hits) { - painter.hitsSame = 1 - } - } - return painter.hitsSame == 1 + return painter.diffHits().same } // regionStructuresUnchanged reports whether the paint produced the same input @@ -1624,16 +1635,7 @@ func (painter *painter) regionStructuresUnchanged() bool { !slices.Equal(painter.canvas.FocusReturns(), painter.publishedReturns) { return false } - hits := painter.canvas.Hits() - if len(hits) != len(painter.publishedHits) { - return false - } - for index := range hits { - if !sameRegionHit(&painter.publishedHits[index], &hits[index]) { - return false - } - } - return true + return painter.diffHits().sameRegions } // sameRegionHit compares the hit fields Focus.Sync copies into an input.Region. @@ -1690,22 +1692,100 @@ func (painter *painter) structuresUnchanged() bool { return true } -// sameHits reports whether two hit lists are identical in the fields the -// semantic tree and the accessibility payload read. The text-editor geometry -// lives beside the hits (Canvas.HitText) and feeds neither, so it is not part of -// the comparison. Strings compare by content: a page that formats a label every -// frame makes a new allocation of the same text, and that is an unchanged hit. -// The index into the text table can only make the comparison stricter (an -// unnecessary publish), never more permissive. -func sameHits(published, current []gfx.Hit) bool { - return slices.Equal(published, current) +// maxPatchedHits is the most changed controls the semantic mirror patches in +// place; past it, rebuilding every entry is no dearer than finding them. +const maxPatchedHits = 64 + +// hitDiff is how one paint's hits differ from the published ones. Hits compare +// whole: the semantic tree and the accessibility payload read every field. The +// text-editor geometry lives beside the hits (Canvas.HitText) and feeds +// neither, so it is not part of the comparison. Strings compare by content: a +// page that formats a label every frame makes a new allocation of the same +// text, and that is an unchanged hit (see sameHit). The index into the text +// table can only make the comparison stricter (an unnecessary publish), never +// more permissive. +type hitDiff struct { + known bool + // same is set when every hit equals its published counterpart. + same bool + // sameRegions is set when every hit equals its counterpart in the fields an + // input region is built from (sameRegionHit): a label, value or description + // change keeps every region. + sameRegions bool + // patchable is set when the hits kept their identities and kinds and at + // most maxPatchedHits of them changed; dirty then names those controls. + patchable bool + dirty []gfx.ID +} + +// sameHit reports whether two hits are equal. Most hits of a repaint are the +// published ones again, byte for byte, so the bytes are compared first: Go +// strings are immutable and publishedHits keeps the previous frame's strings +// reachable, so the same pointer cannot name different text, and padding can +// only make the bytes differ. Hits whose bytes differ compare by value, which +// is what tells a label formatted again with the same words from a change. +func sameHit(published, current *gfx.Hit) bool { + size := unsafe.Sizeof(*published) + left := unsafe.Slice((*byte)(unsafe.Pointer(published)), size) + right := unsafe.Slice((*byte)(unsafe.Pointer(current)), size) + return bytes.Equal(left, right) || *published == *current +} + +// diffHits compares the canvas as painted with publishedHits once per paint, +// in one pass, and answers every caller of that paint from the result. +func (painter *painter) diffHits() *hitDiff { + diff := &painter.hitChanges + if diff.known { + return diff + } + diff.known = true + diff.dirty = diff.dirty[:0] + current, published := painter.canvas.Hits(), painter.publishedHits + if len(current) != len(published) { + diff.same, diff.sameRegions, diff.patchable = false, false, false + return diff + } + diff.same, diff.sameRegions, diff.patchable = true, true, true + for index := range current { + now, was := ¤t[index], &published[index] + if sameHit(was, now) { + continue + } + diff.same = false + if diff.sameRegions && !sameRegionHit(was, now) { + diff.sameRegions = false + } + if diff.patchable { + diff.patchable = now.ID == was.ID && now.IsLabel == was.IsLabel && + now.Block == was.Block && now.MovesWindow == was.MovesWindow && + now.Backdrop == was.Backdrop + // A zero ID is tracked like any other: it marks every zero-ID node + // (headings, groups, live regions) for a rebuild, and matches nothing + // for an occluder or drag region, which has none. + if diff.patchable && !slices.Contains(diff.dirty, now.ID) { + diff.dirty = append(diff.dirty, now.ID) + diff.patchable = len(diff.dirty) <= maxPatchedHits + } + } + if !diff.patchable { + // Only the regions are still in question, and they read a subset of + // each hit: compare just that for the rest of the list. + for rest := index + 1; diff.sameRegions && rest < len(current); rest++ { + diff.sameRegions = sameRegionHit(&published[rest], ¤t[rest]) + } + break + } + } + return diff } // recordHitStructures keeps the state that lets the next repaint skip the // region and semantic mirror when nothing that feeds them changed. func (painter *painter) recordHitStructures() { painter.publishedHits = append(painter.publishedHits[:0], painter.canvas.Hits()...) - painter.hitsSame = 1 + painter.hitChanges.known = true + painter.hitChanges.same, painter.hitChanges.sameRegions, painter.hitChanges.patchable = true, true, true + painter.hitChanges.dirty = painter.hitChanges.dirty[:0] painter.publishedFocus = painter.focus.Focused() painter.publishedTrap = painter.canvas.TrappedFocusScope() painter.publishedInitial = painter.canvas.InitialFocus() @@ -1742,42 +1822,15 @@ func (painter *painter) syncSemantics(incremental bool) (changed bool) { canvasHits := painter.canvas.Hits() // incremental is set when only the hit list changed: the focus, text state // and view are the same, so a control whose hit and label are unchanged - // keeps its accessibility node. Compare the raw hits first and remember the - // few ids whose entry may have moved; a structural change, a label-map - // fallback or too many dirty ids falls back to the full mirror below. - fast := incremental && len(canvasHits) == len(painter.publishedHits) - dirty := painter.semanticDirty[:0] - if fast { - for index := range canvasHits { - current, previous := &canvasHits[index], &painter.publishedHits[index] - if current.ID != previous.ID || current.IsLabel != previous.IsLabel || - current.Block != previous.Block || current.MovesWindow != previous.MovesWindow || - current.Backdrop != previous.Backdrop { - fast = false - break - } - if *current != *previous { - // A zero ID is tracked like any other: it marks every zero-ID - // node (headings, groups, live regions) for a rebuild below, and - // matches nothing for an occluder or drag region, which has none. - known := false - for _, id := range dirty { - if id == current.ID { - known = true - break - } - } - if !known { - dirty = append(dirty, current.ID) - if len(dirty) > 64 { - fast = false - break - } - } - } - } + // keeps its accessibility node. The paint's hit diff names the few ids + // whose entry may have moved; a structural change, a label-map fallback or + // too many dirty ids falls back to the full mirror below. + fast := false + var dirty []gfx.ID + if incremental { + diff := painter.diffHits() + fast, dirty = diff.patchable, diff.dirty } - painter.semanticDirty = dirty for index := range canvasHits { hit := &canvasHits[index] switch { From 38dd04827734dca89c8959e020781ead67f0050e Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Thu, 26 Nov 2026 19:07:28 +0800 Subject: [PATCH 05/16] fix(text): read grapheme context from the leaves and skip bidi in LTR text Arrow keys on a short mixed line cost 1.25 us after the UTF-8 store, 2-3x what they did on runes: every step scanned the whole line for characters that need bidi, and Next and Prev decoded a 64-rune window into a []rune. The window also cut context: in a run of regional indicators longer than a leaf, Prev paired flags wrongly (rune 66 gave 64, not 65). Leaves now count the characters bidi.NeedsBidiRune reports, kept beside the running sums so edits do not widen them; text without one skips the visual step outright. Next and Prev read the leaves in place through a grapheme.Source (NextIn, PrevIn) with all the context the rules ask for. M2 Pro, interleaved: CursorMoveMixedText 1248 -> 543 ns; typing and large document edits unchanged. A run of 100k flags costs 2.4 ms per Prev, as the parity rule requires counting the run. --- internal/bidi/bidi.go | 17 +++- internal/bidi/bidi_test.go | 20 ++++ internal/grapheme/grapheme.go | 68 +++++++------ text/store.go | 175 ++++++++++++++++++++++++---------- text/store_test.go | 26 ++++- text/visual.go | 3 + 6 files changed, 227 insertions(+), 82 deletions(-) diff --git a/internal/bidi/bidi.go b/internal/bidi/bidi.go index ec23a721d..e521a096b 100644 --- a/internal/bidi/bidi.go +++ b/internal/bidi/bidi.go @@ -96,8 +96,7 @@ func NeedsBidi(text string) bool { i += 3 // U+3000..U+AFFF likewise default: r, w := utf8.DecodeRuneInString(text[i:]) - switch uniprops.Bidi(r) { - case cR, cAL, cAN, cLRE, cLRO, cRLE, cRLO, cPDF, cLRI, cRLI, cFSI, cPDI: + if NeedsBidiRune(r) { return true } i += w @@ -106,6 +105,20 @@ func NeedsBidi(text string) bool { return false } +// NeedsBidiRune reports whether r is one of the characters NeedsBidi looks for: +// text holding none of them needs no bidirectional processing. Text kept in +// pieces counts them as it changes instead of scanning for them. +func NeedsBidiRune(r rune) bool { + if r < 0x0580 || r >= 0x3000 && r < 0xB000 { + return false // see NeedsBidi: no relevant class below U+0580 or in U+3000..U+AFFF + } + switch uniprops.Bidi(r) { + case cR, cAL, cAN, cLRE, cLRO, cRLE, cRLO, cPDF, cLRI, cRLI, cFSI, cPDI: + return true + } + return false +} + // Mirrored returns the character whose glyph is the mirror image of r (rule L4), or r // itself. Apply it to characters at odd levels. func Mirrored(r rune) rune { return uniprops.Mirror(r) } diff --git a/internal/bidi/bidi_test.go b/internal/bidi/bidi_test.go index fcabcff51..408c15797 100644 --- a/internal/bidi/bidi_test.go +++ b/internal/bidi/bidi_test.go @@ -8,6 +8,8 @@ import ( "strings" "testing" "unicode/utf8" + + "github.com/vivaui/viva/internal/uniprops" ) type conformCase struct { @@ -223,6 +225,24 @@ func TestNeedsBidiAgrees(t *testing.T) { } } +// NeedsBidiRune skips whole ranges without a table lookup; every character it +// answers must agree with its bidi class, and a string of it with NeedsBidi. +func TestNeedsBidiRuneMatchesTheClasses(t *testing.T) { + for r := rune(0); r <= utf8.MaxRune; r++ { + want := false + switch uniprops.Bidi(r) { + case cR, cAL, cAN, cLRE, cLRO, cRLE, cRLO, cPDF, cLRI, cRLI, cFSI, cPDI: + want = true + } + if got := NeedsBidiRune(r); got != want { + t.Fatalf("NeedsBidiRune(%U) = %v, want %v", r, got, want) + } + if utf8.ValidRune(r) && NeedsBidi(string(r)) != want { + t.Fatalf("NeedsBidi(%U) = %v, want %v", r, !want, want) + } + } +} + func TestLineL1(t *testing.T) { var r Resolver text := "אב abc " diff --git a/internal/grapheme/grapheme.go b/internal/grapheme/grapheme.go index 31683b968..9ed190988 100644 --- a/internal/grapheme/grapheme.go +++ b/internal/grapheme/grapheme.go @@ -47,19 +47,23 @@ func propOf(r rune) prop { return prop{gb: gb, incb: incb, pict: pict} } -// text abstracts a string or a rune slice; at and before return the rune -// starting at or ending at an index and its width. -type text interface { - size() int - at(i int) (rune, int) - before(i int) (rune, int) +// Source is text the rules read a rune at a time: a string, a rune slice, or +// text held in pieces that NextIn and PrevIn read in place. Offsets are whatever +// the source counts (bytes, runes) from 0 to Len. At is the rune starting at +// offset i and its width, Before the rune ending at i; a rune that is not a +// scalar value, such as a byte that is not UTF-8 reported as -1, is a cluster of +// its own and behaves like a Control character. +type Source interface { + Len() int + At(i int) (rune, int) + Before(i int) (rune, int) } type strText string -func (s strText) size() int { return len(s) } +func (s strText) Len() int { return len(s) } -func (s strText) at(i int) (rune, int) { +func (s strText) At(i int) (rune, int) { if c := s[i]; c < utf8.RuneSelf { return rune(c), 1 } @@ -70,7 +74,7 @@ func (s strText) at(i int) (rune, int) { return r, n } -func (s strText) before(i int) (rune, int) { +func (s strText) Before(i int) (rune, int) { if c := s[i-1]; c < utf8.RuneSelf { return rune(c), 1 } @@ -83,11 +87,11 @@ func (s strText) before(i int) (rune, int) { type runeText []rune -func (s runeText) size() int { return len(s) } +func (s runeText) Len() int { return len(s) } -func (s runeText) at(i int) (rune, int) { return s[i], 1 } +func (s runeText) At(i int) (rune, int) { return s[i], 1 } -func (s runeText) before(i int) (rune, int) { return s[i-1], 1 } +func (s runeText) Before(i int) (rune, int) { return s[i-1], 1 } // Context states of the forward scan. const ( @@ -177,15 +181,15 @@ func (s *scan) joins(p prop) bool { return false } -func next[T text](t T, from int) int { - n := t.size() +func next[T Source](t T, from int) int { + n := t.Len() if from >= n { return n } if from < 0 { from = 0 } - r, w := t.at(from) + r, w := t.At(from) i := from + w if i >= n { return n @@ -193,7 +197,7 @@ func next[T text](t T, from int) int { var s scan s.start(propOf(r)) for i < n { - r, w = t.at(i) + r, w = t.At(i) p := propOf(r) if !s.joins(p) { return i @@ -206,9 +210,9 @@ func next[T text](t T, from int) int { // breakBefore reports whether there is a boundary at i, 0 < i < size, which // must be on a character boundary; it reads only what precedes and follows i. -func breakBefore[T text](t T, i int) bool { - ar, aw := t.before(i) - br, _ := t.at(i) +func breakBefore[T Source](t T, i int) bool { + ar, aw := t.Before(i) + br, _ := t.At(i) a, b := propOf(ar), propOf(br) var s scan // Reconstruct the context the forward scan would hold after a. @@ -217,7 +221,7 @@ func breakBefore[T text](t T, i int) bool { case a.gb == uniprops.GBRegionalIndicator && b.gb == uniprops.GBRegionalIndicator: s.ri = 1 for j := i - aw; j > 0; { - r, w := t.before(j) + r, w := t.Before(j) if propOf(r).gb != uniprops.GBRegionalIndicator { break } @@ -227,7 +231,7 @@ func breakBefore[T text](t T, i int) bool { case a.gb == uniprops.GBZWJ && b.pict: s.pict = pictNone for j := i - aw; j > 0; { - r, w := t.before(j) + r, w := t.Before(j) q := propOf(r) if q.pict { s.pict = pictZWJ @@ -243,7 +247,7 @@ func breakBefore[T text](t T, i int) bool { j := i - aw if a.incb != uniprops.InCBConsonant { for j > 0 { - r, w := t.before(j) + r, w := t.Before(j) q := propOf(r) if q.incb == uniprops.InCBLinker { linked = true @@ -260,28 +264,28 @@ func breakBefore[T text](t T, i int) bool { return !s.joins(b) } -func boundary[T text](t T, i int) bool { - n := t.size() +func boundary[T Source](t T, i int) bool { + n := t.Len() if i <= 0 || i >= n { return i == 0 || i == n } return breakBefore(t, i) } -func prev[T text](t T, end int) int { - n := t.size() +func prev[T Source](t T, end int) int { + n := t.Len() if end > n { end = n } if end <= 0 { return 0 } - _, w := t.before(end) + _, w := t.Before(end) for i := end - w; i > 0; i -= w { if breakBefore(t, i) { return i } - _, w = t.before(i) + _, w = t.Before(i) } return 0 } @@ -344,5 +348,13 @@ func NextRunes(r []rune, from int) int { // PrevRunes is Prev for a rune slice. func PrevRunes(r []rune, end int) int { return prev(runeText(r), end) } +// NextIn is Next for a Source, for text that is not one string or rune slice. +// It reads only the runes the rules need around from, so a source held in +// pieces is read where it is, with every rune of context the rules ask for. +func NextIn[S Source](s S, from int) int { return next(s, from) } + +// PrevIn is Prev for a Source (see NextIn). +func PrevIn[S Source](s S, end int) int { return prev(s, end) } + // BoundaryRunes is Boundary for a rune slice. func BoundaryRunes(r []rune, i int) bool { return boundary(runeText(r), i) } diff --git a/text/store.go b/text/store.go index baf3d6f66..ce6802f84 100644 --- a/text/store.go +++ b/text/store.go @@ -7,32 +7,39 @@ import ( "strings" "unicode/utf8" + "github.com/vivaui/viva/internal/bidi" "github.com/vivaui/viva/internal/grapheme" ) // runeStore is the editor's text: what Range, Caret and Selection count in runes, // held as UTF-8 in leaves of about leafBytes bytes (ADR 0092). Each leaf knows how -// many runes, UTF-16 units and newlines it holds, and running totals over the -// leaves turn a rune index into a byte offset, a UTF-16 offset or a line in a -// binary search and a walk inside one leaf. An edit rewrites the leaves it -// touches, not the text after it. The editor reads and changes the text only -// through these methods. +// many runes, UTF-16 units, newlines and characters that need bidirectional +// processing it holds, and running totals over the leaves turn a rune index into +// a byte offset, a UTF-16 offset or a line in a binary search and a walk inside +// one leaf. An edit rewrites the leaves it touches, not the text after it. The +// editor reads and changes the text only through these methods. type runeStore struct { leaves []storeLeaf // sums[i] is the totals before leaf i, valid for i <= summed; an edit lowers // summed to the first leaf it touched and sums are made again from there // when next asked for. - sums []storeSums - summed int - total storeSums - cursor storeCursor - scratch []byte - boundaries []rune + sums []storeSums + summed int + total storeSums + // bidi is how many characters of the text bidi.NeedsBidiRune reports, the + // sum of the leaves' counts. No running total of it is kept: it only ever + // answers whether the whole text has one. + bidi int + cursor storeCursor + // read is the leaf storeText read last. + read int + scratch []byte } type storeLeaf struct { text []byte sizes storeSums + bidi int } type storeSums struct{ runes, bytes, units, newlines int } @@ -60,6 +67,7 @@ func newRuneStore(value string) (store runeStore, valid bool) { } for index := range store.leaves { store.total.add(store.leaves[index].sizes) + store.bidi += store.leaves[index].bidi } return store, valid } @@ -73,6 +81,11 @@ func (store *runeStore) Bytes() int { return store.total.bytes } // Newlines is how many newline runes the text holds. func (store *runeStore) Newlines() int { return store.total.newlines } +// NeedsBidi reports whether the text holds a character that can need +// bidirectional processing (bidi.NeedsBidiRune). Text without one is read left +// to right throughout, so a caller can skip the bidi algorithm for every line. +func (store *runeStore) NeedsBidi() bool { return store.bidi > 0 } + // At is the rune at index. func (store *runeStore) At(index int) rune { leaf, offset := store.seek(index) @@ -261,45 +274,88 @@ func (store *runeStore) Line(index int) int { var newline = []byte{'\n'} // Next is the grapheme cluster boundary after start; Prev the one before end. -// A cluster is found in a window of the runes around it, with the context on -// both sides the rules read, widened for a cluster longer than the window. +// The rules read the leaves in place, with as much context on either side as +// they ask for. func (store *runeStore) Next(start int) int { - // Between two ASCII runes other than CR LF there is always a boundary. - if start >= 0 && start < store.Len() && store.At(start) < utf8.RuneSelf { - if start+1 == store.Len() { - return start + 1 - } - if next := store.At(start + 1); next < utf8.RuneSelf && (next != '\n' || store.At(start) != '\r') { - return start + 1 - } - } - for width := 64; ; width *= 4 { - from, to := max(start-width, 0), min(start+width, store.Len()) - store.boundaries = store.AppendSlice(store.boundaries[:0], from, to) - next := grapheme.NextRunes(store.boundaries, start-from) + from - if next < to || to == store.Len() { - return next - } + if start >= store.Len() { + return store.Len() } + start = max(start, 0) + text := store.graphemeText() + from := store.ByteOffset(start) + return start + text.runes(from, grapheme.NextIn(text, from)) } func (store *runeStore) Prev(end int) int { - if end > 0 && end <= store.Len() && store.At(end-1) < utf8.RuneSelf { - if end == 1 { - return 0 - } - if previous := store.At(end - 2); previous < utf8.RuneSelf && (previous != '\r' || store.At(end-1) != '\n') { - return end - 1 - } + if end <= 0 { + return 0 } - for width := 64; ; width *= 4 { - from, to := max(end-width, 0), min(end+width, store.Len()) - store.boundaries = store.AppendSlice(store.boundaries[:0], from, to) - previous := grapheme.PrevRunes(store.boundaries, end-from) + from - if previous > from || from == 0 { - return previous - } + end = min(end, store.Len()) + text := store.graphemeText() + to := store.ByteOffset(end) + return end - text.runes(grapheme.PrevIn(text, to), to) +} + +// storeText is the store read as a grapheme.Source: offsets are byte offsets +// in the text, and the store's read leaf is the one last read, so the runes the +// rules read around one place cost no search. Leaves are cut on rune boundaries +// and hold valid UTF-8, so a rune never spans two of them. +type storeText runeStore + +func (store *runeStore) graphemeText() *storeText { + store.sum(len(store.leaves)) + return (*storeText)(store) +} + +func (text *storeText) Len() int { return text.total.bytes } + +func (text *storeText) At(offset int) (rune, int) { + bytes := text.find(offset)[offset-text.sums[text.read].bytes:] + if bytes[0] < utf8.RuneSelf { + return rune(bytes[0]), 1 } + return utf8.DecodeRune(bytes) +} + +func (text *storeText) Before(offset int) (rune, int) { + bytes := text.find(offset - 1)[:offset-text.sums[text.read].bytes] + if last := bytes[len(bytes)-1]; last < utf8.RuneSelf { + return rune(last), 1 + } + return utf8.DecodeLastRune(bytes) +} + +// find makes the read leaf the one holding byte offset and returns its text. The rules +// walk from a place to its neighbours, so the leaf last read and the ones beside +// it are tried before a search. +func (text *storeText) find(offset int) []byte { + sums, leaves := text.sums, text.leaves + holds := func(leaf int) bool { + return leaf >= 0 && leaf < len(leaves) && sums[leaf].bytes <= offset && offset < sums[leaf+1].bytes + } + switch { + case holds(text.read): + case holds(text.read + 1): + text.read++ + case holds(text.read - 1): + text.read-- + default: + text.read = sort.Search(len(leaves), func(i int) bool { return sums[i+1].bytes > offset }) + } + return leaves[text.read].text +} + +// runes counts the runes in bytes [from, to), both offsets of rune starts. +func (text *storeText) runes(from, to int) int { + count := 0 + for from < to { + leaf := text.find(from) + begin := text.sums[text.read].bytes + piece := leaf[from-begin : min(len(leaf), to-begin)] + count += utf8.RuneCount(piece) + from += len(piece) + } + return count } // Replace makes runes [start, end) replacement. @@ -313,6 +369,7 @@ func (store *runeStore) Replace(start, end int, replacement []rune) { store.leaves = splitLeaves(encoded) for index := range store.leaves { store.total.add(store.leaves[index].sizes) + store.bidi += store.leaves[index].bidi } return } @@ -323,12 +380,15 @@ func (store *runeStore) Replace(start, end int, replacement []rune) { // only leaf stays when it is emptied, ready for the next text. leaf := &store.leaves[first] if size := len(leaf.text) - (endOffset - startOffset) + len(encoded); (size > 0 || len(store.leaves) == 1) && size <= 2*leafBytes { - removed, added := measure(leaf.text[startOffset:endOffset]), measure(encoded) + removed, removedBidi := measure(leaf.text[startOffset:endOffset]) + added, addedBidi := measure(encoded) leaf.text = slices.Replace(leaf.text, startOffset, endOffset, encoded...) leaf.sizes.sub(removed) leaf.sizes.add(added) + leaf.bidi += addedBidi - removedBidi store.total.sub(removed) store.total.add(added) + store.bidi += addedBidi - removedBidi store.edited(first, startOffset) return } @@ -347,9 +407,11 @@ func (store *runeStore) Replace(start, end int, replacement []rune) { made := splitLeaves(buffer) for index := first; index < last; index++ { store.total.sub(store.leaves[index].sizes) + store.bidi -= store.leaves[index].bidi } for index := range made { store.total.add(made[index].sizes) + store.bidi += made[index].bidi } store.leaves = slices.Replace(store.leaves, first, last, made...) store.edited(first, 0) @@ -381,25 +443,36 @@ func splitLeaves[T string | []byte](text T) []storeLeaf { size++ } chunk := append([]byte(nil), text[:size]...) - leaves = append(leaves, storeLeaf{text: chunk, sizes: measure(chunk)}) + sizes, bidi := measure(chunk) + leaves = append(leaves, storeLeaf{text: chunk, sizes: sizes, bidi: bidi}) text = text[size:] } return leaves } -// measure counts text's runes, bytes, UTF-16 units and newlines. -func measure(text []byte) storeSums { - sizes := storeSums{bytes: len(text)} +// measure counts text's runes, bytes, UTF-16 units and newlines, and the +// characters in it that need bidirectional processing. +func measure(text []byte) (sizes storeSums, bidiRunes int) { + sizes = storeSums{bytes: len(text)} for i := 0; i < len(text); { + if c := text[i]; c < utf8.RuneSelf { + sizes.runes++ + sizes.units++ + if c == '\n' { + sizes.newlines++ + } + i++ + continue + } r, size := utf8.DecodeRune(text[i:]) sizes.runes++ sizes.units += utf16Len(r) - if r == '\n' { - sizes.newlines++ + if bidi.NeedsBidiRune(r) { + bidiRunes++ } i += size } - return sizes + return sizes, bidiRunes } func (sums *storeSums) sub(other storeSums) { diff --git a/text/store_test.go b/text/store_test.go index 80c54d70f..f7ff52a2a 100644 --- a/text/store_test.go +++ b/text/store_test.go @@ -8,6 +8,7 @@ import ( "unicode/utf16" "unicode/utf8" + "github.com/vivaui/viva/internal/bidi" "github.com/vivaui/viva/internal/grapheme" ) @@ -15,7 +16,7 @@ import ( // boundaries and with text that is not UTF-8, and checks every way the editor // reads the store against the runes. func TestRuneStoreAgreesWithRunes(t *testing.T) { - alphabet := []rune{'a', 'b', ' ', '\n', '\r', 'é', '中', '😀', 0x301, 0x200d, 0x1f3fd, 0xd800, -1, utf8.MaxRune + 1} + alphabet := []rune{'a', 'b', ' ', '\n', '\r', 'é', '中', '😀', 0x301, 0x200d, 0x1f3fd, 0x1f1e8, 'א', 0x2067, 0xd800, -1, utf8.MaxRune + 1} random := rand.New(rand.NewSource(1)) piece := func(limit int) []rune { runes := make([]rune, random.Intn(limit)) @@ -56,6 +57,9 @@ func TestRuneStoreAgreesWithRunes(t *testing.T) { if store.Newlines() != countLabelLF(want) { t.Fatalf("step %d: %d newlines, want %d", step, store.Newlines(), countLabelLF(want)) } + if store.NeedsBidi() != bidi.NeedsBidi(string(want)) { + t.Fatalf("step %d: NeedsBidi = %v for %q", step, store.NeedsBidi(), string(want)) + } for probe := 0; probe < 8; probe++ { index := random.Intn(len(want) + 1) bytes := len(string(want[:index])) @@ -112,6 +116,26 @@ func TestRuneStoreAgreesWithRunes(t *testing.T) { } } +// A cluster's boundaries can depend on every rune before it: whether a +// regional indicator ends a flag is the parity of the whole run. Next and Prev +// read the leaves in place, so a run longer than a leaf answers as the runes do. +func TestRuneStoreClustersReadTheWholeContext(t *testing.T) { + run := []rune(strings.Repeat("\U0001F1E8", 3*leafBytes/4+1)) + run = append([]rune("a"), run...) + store, _ := newRuneStore(string(run)) + if len(store.leaves) < 2 { + t.Fatalf("the run fits one leaf (%d bytes)", store.Bytes()) + } + for index := 0; index <= len(run); index++ { + if got, want := store.Next(index), grapheme.NextRunes(run, index); got != want { + t.Fatalf("cluster after %d ends at %d, want %d", index, got, want) + } + if got, want := store.Prev(index), grapheme.PrevRunes(run, index); got != want { + t.Fatalf("cluster before %d starts at %d, want %d", index, got, want) + } + } +} + // TestRuneStoreRollbackAgreesWithRunes checks the rolled-back reading the input // method planner uses against the runes it stands for. func TestRuneStoreRollbackAgreesWithRunes(t *testing.T) { diff --git a/text/visual.go b/text/visual.go index 4f9cba362..6628948ef 100644 --- a/text/visual.go +++ b/text/visual.go @@ -34,6 +34,9 @@ func (editor *Editor) stepRight(caret int) int { // to the boundary with the next place along the screen; boundaries drawn at the same place // are one stop. func (editor *Editor) visualStep(caret, direction int) (int, bool) { + if !editor.runes.NeedsBidi() { + return 0, false // no line of the text reads other than left to right + } lineStart, lineEnd := editor.runes.LineStart(caret), editor.runes.LineEnd(caret) lineOffset := editor.runes.ByteOffset(lineStart) line := editor.String()[lineOffset:editor.runes.ByteOffset(lineEnd)] From ccd13a38dc15180c088e271b55128a0593c35736 Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Thu, 26 Nov 2026 19:07:28 +0800 Subject: [PATCH 06/16] fix(render): apply mixed delete and insert batches without a rebuild A batch that deleted and inserted shapes re-flattened and re-uploaded the whole page. Deleted instances now leave the list first, in one pass shared with delete-only batches, and the update is the suffix from the first changed instance, with Shrink when the list ended shorter; every backend already applies that form. New nodes are linked after the new parents and previous siblings they name. A shape inserted between a new one and its predecessor was queued after it, so the store rejected the batch and the builder resynced the page. The splice path also requires every new shape to sit under the root, so a shape inserted into a group in the same batch goes through the rebuild. M2 Pro: delete plus append on 10k instances 65.7 us -> 250 ns. --- app/key_traversal_frame_test.go | 14 ++- internal/render/store.go | 177 ++++++++++++++++++++++------ internal/render/store_bench_test.go | 12 +- internal/render/store_test.go | 144 +++++++++++++++++++++- 4 files changed, 293 insertions(+), 54 deletions(-) diff --git a/app/key_traversal_frame_test.go b/app/key_traversal_frame_test.go index b0d7f49de..aa1085b9f 100644 --- a/app/key_traversal_frame_test.go +++ b/app/key_traversal_frame_test.go @@ -56,13 +56,15 @@ func TestContinueTraversalKeyPublishesOneConsistentFrame(t *testing.T) { if count >= base { t.Fatalf("the popup did not close: %d -> %d", base, count) } - // The platform still holds base rectangles. A frame that carries a different - // number of them has to say so with a rebuild. - if len(frame.Rectangles) != base && !frame.Update.Rebuild { - t.Fatalf("frame does not match the platform's base: base=%d frame=%d update=%+v", base, len(frame.Rectangles), frame.Update) + // The platform still holds base rectangles. A frame that carries fewer has + // to say so: a rebuild, or a shrink whose range runs to the new end, which + // every backend applies to the base and then truncates. + update := frame.Update + if len(frame.Rectangles) != count { + t.Fatalf("frame carries %d rectangles, the renderer holds %d", len(frame.Rectangles), count) } - if !frame.Update.Rebuild || frame.Update.Count != count { - t.Fatalf("update = %+v, want a rebuild of all %d rectangles", frame.Update, count) + if !update.Rebuild && (!update.Shrink || update.First > count || update.First+update.Count != count) { + t.Fatalf("update = %+v cannot take the platform from %d rectangles to %d", update, base, count) } } diff --git a/internal/render/store.go b/internal/render/store.go index e372fac5c..e903a3ce9 100644 --- a/internal/render/store.go +++ b/internal/render/store.go @@ -83,6 +83,10 @@ type node struct { // this batch and has no instance until the batch finishes flattening it. const freshInstance = uint32(1) << 31 +// unlinked marks, while a batch links its new nodes, the slot of a new node not +// linked yet; the rest of the entry is the index of its change in the batch. +const unlinked = uint32(1) << 30 + type Store struct { nodes []node instanceBySlot []uint32 @@ -92,6 +96,10 @@ type Store struct { // page rather than the number of rebuilds. order []scene.ID scratch []scene.ID + // deleted collects the instances a batch removes, and linking is the walk + // stack of the new nodes a batch links; both are reused like order. + deleted []int + linking []int root scene.ID } @@ -111,9 +119,11 @@ func (store *Store) Apply(changes []scene.Change) (Update, error) { return store.deleteBatch(changes) } - oldCount := len(store.rectangles) structureChanged := false - deleted := false + // shrunk is the first instance a delete in the batch removed; the update + // then runs from there to the end of the list, as a delete-only batch's. + shrunk := -1 + before := len(store.rectangles) // appended collects new shape nodes whose insertion may be a pure append // after the last instance. If the chain holds, the store can append them // without rebuilding (and re-uploading) the whole instance list. @@ -122,51 +132,96 @@ func (store *Store) Apply(changes []scene.Change) (Update, error) { // rebuild resolves their geometry from this batch instead of the rectangles // the store already holds. var inserted []uint32 - appendOnly := oldCount > 0 // Deletes are applied before upserts. The scene relinks a deleted node's // successor without reporting that successor, so an upsert of it (queued // earlier in the same batch for another reason, such as a new color) carries // the post-delete previous sibling. Applied in queue order it would see the // stale link and be rejected as a structural mutation, dropping the rest of - // the batch. + // the batch. The deleted instances leave the list before anything is + // inserted, so every index below is one in the list the batch ends with. + store.deleted = store.deleted[:0] for _, change := range changes { switch change.Operation { case scene.OperationDelete: - if err := store.remove(change.ID); err != nil { + if err := store.removeInstance(change.ID); err != nil { return Update{}, err } structureChanged = true - deleted = true - appendOnly = false case scene.OperationUpsert: default: return Update{}, fmt.Errorf("render: unsupported operation %d", change.Operation) } } + if len(store.deleted) > 0 { + shrunk = store.compact() + } + oldCount := len(store.rectangles) + appendOnly := oldCount > 0 // New nodes are linked before changed ones are applied. The scene reports a // node's current neighbours, so an existing node's upsert queued before the // insert of its new predecessor already names that predecessor, which the - // store only learns of when it reaches the insert. + // store only learns of when it reaches the insert. A new node can likewise + // name a parent or previous sibling that is new too and queued after it (a + // shape inserted between a new one and its predecessor), so every new node + // is marked first and each is linked after the new nodes it names. Parents + // and previous siblings form a tree and lists, so the walk ends; a batch + // that names a cycle is rejected. + fresh := 0 for index, change := range changes { if change.Operation != scene.OperationUpsert || store.exists(change.ID) { continue } - if _, _, err := store.upsert(change); err != nil { - return Update{}, err + slot, ok := change.ID.Slot() + if !ok { + return Update{}, fmt.Errorf("render: invalid node ID %d", change.ID) } - if change.Kind != scene.KindGroup { - slot, _ := change.ID.Slot() - store.instanceBySlot[slot] = freshInstance | uint32(len(inserted)) - inserted = append(inserted, uint32(index)) + store.ensureSlots(slot) + store.instanceBySlot[slot] = unlinked | uint32(index) + fresh++ + } + for index := 0; fresh > 0 && index < len(changes); index++ { + if store.unlinkedChange(changes, changes[index].ID) < 0 { + continue } - structureChanged = true - if change.Kind == scene.KindGroup || change.Parent != store.root { - appendOnly = false - } else { - appended = append(appended, change) + stack := append(store.linking[:0], index) + for len(stack) > 0 { + if len(stack) > len(changes) { + return Update{}, fmt.Errorf("render: node %d is placed after or inside itself", changes[stack[0]].ID) + } + top := stack[len(stack)-1] + change := changes[top] + if dependency := store.unlinkedChange(changes, change.Parent); dependency >= 0 { + stack = append(stack, dependency) + continue + } + if dependency := store.unlinkedChange(changes, change.PreviousSibling); dependency >= 0 { + stack = append(stack, dependency) + continue + } + stack = stack[:len(stack)-1] + if store.unlinkedChange(changes, change.ID) < 0 { + continue // linked already, as the dependency of another + } + if _, _, err := store.upsert(change); err != nil { + return Update{}, err + } + fresh-- + slot, _ := change.ID.Slot() + store.instanceBySlot[slot] = 0 + if change.Kind != scene.KindGroup { + store.instanceBySlot[slot] = freshInstance | uint32(len(inserted)) + inserted = append(inserted, uint32(top)) + } + structureChanged = true + if change.Kind == scene.KindGroup || change.Parent != store.root { + appendOnly = false + } else { + appended = append(appended, change) + } } + store.linking = stack } first := oldCount @@ -217,13 +272,13 @@ func (store *Store) Apply(changes []scene.Change) (Update, error) { if first > oldCount { first = oldCount } - case !deleted && len(appended) > 0 && oldCount > 0: + case len(appended) > 0 && len(appended) == len(inserted) && oldCount > 0: // Insertions in the middle of the page move the tail of paint // order, but the scene's neighbour links say exactly where each // new shape goes. Splicing it in and renumbering the slots after // it costs one shift of the instance list instead of re-flattening - // and re-uploading the whole page. Deletions still rebuild, - // because every backend's retained store is sized to the count. + // and re-uploading the whole page. A shape inserted inside a group + // is placed by the rebuild below. for _, change := range appended { at := 0 if change.PreviousSibling != 0 { @@ -248,6 +303,8 @@ func (store *Store) Apply(changes []scene.Change) (Update, error) { if last < len(store.rectangles)-1 { last = len(store.rectangles) - 1 } + case len(appended) == 0 && len(inserted) == 0 && shrunk >= 0: + // Only deletes, alongside changes to shapes that stay. default: if err := store.rebuild(changes, inserted); err != nil { return Update{}, err @@ -255,6 +312,12 @@ func (store *Store) Apply(changes []scene.Change) (Update, error) { return Update{Count: len(store.rectangles), Rebuild: true}, nil } } + if shrunk >= 0 { + // Everything after the first removed instance moved: send it all, and + // let a backend truncate when the list ended shorter than it began. + first = min(first, shrunk) + return Update{First: first, Count: len(store.rectangles) - first, Shrink: len(store.rectangles) < before}, nil + } if last < first { return Update{}, nil } @@ -275,31 +338,49 @@ func changesAreDeletes(changes []scene.Change) bool { } func (store *Store) deleteBatch(changes []scene.Change) (Update, error) { - var instances []int + store.deleted = store.deleted[:0] for _, change := range changes { - slot, ok := change.ID.Slot() - if !ok || int(slot) >= len(store.nodes) { - return Update{}, fmt.Errorf("render: delete references invalid node %d", change.ID) - } - if instance := store.instanceIndex(slot, change.ID); instance >= 0 { - instances = append(instances, instance) - } - if err := store.remove(change.ID); err != nil { + if err := store.removeInstance(change.ID); err != nil { return Update{}, err } } - if len(instances) == 0 { + if len(store.deleted) == 0 { return Update{}, nil } - slices.Sort(instances) - first := instances[0] - for index := len(instances) - 1; index >= 0; index-- { - at := instances[index] - copy(store.rectangles[at:], store.rectangles[at+1:]) - store.rectangles = store.rectangles[:len(store.rectangles)-1] + first := store.compact() + return Update{First: first, Count: len(store.rectangles) - first, Shrink: true}, nil +} + +// removeInstance removes node id and notes its instance, if it has one, in +// deleted for compact. +func (store *Store) removeInstance(id scene.ID) error { + slot, ok := id.Slot() + if !ok || int(slot) >= len(store.nodes) { + return fmt.Errorf("render: delete references invalid node %d", id) + } + if instance := store.instanceIndex(slot, id); instance >= 0 { + store.deleted = append(store.deleted, instance) + } + return store.remove(id) +} + +// compact drops the instances in deleted from the list in one pass, renumbers +// the slots after the first of them, and returns it. +func (store *Store) compact() int { + slices.Sort(store.deleted) + first := store.deleted[0] + write, next := first, 0 + for read := first; read < len(store.rectangles); read++ { + if next < len(store.deleted) && store.deleted[next] == read { + next++ + continue + } + store.rectangles[write] = store.rectangles[read] + write++ } + store.rectangles = store.rectangles[:write] store.reindexFrom(first) - return Update{First: first, Count: len(store.rectangles) - first, Shrink: true}, nil + return first } // rectangleOf is the render instance a scene change describes. @@ -331,6 +412,24 @@ func (store *Store) reindexFrom(index int) { } } +// unlinkedChange is the index in changes of the new node id when the batch has +// not linked it yet, or -1. +func (store *Store) unlinkedChange(changes []scene.Change, id scene.ID) int { + slot, ok := id.Slot() + if !ok || int(slot) >= len(store.nodes) || store.nodes[slot].alive { + return -1 + } + encoded := store.instanceBySlot[slot] + if encoded&unlinked == 0 || encoded&freshInstance != 0 { + return -1 + } + index := int(encoded &^ unlinked) + if index >= len(changes) || changes[index].ID != id { + return -1 + } + return index +} + // exists reports whether the store already holds the node with this identity. func (store *Store) exists(id scene.ID) bool { slot, ok := id.Slot() diff --git a/internal/render/store_bench_test.go b/internal/render/store_bench_test.go index 636e07924..2d193049d 100644 --- a/internal/render/store_bench_test.go +++ b/internal/render/store_bench_test.go @@ -28,10 +28,10 @@ func BenchmarkStoreAppendTail(b *testing.B) { } } -// Deleting one instance from a large page still rebuilds every instance, -// because the backends keep a store sized to the count. Measure that fallback -// so an incremental delete can be compared against it. -func BenchmarkStoreDeleteRebuild(b *testing.B) { +// Deleting one instance from the middle of a large page and appending another +// in the same batch compacts the list and sends the suffix from the deleted +// instance, rather than re-flattening the page. +func BenchmarkStoreDeleteAndAppend(b *testing.B) { graph := scene.NewWithCapacity(10_001) var id scene.ID for index := 0; index < 10000; index++ { @@ -56,8 +56,8 @@ func BenchmarkStoreDeleteRebuild(b *testing.B) { } id = next update, err := store.Apply(graph.DrainChanges(nil)) - if err != nil || !update.Rebuild { - b.Fatalf("delete update = %+v, err %v", update, err) + if err != nil || update.Rebuild { + b.Fatalf("delete and append update = %+v, err %v", update, err) } } } diff --git a/internal/render/store_test.go b/internal/render/store_test.go index 58ba2bcac..70d646ab9 100644 --- a/internal/render/store_test.go +++ b/internal/render/store_test.go @@ -1,6 +1,8 @@ package render import ( + "math/rand" + "slices" "testing" "github.com/vivaui/viva/internal/scene" @@ -167,8 +169,9 @@ func TestStoreAcceptsSuccessorUpsertQueuedBeforeItsPredecessorsDelete(t *testing if err != nil { t.Fatalf("apply: %v", err) } - if !update.Rebuild { - t.Fatalf("update = %+v, want a rebuild after a delete", update) + // Everything from the deleted instance on moved, and the list is shorter. + if update != (Update{First: 1, Count: 2, Shrink: true}) { + t.Fatalf("update = %+v, want the suffix from the deleted instance, shrunk", update) } rectangles := store.Rectangles() if len(rectangles) != 3 || rectangles[0].ID != kept || rectangles[1].ID != successor || rectangles[2].ID != tail { @@ -375,7 +378,8 @@ func TestStoreDeletesOneShapeAndInsertsAnotherBeforeIt(t *testing.T) { if err != nil { t.Fatal(err) } - if !update.Rebuild { + // One instance left and one took its place: the suffix from there, same length. + if update != (Update{First: 1, Count: 2}) { t.Fatalf("delete plus insert update = %+v", update) } rectangles := store.Rectangles() @@ -430,3 +434,137 @@ func TestStoreDeletesNonContiguousInstancesInOrder(t *testing.T) { t.Fatalf("remaining = %+v", got) } } + +// storeModel is the tree a random test builds alongside a scene: the paint +// order the store must end each batch in is its depth-first walk. +type storeModel struct { + id scene.ID + group bool + color scene.Color + children []*storeModel +} + +func (model *storeModel) walk(visit func(parent, node *storeModel)) { + for _, child := range model.children { + visit(model, child) + if child.group { + child.walk(visit) + } + } +} + +// TestStoreUpdatesKeepABackendInStep applies random batches of appends, +// insertions, deletions, recolors and groups, and checks after each one that +// the store holds the scene's paint order and that a backend which applies only +// the reported Update (rebuild, or a range that may grow the list or be cut +// short with Shrink) holds exactly the store's instances. +func TestStoreUpdatesKeepABackendInStep(t *testing.T) { + random := rand.New(rand.NewSource(7)) + graph := scene.New() + root := &storeModel{id: graph.Root(), group: true} + var store Store + var backend []Rectangle + color := func() scene.Color { return scene.Color{Red: float32(random.Intn(1000)), Alpha: 1} } + pick := func(groups bool) (parent, node *storeModel, index int) { + var parents, nodes []*storeModel + root.walk(func(p, n *storeModel) { + if groups || !n.group { + parents, nodes = append(parents, p), append(nodes, n) + } + }) + if len(nodes) == 0 { + return nil, nil, -1 + } + at := random.Intn(len(nodes)) + return parents[at], nodes[at], slices.Index(parents[at].children, nodes[at]) + } + groupOf := func() *storeModel { + groups := []*storeModel{root} + root.walk(func(_, n *storeModel) { + if n.group { + groups = append(groups, n) + } + }) + return groups[random.Intn(len(groups))] + } + for batch := 0; batch < 3000; batch++ { + for operations := 1 + random.Intn(5); operations > 0; operations-- { + switch random.Intn(6) { + case 0, 1: // insert a shape after a random sibling, or first + parent := groupOf() + at := random.Intn(len(parent.children) + 1) + previous := scene.ID(0) + if at > 0 { + previous = parent.children[at-1].id + } + shade := color() + id, ok := graph.InsertRoundedRectangle(parent.id, previous, scene.Rect{Width: 1}, shade, 0) + if !ok { + t.Fatal("insert failed") + } + parent.children = slices.Insert(parent.children, at, &storeModel{id: id, color: shade}) + case 2: // remove a shape or a whole group + if parent, node, index := pick(true); node != nil { + if !graph.Remove(node.id) { + t.Fatal("remove failed") + } + parent.children = slices.Delete(parent.children, index, index+1) + } + case 3, 4: // recolor a shape + if _, node, _ := pick(false); node != nil { + node.color.Red++ // a change, which the scene queues + if !graph.SetRectangle(node.id, scene.Rect{Width: 1}, node.color) { + t.Fatal("recolor failed") + } + } + case 5: // a group holding a few shapes, at the end of the page + id, ok := graph.AddGroup(graph.Root()) + if !ok { + t.Fatal("group failed") + } + group := &storeModel{id: id, group: true} + for count := random.Intn(3); count > 0; count-- { + shade := color() + child, _ := graph.AddRectangle(id, scene.Rect{Width: 1}, shade) + group.children = append(group.children, &storeModel{id: child, color: shade}) + } + root.children = append(root.children, group) + } + } + + update, err := store.Apply(graph.DrainChanges(nil)) + if err != nil { + t.Fatalf("batch %d: %v", batch, err) + } + rectangles := store.Rectangles() + switch { + case update.Rebuild: + backend = append(backend[:0], rectangles...) + case update.Count > 0 || update.Shrink: + if end := update.First + update.Count; end > len(backend) { + backend = append(backend, make([]Rectangle, end-len(backend))...) + } + copy(backend[update.First:], rectangles[update.First:update.First+update.Count]) + if update.Shrink { + backend = backend[:len(rectangles)] + } + } + if !slices.Equal(backend, rectangles) { + t.Fatalf("batch %d: update %+v left the backend with %d instances, the store %d", batch, update, len(backend), len(rectangles)) + } + var want []*storeModel + root.walk(func(_, n *storeModel) { + if !n.group { + want = append(want, n) + } + }) + if len(rectangles) != len(want) { + t.Fatalf("batch %d: %d instances, want %d", batch, len(rectangles), len(want)) + } + for index, node := range want { + if rectangles[index].ID != node.id || rectangles[index].Color != node.color { + t.Fatalf("batch %d: instance %d is %d %v, want %d %v", batch, index, rectangles[index].ID, rectangles[index].Color, node.id, node.color) + } + } + } +} From 0c822d218ec9fc72e39b4a1514e8bd87031b99ad Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Thu, 26 Nov 2026 19:51:27 +0800 Subject: [PATCH 07/16] fix(render): release batch scratch once the page shrinks The store's batch scratch (paint order, walk stack, deleted instances, link stack) kept the capacity of the largest batch for the rest of the session: closing a 100k-row page left about 800 KB behind. The scratch holds nothing between batches and only looks oversized after the page shrinks, so compact now gives back any of it past four times the page, above a 4096 floor. A page that stays large keeps what its batches use; frames without a shrinking batch do no extra work. --- internal/render/store.go | 36 ++++++++++++++++++++++++-- internal/render/store_test.go | 48 +++++++++++++++++++++++++++++++++++ 2 files changed, 82 insertions(+), 2 deletions(-) diff --git a/internal/render/store.go b/internal/render/store.go index e903a3ce9..b9cfa11ae 100644 --- a/internal/render/store.go +++ b/internal/render/store.go @@ -92,8 +92,8 @@ type Store struct { instanceBySlot []uint32 rectangles []Rectangle // order is the paint order one rebuild computes for the new batch; scratch - // is the walk stack. Both are reused, so their capacity tracks the largest - // page rather than the number of rebuilds. + // is the walk stack. Both are reused from batch to batch; releaseScratch + // gives back what a past large batch left in them. order []scene.ID scratch []scene.ID // deleted collects the instances a batch removes, and linking is the walk @@ -103,6 +103,37 @@ type Store struct { root scene.ID } +// releaseScratch gives back the batch scratch a page that just shrank no longer +// needs, so a one-off peak does not stay for the rest of the session. The +// scratch holds nothing between batches and only ever looks oversized after +// the page shrinks, so this runs then and costs other frames nothing; a page +// that stays large keeps what its batches use and never reallocates. +func (store *Store) releaseScratch() { + page := len(store.rectangles) + if oversized(cap(store.order), page) { + store.order = make([]scene.ID, 0, max(page, minScratch)) + } + if oversized(cap(store.scratch), page) { + store.scratch = make([]scene.ID, 0, max(page, minScratch)) + } + if oversized(cap(store.deleted), page) { + store.deleted = make([]int, 0, max(page, minScratch)) + } + if oversized(cap(store.linking), page) { + store.linking = make([]int, 0, max(page, minScratch)) + } +} + +// minScratch is the capacity batch scratch is given back at; trimAt is the +// capacity below which it is never released. +const minScratch, trimAt = 64, 4096 + +// oversized is the retention rule for batch scratch: past trimAt, it keeps at +// most four times the page it serves. +func oversized(capacity, page int) bool { + return capacity > trimAt && page*4 < capacity +} + // Rectangles returns the current ordered rectangle instances. The result is // invalidated by the next call to Apply. func (store *Store) Rectangles() []Rectangle { @@ -380,6 +411,7 @@ func (store *Store) compact() int { } store.rectangles = store.rectangles[:write] store.reindexFrom(first) + store.releaseScratch() return first } diff --git a/internal/render/store_test.go b/internal/render/store_test.go index 70d646ab9..efeec5411 100644 --- a/internal/render/store_test.go +++ b/internal/render/store_test.go @@ -568,3 +568,51 @@ func TestStoreUpdatesKeepABackendInStep(t *testing.T) { } } } + +// Deleting most of a large page gives back the batch scratch that page needed, +// once the page left is small. +func TestStoreReleasesTheScratchOfAPageThatShrank(t *testing.T) { + graph := scene.NewWithCapacity(20_001) + ids := make([]scene.ID, 0, 20_000) + for index := 0; index < 20_000; index++ { + id, _ := graph.AddRectangle(graph.Root(), scene.Rect{X: float32(index)}, scene.Color{Alpha: 1}) + ids = append(ids, id) + } + var store Store + if _, err := store.Apply(graph.DrainChanges(nil)); err != nil { + t.Fatal(err) + } + for _, id := range ids[1:] { + graph.Remove(id) + } + if _, err := store.Apply(graph.DrainChanges(nil)); err != nil { + t.Fatal(err) + } + if cap(store.deleted) > 4096 { + t.Fatalf("the store keeps %d scratch for a one-shape page", cap(store.deleted)) + } +} + +// A page that stays large keeps the scratch its batches use, so its next large +// batch does not allocate again. +func TestStoreKeepsTheScratchOfAPageThatStaysLarge(t *testing.T) { + graph := scene.NewWithCapacity(20_001) + ids := make([]scene.ID, 0, 20_000) + for index := 0; index < 20_000; index++ { + id, _ := graph.AddRectangle(graph.Root(), scene.Rect{X: float32(index)}, scene.Color{Alpha: 1}) + ids = append(ids, id) + } + var store Store + if _, err := store.Apply(graph.DrainChanges(nil)); err != nil { + t.Fatal(err) + } + for _, id := range ids[:10_000] { + graph.Remove(id) + } + if _, err := store.Apply(graph.DrainChanges(nil)); err != nil { + t.Fatal(err) + } + if cap(store.deleted) < 10_000 { + t.Fatalf("the store dropped the scratch of a %d-instance page: %d", len(store.Rectangles()), cap(store.deleted)) + } +} From 89e823c57adcb8705e7ee06b72d3d22029cff8e5 Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Thu, 26 Nov 2026 19:51:27 +0800 Subject: [PATCH 08/16] test(windows): check incremental frames draw what a rebuild draws Random batches that delete, insert in the middle and recolor shapes go through render.Store, and the Direct3D 11 renderer is sent only the updates it reports (ranges that grow the list or end it shorter with Shrink); every frame is compared pixel for pixel with a renderer given the whole list. The test requires both shrinking and growing ranges, so it keeps exercising the suffix path. Run on the physical Windows 11 machine; an off-by-one range in the store fails it at the first batch. --- .../windows/offscreen_update_windows_test.go | 85 +++++++++++++++++++ 1 file changed, 85 insertions(+) create mode 100644 internal/platform/windows/offscreen_update_windows_test.go diff --git a/internal/platform/windows/offscreen_update_windows_test.go b/internal/platform/windows/offscreen_update_windows_test.go new file mode 100644 index 000000000..7c4d3de3a --- /dev/null +++ b/internal/platform/windows/offscreen_update_windows_test.go @@ -0,0 +1,85 @@ +package windows + +import ( + "bytes" + "math/rand" + "testing" + + "github.com/vivaui/viva/internal/platform" + "github.com/vivaui/viva/internal/render" + "github.com/vivaui/viva/internal/scene" +) + +// A renderer that is sent only the store's updates (a range that may grow the +// list, be cut short with Shrink, or a rebuild) draws exactly what a renderer +// given the whole list draws, through batches that delete, insert in the +// middle and recolor shapes together. +func TestOffscreenIncrementalUpdatesDrawWhatARebuildDraws(t *testing.T) { + incremental := newOffscreen(t, 160, 120, 1) + random := rand.New(rand.NewSource(3)) + graph := scene.New() + var store render.Store + var shapes []scene.ID + place := func() (scene.Rect, scene.Color) { + bounds := scene.Rect{X: float32(random.Intn(140)), Y: float32(random.Intn(100)), Width: float32(8 + random.Intn(20)), Height: float32(8 + random.Intn(20))} + return bounds, scene.Color{Red: random.Float32(), Green: random.Float32(), Blue: random.Float32(), Alpha: 1} + } + for range 40 { + bounds, color := place() + id, _ := graph.AddRectangle(graph.Root(), bounds, color) + shapes = append(shapes, id) + } + shrinks, grows := 0, 0 + for batch := 0; batch < 120; batch++ { + if batch > 0 { + for operations := 1 + random.Intn(6); operations > 0; operations-- { + switch operation := random.Intn(3); { + case operation == 0 && len(shapes) > 1: + at := random.Intn(len(shapes)) + graph.Remove(shapes[at]) + shapes = append(shapes[:at], shapes[at+1:]...) + case operation == 1: + at := random.Intn(len(shapes) + 1) + previous := scene.ID(0) + if at > 0 { + previous = shapes[at-1] + } + bounds, color := place() + id, ok := graph.InsertRoundedRectangle(graph.Root(), previous, bounds, color, 0) + if !ok { + t.Fatal("insert failed") + } + shapes = append(shapes[:at], append([]scene.ID{id}, shapes[at:]...)...) + case len(shapes) > 0: + bounds, color := place() + graph.SetRectangle(shapes[random.Intn(len(shapes))], bounds, color) + } + } + } + update, err := store.Apply(graph.DrainChanges(nil)) + if err != nil { + t.Fatalf("batch %d: %v", batch, err) + } + rectangles := store.Rectangles() + if !update.Rebuild && update.Shrink { + shrinks++ + } + if !update.Rebuild && !update.Shrink && update.First+update.Count > len(incremental.renderer.instances) { + grows++ + } + if err := incremental.renderer.apply(platform.Frame{Update: update, Rectangles: rectangles}); err != nil { + t.Fatalf("batch %d: update %+v: %v", batch, update, err) + } + got, err := incremental.Image() + if err != nil { + t.Fatal(err) + } + want := renderScene(t, newOffscreen(t, 160, 120, 1), append([]render.Rectangle(nil), rectangles...), nil) + if !bytes.Equal(got.Pix, want.Pix) { + t.Fatalf("batch %d: update %+v drew other pixels than a rebuild of %d instances", batch, update, len(rectangles)) + } + } + if shrinks == 0 || grows == 0 { + t.Fatalf("the batches sent %d shrinking and %d growing ranges; the test needs both", shrinks, grows) + } +} From ccccd882fac6c1a55feb2068625471671d973f55 Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Thu, 26 Nov 2026 21:46:54 +0800 Subject: [PATCH 09/16] feat(ui): select and copy read-only text in a TextSelectionArea ui.TextSelectionArea(c, &state) declares a column whose Text, Paragraph and Wrap the user can drag across, double/triple-click, extend with Shift, copy with Primary+C or the page's Copy/Select All menu, and drop with Escape. Text inside elements that act on a press (buttons, links, LabelFor labels) keeps its own presses; Box.Unselectable takes a text out. Copies are the source text: an ellipsis copies whole, texts side by side in a row join with a tab, others with a newline. Boundary: hit regions, focus, paint and page routing are framework concerns, so the area lives in base. The cross-text selection engine (TextSelection, TextPoint) moves from components to base and components.MarkdownSelection becomes base.TextRange, re-exported by ui, with no aliases left behind. gfx gains HitOptions.Presentational: a pointer-only region that shows the text cursor over the words without an accessibility node of its own. Desktop checklist: - Keyboard: no Tab stop (as SwiftUI/Flutter/Compose); Primary+C/A, Shift+arrows, Escape. Guarded by headless tests. - Pointer: drag, double/triple press, Shift-press, secondary press opens the in-page edit menu; drag past a scroll area's edge autoscrolls. - Focus: a press focuses the area without a ring; the selection drops when another control takes the keyboard; the menu gives it back. - Text: offsets snap to graphemes; words via text.WordRange. - Density/Window: no new control sizes; inactive-window selection color not done (the canvas does not know window activation; fields share the gap). - Accessibility: words stay the painted static text; selection is not yet exposed through AX/UIA/AT-SPI. Steady paint allocates nothing (40 rows, ~30 texts selected: 28.5us vs 20.8us for the same texts outside an area on M2 Pro). Companion: motty commit adopting it for host keys, errors and details. --- app/accessibility_test.go | 22 + app/painter.go | 5 +- base/frame.go | 23 +- base/page.go | 1 + base/paint.go | 31 +- {components => base}/text_selection.go | 66 +- base/text_selection_area.go | 738 ++++++++++++++++++++ {components => base}/text_selection_test.go | 56 +- components/doc.go | 12 +- components/markdown.go | 38 +- components/markdown_test.go | 97 +-- docs/skills/building-with-viva/SKILL.md | 1 + gfx/canvas.go | 12 +- headless/layout.go | 5 +- headless/session.go | 2 +- internal/platform/web/accessibility.go | 4 +- ui/edit_menu.go | 2 +- ui/markdown/markdown.go | 3 +- ui/text_selection.go | 32 + ui/text_selection_test.go | 504 +++++++++++++ 20 files changed, 1509 insertions(+), 145 deletions(-) rename {components => base}/text_selection.go (78%) create mode 100644 base/text_selection_area.go rename {components => base}/text_selection_test.go (79%) create mode 100644 ui/text_selection.go create mode 100644 ui/text_selection_test.go diff --git a/app/accessibility_test.go b/app/accessibility_test.go index 423fab09f..421128af3 100644 --- a/app/accessibility_test.go +++ b/app/accessibility_test.go @@ -262,3 +262,25 @@ func TestSyncSemanticsUpdatesZeroIDContainerOnIncrementalPaint(t *testing.T) { t.Fatalf("stale zero-ID container accessibility node: %+v", nodes) } } + +// A pointer region over painted words (a selectable text's) is no node of its own and +// takes no focus, while the control it belongs to stays one. +func TestPresentationalHitsAreNoAccessibilityNodes(t *testing.T) { + var canvas gfx.Canvas + config := Config{Title: "presentational", Width: 200, Height: 120} + config.Paint = func(canvas *gfx.Canvas, size gfx.Size) { + canvas.HitWithOptions(gfx.Item(1), gfx.Rect{Width: 200, Height: 100}, "", gfx.HitOptions{Role: gfx.RoleGroup, SkipTab: true}) + canvas.HitWithOptions(gfx.Item(2), gfx.Rect{Y: 10, Width: 120, Height: 16}, "", gfx.HitOptions{ + Role: gfx.RoleGroup, Cursor: gfx.PointerCursorText, Presentational: true, + }) + } + painter := newTestPainter(t, &canvas, config) + if len(painter.accessibility) != 1 || painter.accessibility[0].ID != gfx.Item(1) { + t.Fatalf("accessibility = %+v", painter.accessibility) + } + for _, hit := range canvas.Hits() { + if hit.ID == gfx.Item(2) && (hit.Focusable || hit.Cursor != gfx.PointerCursorText) { + t.Fatalf("the pointer region is %+v", hit) + } + } +} diff --git a/app/painter.go b/app/painter.go index a210317b6..7f946de39 100644 --- a/app/painter.go +++ b/app/painter.go @@ -1655,6 +1655,7 @@ func sameRegionHit(published, current *gfx.Hit) bool { published.BlockSurface == current.BlockSurface && published.Container == current.Container && published.IsLabel == current.IsLabel && + published.Presentational == current.Presentational && published.Backdrop == current.Backdrop && published.MovesWindow == current.MovesWindow && published.PassSecondary == current.PassSecondary && @@ -1757,7 +1758,7 @@ func (painter *painter) diffHits() *hitDiff { } if diff.patchable { diff.patchable = now.ID == was.ID && now.IsLabel == was.IsLabel && - now.Block == was.Block && now.MovesWindow == was.MovesWindow && + now.Presentational == was.Presentational && now.Block == was.Block && now.MovesWindow == was.MovesWindow && now.Backdrop == was.Backdrop // A zero ID is tracked like any other: it marks every zero-ID node // (headings, groups, live regions) for a rebuild, and matches nothing @@ -1834,7 +1835,7 @@ func (painter *painter) syncSemantics(incremental bool) (changed bool) { for index := range canvasHits { hit := &canvasHits[index] switch { - case hit.Block, hit.MovesWindow: + case hit.Block, hit.MovesWindow, hit.Presentational: case hit.IsLabel: labelled = true switch { diff --git a/base/frame.go b/base/frame.go index ddb2f2c2c..5a822a17f 100644 --- a/base/frame.go +++ b/base/frame.go @@ -227,6 +227,8 @@ type Extra struct { addons int32 // 1 + the index of the field's icon and button in frame.addons, or 0 focusGroup FocusAxis // FocusGroup: the arrow keys that move the focus between the controls inside; zero is none highlight int32 // 1 + the index of this text's query in frame.highlights; zero is none + textArea int32 // 1 + the index of the TextSelectionArea the element is in frame.textAreas, or 0 + unselectable bool // Unselectable: the element's texts take no part in the area they are in focusOrder FocusOrder // FocusOrder: how the group chooses the next member; nil is its axis layout Layout // CustomLayout: who measures and places the children swatchFlush bool // a ColorSwatch fills its border with its color @@ -300,10 +302,20 @@ type Frame struct { Lines []string highlights []textHighlight paintHighlightFn func(*Frame, *Node, string, Rect, gfx.TextStyle, gfx.Alignment) - controls any // the layer above's control declarations: see widgetsOf - Ellipses []gfx.EllipsisCache // the cut-off ends of wrapped texts, kept between frames - Wraps []wrapCache // the full line sets of wrapped texts, kept between frames - wrapCursor int + // textAreas are the TextSelectionAreas of the paint; area is the one being + // painted, whose texts are collected unless areaSkip says a control or an + // Unselectable element they are in keeps them out. lineAt is where the next line + // of the text being collected is looked for in its source, and selectionSpans + // reuses the spans of a selected line. + textAreas []*TextSelectionState + area *TextSelectionState + areaSkip int32 + lineAt int + selectionSpans []gfx.TextSpan + controls any // the layer above's control declarations: see widgetsOf + Ellipses []gfx.EllipsisCache // the cut-off ends of wrapped texts, kept between frames + Wraps []wrapCache // the full line sets of wrapped texts, kept between frames + wrapCursor int // tails is how long each reused slice that holds pointers was when the last // frame ended: what lies past its length up to there is the last frame's, // cleared by releaseTail so a page that shrank does not keep it reachable. @@ -353,6 +365,9 @@ func (View *View) Begin(Surface *gfx.Canvas, Palette Theme, bounds Rect) *Frame f.Surface, f.Palette, f.bounds, f.done = Surface, Palette, bounds, false f.Nodes = f.Nodes[:0] f.Lines = f.Lines[:0] + clear(f.textAreas) + f.textAreas = f.textAreas[:0] + f.area, f.areaSkip = nil, 0 clear(f.highlights) f.highlights = f.highlights[:0] f.Exts = append(f.Exts[:0], Extra{}) diff --git a/base/page.go b/base/page.go index 08263378b..c5a26da8b 100644 --- a/base/page.go +++ b/base/page.go @@ -168,6 +168,7 @@ const ( pkDisclosure pkProgress pkAlertDialog + pkTextSelection pkKinds ) diff --git a/base/paint.go b/base/paint.go index d6da041ce..ae3283628 100644 --- a/base/paint.go +++ b/base/paint.go @@ -20,6 +20,22 @@ func (f *Frame) PaintChild(i int32) { f.Surface.PushLayer(n.Band) defer f.Surface.PopLayer() } + if len(f.textAreas) > 0 { + // The texts of a TextSelectionArea are collected as it is painted, in reading + // order; a control inside it, or what Unselectable takes out, keeps its own. + if extra := &f.Exts[n.Ext]; extra.textArea != 0 { + area, skip := f.area, f.areaSkip + f.area, f.areaSkip = f.textAreas[extra.textArea-1], 0 + f.beginTextArea(f.area) + defer func() { + f.endTextArea(f.area) + f.area, f.areaSkip = area, skip + }() + } else if f.area != nil && (actsOnPress(n, extra) || extra.unselectable) { + f.areaSkip++ + defer func() { f.areaSkip-- }() + } + } if n.Flags&flagDialog != 0 { f.paintDialog(n) return @@ -50,7 +66,7 @@ func (f *Frame) PaintChild(i int32) { f.Surface.BeginGlide(extra.glideIdentity(n), 0, gfx.Point{X: n.Rect.X + extra.glideScroll.X, Y: n.Rect.Y + extra.glideScroll.Y}, extra.glide) defer f.Surface.EndPose() } - if memo := f.Exts[n.Ext].memo; memo != 0 && f.memoFn != nil { + if memo := f.Exts[n.Ext].memo; memo != 0 && f.memoFn != nil && f.area == nil { if f.memoFn(f, i, true) { return } @@ -371,6 +387,14 @@ func (f *Frame) paintText(n *Node) { style.Direction = gfx.TextDirectionOf(n.Text) } lh := n.leading() + if f.area != nil && f.areaSkip == 0 { + f.beginSelectableText(n, r, style, alignment) + for k := int32(0); k < n.LineCount; k++ { + bounds := Rect{X: r.X, Y: r.Y + float32(k)*lh, Width: r.Width, Height: lh} + f.addSelectableLine(n, f.Lines[n.LineFirst+k], bounds, k == n.LineCount-1) + } + f.paintSelection() + } for k := int32(0); k < n.LineCount; k++ { bounds := Rect{X: r.X, Y: r.Y + float32(k)*lh, Width: r.Width, Height: lh} line := f.Lines[n.LineFirst+k] @@ -387,6 +411,11 @@ func (f *Frame) paintText(n *Node) { if clipped { f.Surface.Clip(r) } + if f.area != nil && f.areaSkip == 0 { + f.beginSelectableText(n, r, style, alignment) + f.addSelectableLine(n, n.Text, bounds, true) + f.paintSelection() + } f.paintLabel(n, n.Text, bounds, style, alignment) if n.TextDecor&textStrike != 0 { f.paintStrike(n.Text, bounds, style, alignment) diff --git a/components/text_selection.go b/base/text_selection.go similarity index 78% rename from components/text_selection.go rename to base/text_selection.go index aef475a1e..6a7fa3dae 100644 --- a/components/text_selection.go +++ b/base/text_selection.go @@ -1,4 +1,4 @@ -package components +package base import ( "math" @@ -9,7 +9,7 @@ import ( // TextPoint is a place in a run of painted texts that a selection can cross: // Surface numbers the text in reading order, from 0, and Offset is a byte -// offset in that text, as MarkdownView.OffsetAt reports it. +// offset in that text, as MarkdownView.OffsetAt or a TextSelectionArea reports it. type TextPoint struct { Surface int Offset int @@ -38,6 +38,50 @@ type TextSelection struct { dragging bool } +// TextRange is the selected part of one text, in byte offsets: of a Text in a +// TextSelectionArea, of the rendered text of a MarkdownView. Anchor is where the +// user began and Focus is where the pointer is now; either may be ahead of the +// other. Range clamps and orders them against the text, so a selection that was +// made before the text changed still copies the part that is there. +type TextRange struct { + Anchor, Focus int +} + +// Range returns the selected bytes, ordered and clamped to text. Clamping snaps +// both ends back to the start of the rune they point into, because a selection +// kept while a streaming message shortened can land inside a multi-byte +// character; without the snap SelectedText would return invalid UTF-8. +func (s TextRange) Range(text []byte) (start, end int) { + start, end = s.Anchor, s.Focus + if start > end { + start, end = end, start + } + start = snapRune(text, min(max(start, 0), len(text))) + end = snapRune(text, min(max(end, 0), len(text))) + return start, end +} + +// rangeIn is Range for a text held as a string. +func (s TextRange) rangeIn(text string) (start, end int) { + start, end = s.Anchor, s.Focus + if start > end { + start, end = end, start + } + start = snapRune(text, min(max(start, 0), len(text))) + end = snapRune(text, min(max(end, 0), len(text))) + return start, end +} + +// snapRune moves offset back to the leading byte of the rune it points into. +// Offsets that are already at a boundary, including len(text), are returned as +// they are. +func snapRune[T string | []byte](text T, offset int) int { + for offset > 0 && offset < len(text) && text[offset]&0xC0 == 0x80 { + offset-- + } + return offset +} + // TextSelectionResult says what Pointer did with an event. type TextSelectionResult struct { // Handled is true when the event belongs to the selection, so nothing else @@ -152,28 +196,28 @@ func (selection *TextSelection) Pointer(event gfx.PointerEvent, at func(gfx.Poin // selection begins or ends only the part on its side. Within one surface the // Anchor and the Focus keep the order the drag gave them, so a drag upward is // not turned round on each paint. The offsets of a surface the selection runs -// past the end of are larger than its text; MarkdownSelection clamps them. -func (selection *TextSelection) In(surface int) MarkdownSelection { +// past the end of are larger than its text; TextRange.Range clamps them. +func (selection *TextSelection) In(surface int) TextRange { if selection.Empty() { - return MarkdownSelection{} + return TextRange{} } first, last := selection.Anchor, selection.Focus if last.before(first) { first, last = last, first } if surface < first.Surface || surface > last.Surface { - return MarkdownSelection{} + return TextRange{} } if first.Surface == last.Surface { - return MarkdownSelection{Anchor: selection.Anchor.Offset, Focus: selection.Focus.Offset} + return TextRange{Anchor: selection.Anchor.Offset, Focus: selection.Focus.Offset} } switch surface { case first.Surface: - return MarkdownSelection{Anchor: first.Offset, Focus: math.MaxInt} + return TextRange{Anchor: first.Offset, Focus: math.MaxInt} case last.Surface: - return MarkdownSelection{Anchor: 0, Focus: last.Offset} + return TextRange{Anchor: 0, Focus: last.Offset} } - return MarkdownSelection{Anchor: 0, Focus: math.MaxInt} + return TextRange{Anchor: 0, Focus: math.MaxInt} } // Text is the selected text of surfaces texts in reading order, with separator @@ -181,7 +225,7 @@ func (selection *TextSelection) In(surface int) MarkdownSelection { // clipboard. text gives the text of one surface for the part In reports for it; // surfaces with nothing selected are skipped and add no separator. It returns "" // for an empty selection. -func (selection *TextSelection) Text(surfaces int, separator string, text func(surface int, part MarkdownSelection) string) string { +func (selection *TextSelection) Text(surfaces int, separator string, text func(surface int, part TextRange) string) string { if selection.Empty() { return "" } diff --git a/base/text_selection_area.go b/base/text_selection_area.go new file mode 100644 index 000000000..2f4c69844 --- /dev/null +++ b/base/text_selection_area.go @@ -0,0 +1,738 @@ +package base + +import ( + "math" + "strings" + "time" + "unicode/utf8" + "unsafe" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/text" +) + +// SetPrimarySelection makes text the primary selection of an X11 desktop, which +// selecting text fills and a middle click pastes. The styled layer installs the +// system's; a host that installs nothing has none. +var SetPrimarySelection func(string) error + +// TextSelectionState is the selection of one TextSelectionArea: what the user has +// selected in it and where the last paint drew its texts. Keep it in the model +// next to what the area shows; its zero value selects nothing. +type TextSelectionState struct { + // Selection is the selected run, from the press (Anchor) to where the pointer + // or the keyboard took it (Focus). Surface numbers the area's texts in reading + // order, as the last paint drew them; Offset is a byte offset in that text. + Selection TextSelection + + id gfx.ID + handlers Handlers + bound *TextSelectionState // the state handlers were made for, so a copy of a state makes its own + canvas *gfx.Canvas + + // texts and lines are what the last paint drew, which the events between two + // paints are read against. + texts []selectableText + lines []selectableLine + // parent is the element the last text collected sits in, and inRow whether + // that element lays its children out in a row, which joins two texts with a tab. + parent int32 + + // pressed says a primary press on a text is held; press is where it went + // down, moved whether it has left that spot, and pointer where it is now. + pressed, moved bool + press, pointer gfx.Point + unit selectUnit + // span is the word or line the press picked, which a drag by words or lines + // keeps whole. anchor is where the last press began, which Shift with a press + // extends from even when that press selected nothing. + span [2]TextPoint + anchor TextPoint + hasAnchor bool + + focused bool // the area had the keyboard focus in the last paint, or lost it to nothing + page *Page + menuBody func(*MenuItems) + menuOpen bool + menuWas bool // the menu was open in the last paint: the keyboard is on its way back + menuAt gfx.Point + primary string // what the area last made the primary selection + + scroll *ScrollState // the area the area scrolls in, which a drag past its edge scrolls + scrollNode int32 // its element, whose rectangle the last paint gave it + scrollRect Rect + stepAt time.Duration +} + +// selectUnit is what a press selects and a drag extends by. +type selectUnit uint8 + +const ( + unitChar selectUnit = iota + unitWord + unitLine +) + +// selectableText is one text of an area as a paint drew it. +type selectableText struct { + text string + style gfx.TextStyle + align gfx.Alignment + // first and count are its lines in TextSelectionState.lines. + first, count int32 + bounds Rect // where its element put it + // tab joins it to the text before it with a tab instead of a line break: the two + // sit side by side in one row, as a label and its value. + tab bool +} + +// selectableLine is one line of a text: the source bytes from to to, drawn as +// shown in bounds. A line cut short by an ellipsis shows fewer bytes than it +// covers: the cut-off rest belongs to it. +type selectableLine struct { + from, to int + shown string + visible int // how many bytes of shown are the text's own, before an ellipsis + bounds Rect +} + +// TextSelectionArea declares a column whose texts the user can select with the +// pointer and copy, as the labels of a dialog, an error or a detail page are in a +// desktop application. Text, Paragraph and Wrap inside it take part, across their +// boundaries: a drag may begin in one and end in another. Text that belongs to a +// control does not (a button's, a link's, a field's, a label given LabelFor: +// anything inside an element that takes presses; a group region given HitWith to +// name its content keeps it in), nor what Unselectable takes out; a field and a +// view with a selection of its own keep theirs. +// +// A press on a text begins a selection, a double press selects a word and a triple +// press a line; Shift with a press extends it. A press in the area's blank part +// begins at the nearest text, so a click there drops the selection. Primary+C +// copies, Primary+A selects all the area holds, Shift with the arrow keys extends +// the selection and Escape drops it; a secondary press opens the page's Copy and +// Select All menu (see PageConfig.EditMenu). The selection is dropped when another +// control takes the keyboard. A drag past the edge of +// the scrolling area the area is in scrolls it. +// +// The area takes no Tab stop. Its texts are copied as their source: a text cut +// short by an ellipsis copies whole. Texts side by side in a row are joined with a +// tab, others with a line break. A text inside a Memo is drawn but not selected. +// +// ui.TextSelectionArea(c, &m.details).Gap(6).Children(func() { +// ui.Text(c, m.fingerprint) +// }) +func TextSelectionArea(c C, state *TextSelectionState) Box { + p := c.page + p.ForbidInMemo("TextSelectionArea") + if state == nil { + panic("ui: TextSelectionArea needs its state") + } + id := p.boundID(pkTextSelection, unsafe.Pointer(state)) + state.id = id + if state.bound != state { + state.bound = state + state.handlers = Handlers{Role: gfx.RoleGroup, Pointer: state.onPointer, Key: state.onKey} + state.menuBody = state.menu + } + state.handlers.parts = p.tree.Sub(id.Scope(), id.Name()) + p.controls = append(p.controls, controlEntry{ID: id, handlers: &state.handlers}) + if p.pointerRoute == nil { + p.keyRoute, p.pointerRoute = (*Page).RouteKey, (*Page).routePointer + } + canvas := c.f.Surface + state.canvas = canvas + if canvas != nil { + state.followFocus(canvas.Focused()) + } + state.menuWas = state.menuOpen + + state.scroll, state.scrollNode = nil, -1 + for i := c.f.Parent; i >= 0; i = c.f.Nodes[i].Parent { + if n := &c.f.Nodes[i]; n.Ext != 0 && c.f.Exts[n.Ext].scrollState != nil { + state.scroll, state.scrollNode = c.f.Exts[n.Ext].scrollState, i + break + } + } + if canvas != nil { + state.dragScroll(canvas) + } + + b := p.container(c.f.Column()) + b.HitWith(id, "", gfx.HitOptions{Role: gfx.RoleGroup, SkipTab: true}) + c.f.textAreas = append(c.f.textAreas, state) + c.f.Extra(b.i).textArea = int32(len(c.f.textAreas)) + + if p.shortcut(c, Primary, "c", id, 0, 0) && state.Has() { + state.copy() + } + if p.shortcut(c, Primary, "a", id, 0, 0) { + state.SelectAll() + } + state.page = p + ContextMenuAt(c, b, &state.menuOpen, state.menuAt, state.menuBody) + return b +} + +// actsOnPress reports whether an element takes presses, which keeps the text inside +// it out of the TextSelectionArea it is in: a button, a link, a label of a control. +// A group region, which declares a hit to name what it holds for assistive +// technology and does nothing when pressed, leaves its text in. +func actsOnPress(n *Node, extra *Extra) bool { + return n.Flags&flagHasHit != 0 && (n.Flags&flagLabelFor != 0 || extra.hit.Role != gfx.RoleGroup) +} + +// Unselectable keeps the element and what it holds out of the TextSelectionArea it +// is in: words the user has no use for copying, such as a decorative caption. +func (b Box) Unselectable() Box { + b.N() + b.f.Extra(b.i).unselectable = true + return b +} + +// Has reports whether text is selected. +func (s *TextSelectionState) Has() bool { + if s.Selection.Empty() { + return false + } + for i := range s.texts { + if s.selected(i) != "" { + return true + } + } + return false +} + +// Text is the selected text, what Primary+C puts on the clipboard: each text's +// selected part in reading order, the parts of two texts in a row joined with a +// tab and others with a line break. +func (s *TextSelectionState) Text() string { + if s.Selection.Empty() { + return "" + } + var out strings.Builder + for i := range s.texts { + piece := s.selected(i) + if piece == "" { + continue + } + if out.Len() > 0 { + if s.texts[i].tab { + out.WriteByte('\t') + } else { + out.WriteByte('\n') + } + } + out.WriteString(piece) + } + return out.String() +} + +// Clear drops the selection. +func (s *TextSelectionState) Clear() { + s.Selection.Clear() + s.pressed, s.hasAnchor = false, false +} + +// SelectAll selects every text the area held in its last paint. +func (s *TextSelectionState) SelectAll() { + s.Selection.SelectAll(len(s.texts), s.length) + s.pressed = false + s.publish() +} + +func (s *TextSelectionState) length(surface int) int { return len(s.texts[surface].text) } + +// selected is the selected part of text i. +func (s *TextSelectionState) selected(i int) string { + value := s.texts[i].text + start, end := s.Selection.In(i).rangeIn(value) + return value[start:end] +} + +// followFocus drops the selection once another control has taken the keyboard, as +// a selectable label's selection goes when it stops being the first responder. The +// area's own menu, which holds the keyboard while it is open, does not count, and +// neither does a press on nothing, which leaves the focus nowhere. +func (s *TextSelectionState) followFocus(focused gfx.ID) { + switch { + case focused == s.id: + s.focused = true + case s.menuOpen, s.menuWas: + case focused.IsZero(): + default: + if s.focused && !s.Selection.Empty() { + s.Clear() + } + s.focused = false + } +} + +func (s *TextSelectionState) copy() { + if value := s.Text(); value != "" && SetClipboardText != nil { + _ = SetClipboardText(value) + } +} + +// publish makes the selection the primary selection, where the desktop has one. +func (s *TextSelectionState) publish() { + if SetPrimarySelection == nil { + return + } + value := s.Text() + if value == "" || value == s.primary { + return + } + if SetPrimarySelection(value) == nil { + s.primary = value + } +} + +// menu is the body of the area's context menu: the page's words for Copy and +// Select All, which act on the area. +func (s *TextSelectionState) menu(menu *MenuItems) { + var labels EditMenuLabels + if s.page != nil && s.page.config.EditMenu != nil { + labels = *s.page.config.EditMenu + } + labels = labels.WithDefaults() + // The item chosen acts on the area and gives it the keyboard back, as a field's + // edit menu does. + if menu.Item(labels.Copy).Keys(Primary, "c").Disabled(!s.Has()).Clicked() { + s.copy() + s.page.editFocus = s.id + } + menu.Separator() + if menu.Item(labels.SelectAll).Keys(Primary, "a").Disabled(len(s.texts) == 0).Clicked() { + s.SelectAll() + s.page.editFocus = s.id + } +} + +// dragScroll scrolls the area the selection is dragged out of, a step of lines +// every 50 ms that grows with the distance past its edge, as a text view does. It +// asks for the frames of the steps only while a drag holds the pointer outside. +func (s *TextSelectionState) dragScroll(canvas *gfx.Canvas) { + if !s.pressed || !s.moved || s.scroll == nil { + return + } + top, bottom := s.scrollRect.Y, s.scrollRect.Y+s.scrollRect.Height + var distance float32 + switch { + case s.pointer.Y < top: + distance = s.pointer.Y - top + case s.pointer.Y > bottom: + distance = s.pointer.Y - bottom + default: + return + } + line := s.lineHeight() + if now := canvas.Now(); now-s.stepAt >= textDragStep { + s.stepAt = now + lines := min(1+float32(math.Abs(float64(distance)))/line, 8) + if distance < 0 { + lines = -lines + } + s.scroll.ScrollTo(min(max(s.scroll.Offset+float32(int(lines))*line, 0), s.scroll.Max())) + } + canvas.RequestFrameIn(textDragStep) +} + +const textDragStep = 50 * time.Millisecond + +// lineHeight is the height of a line of the area's first text, which a drag past +// the edge scrolls by. +func (s *TextSelectionState) lineHeight() float32 { + for _, line := range s.lines { + if line.bounds.Height > 0 { + return line.bounds.Height + } + } + return 16 +} + +// partOf is the text a press landed on, given the target of the event. +func (s *TextSelectionState) partOf(target gfx.ID) (int, bool) { + i, ok := target.In(s.handlers.parts) + return i, ok && i < len(s.texts) +} + +func (s *TextSelectionState) onPointer(event gfx.PointerEvent) gfx.EventResult { + at := gfx.Point{X: event.X, Y: event.Y} + switch event.Kind { + case gfx.PointerDown: + if event.Button == gfx.PointerButtonSecondary { + s.menuOpen, s.menuAt = true, at + return gfx.EventResult{Handled: true, Repaint: true, Focus: s.id} + } + if event.Button != gfx.PointerButtonPrimary { + return gfx.EventResult{} + } + // A press beside the words, in the area's blank part, begins at the nearest of + // them, as a drag in a document does; a click there selects nothing. + var point TextPoint + if surface, onText := s.partOf(event.Target); onText { + point = s.pointIn(surface, at) + } else if nearest, ok := s.pointAt(at); ok { + point = nearest + } else { + had := !s.Selection.Empty() + s.Clear() + return gfx.EventResult{Handled: true, Repaint: had, Focus: s.id} + } + clicks := max(event.ClickCount, 1) + if event.Modifiers&gfx.ModifierShift != 0 && clicks == 1 && (s.hasAnchor || !s.Selection.Empty()) { + s.unit = unitChar + if s.Selection.Empty() { + s.Selection.Anchor = s.anchor + } + s.Selection.Focus = point + } else { + s.unit = unitChar + switch { + case clicks >= 3: + s.unit = unitLine + case clicks == 2: + s.unit = unitWord + } + s.span[0], s.span[1] = s.unitSpan(point) + s.Selection.Select(s.span[0], s.span[1]) + s.anchor, s.hasAnchor = point, true + } + s.pressed, s.moved, s.press, s.pointer = true, false, at, at + return gfx.EventResult{Handled: true, Repaint: true, Focus: s.id} + case gfx.PointerMove: + if !s.pressed { + return gfx.EventResult{} + } + s.pointer = at + if !s.moved && math.Abs(float64(at.X-s.press.X)) < 3 && math.Abs(float64(at.Y-s.press.Y)) < 3 { + return gfx.EventResult{Handled: true} + } + s.moved = true + return gfx.EventResult{Handled: true, Repaint: s.extendTo(at)} + case gfx.PointerUp: + if !s.pressed { + return gfx.EventResult{} + } + s.pressed = false + if s.moved { + s.extendTo(at) + } + if s.Selection.Empty() { + s.Selection.Clear() + } + s.publish() + return gfx.EventResult{Handled: true, Repaint: true} + case gfx.PointerExit: + // The release of a held press was not seen: the system took the press, or + // the button came up outside the window. + if s.pressed { + s.pressed = false + s.publish() + return gfx.EventResult{Handled: true, Repaint: true} + } + } + return gfx.EventResult{} +} + +// extendTo moves the selection's focus to the text under a point of the window, by +// the unit of the press, and reports whether the selection changed. +func (s *TextSelectionState) extendTo(at gfx.Point) bool { + point, ok := s.pointAt(at) + if !ok { + return false + } + was := s.Selection + if s.unit == unitChar { + s.Selection.Focus = point + } else { + from, to := s.unitSpan(point) + if from.before(s.span[0]) { + s.Selection.Anchor, s.Selection.Focus = s.span[1], from + } else { + s.Selection.Anchor, s.Selection.Focus = s.span[0], to + } + } + return s.Selection != was +} + +// unitSpan is the unit of the press around a point: the point itself for +// characters, the word or the line of its text around it. +func (s *TextSelectionState) unitSpan(point TextPoint) (TextPoint, TextPoint) { + if s.unit == unitChar || point.Surface >= len(s.texts) { + return point, point + } + value := s.texts[point.Surface].text + index := utf8.RuneCountInString(value[:min(point.Offset, len(value))]) + var picked text.Range + if s.unit == unitWord { + picked = text.WordRange(value, index) + } else { + picked = text.LineRange(value, index) + } + from, to := byteOfRune(value, picked.Start), byteOfRune(value, picked.End) + return TextPoint{point.Surface, from}, TextPoint{point.Surface, to} +} + +// byteOfRune is the byte offset of rune index i in value, its length past the end. +func byteOfRune(value string, i int) int { + n := 0 + for offset := range value { + if n == i { + return offset + } + n++ + } + return len(value) +} + +func (s *TextSelectionState) onKey(event gfx.KeyEvent) gfx.EventResult { + if event.Release { + return gfx.EventResult{} + } + switch event.Key { + case gfx.KeyEscape: + if s.Selection.Empty() { + return gfx.EventResult{} + } + s.Clear() + return gfx.EventResult{Handled: true, Repaint: true} + case gfx.KeyLeft, gfx.KeyRight, gfx.KeyUp, gfx.KeyDown: + if event.Modifiers&^gfx.ModifierShift != 0 || event.Modifiers&gfx.ModifierShift == 0 || s.Selection.Empty() { + return gfx.EventResult{} + } + focus, ok := s.step(s.Selection.Focus, event.Key) + if !ok || focus == s.Selection.Focus { + return gfx.EventResult{Handled: true} + } + s.Selection.Focus = focus + s.publish() + return gfx.EventResult{Handled: true, Repaint: true} + } + return gfx.EventResult{} +} + +// step is the place one character to either side of point, across the end of a +// text into the next, or one line above or below it, at the same distance across. +func (s *TextSelectionState) step(point TextPoint, key gfx.Key) (TextPoint, bool) { + if point.Surface < 0 || point.Surface >= len(s.texts) { + return point, false + } + value := s.texts[point.Surface].text + offset := min(max(point.Offset, 0), len(value)) + switch key { + case gfx.KeyLeft: + if offset > 0 { + return TextPoint{point.Surface, text.PreviousGraphemeBoundary(value, offset)}, true + } + if point.Surface > 0 { + return TextPoint{point.Surface - 1, len(s.texts[point.Surface-1].text)}, true + } + return point, true + case gfx.KeyRight: + if offset < len(value) { + return TextPoint{point.Surface, nextGraphemeOf(value, offset)}, true + } + if point.Surface+1 < len(s.texts) { + return TextPoint{point.Surface + 1, 0}, true + } + return point, true + } + caret, line, ok := s.caretOf(point) + if !ok { + return point, false + } + y := line.Y - 1 + if key == gfx.KeyDown { + y = line.Y + line.Height + 1 + } + if next, ok := s.pointAt(gfx.Point{X: caret, Y: y}); ok { + return next, true + } + return point, true +} + +func nextGraphemeOf(value string, offset int) int { + for next := offset + 1; next < len(value); next++ { + if gfx.GraphemeStart(value, next) == next { + return next + } + } + return len(value) +} + +// caretOf is the x of the place point is in the line the last paint drew it on, +// and that line's box. +func (s *TextSelectionState) caretOf(point TextPoint) (float32, Rect, bool) { + t := &s.texts[point.Surface] + if t.count == 0 || s.canvas == nil { + return 0, Rect{}, false + } + lines := s.lines[t.first : t.first+t.count] + index := len(lines) - 1 + for k, line := range lines { + if point.Offset < line.to || k == len(lines)-1 { + index = k + break + } + } + line := lines[index] + within := min(max(point.Offset-line.from, 0), line.visible) + origin := s.canvas.LabelOrigin(line.shown, line.bounds, t.style, t.align) + return origin + s.canvas.TextCaretStyle(line.shown, t.style, within), line.bounds, true +} + +// pointAt is the place in the area's texts under a point of the window: in the +// text under it, or else the nearest one, so a drag that leaves a text or crosses +// the gap between two goes on into the next. Above a text it is the text's start +// and below it its end. ok is false for an area with no text. +func (s *TextSelectionState) pointAt(at gfx.Point) (TextPoint, bool) { + best, found := -1, false + var bestDistance float32 + for i := range s.texts { + b := s.texts[i].bounds + dy := max(b.Y-at.Y, at.Y-(b.Y+b.Height), 0) + dx := max(b.X-at.X, at.X-(b.X+b.Width), 0) + distance := dy*1_000_000 + dx + if !found || distance < bestDistance { + best, bestDistance, found = i, distance, true + } + } + if !found { + return TextPoint{}, false + } + return s.pointIn(best, at), true +} + +// pointIn is the place in text i nearest a point of the window. +func (s *TextSelectionState) pointIn(i int, at gfx.Point) TextPoint { + t := &s.texts[i] + if t.count == 0 { + return TextPoint{Surface: i} + } + lines := s.lines[t.first : t.first+t.count] + switch { + case at.Y < lines[0].bounds.Y: + return TextPoint{Surface: i} + case at.Y >= lines[len(lines)-1].bounds.Y+lines[len(lines)-1].bounds.Height: + return TextPoint{Surface: i, Offset: len(t.text)} + } + line := lines[len(lines)-1] + for _, candidate := range lines { + if at.Y < candidate.bounds.Y+candidate.bounds.Height { + line = candidate + break + } + } + if s.canvas == nil { + return TextPoint{Surface: i, Offset: line.from} + } + origin := s.canvas.LabelOrigin(line.shown, line.bounds, t.style, t.align) + offset := s.canvas.TextOffsetAtStyle(line.shown, t.style, at.X-origin) + if offset > line.visible { + // The ellipsis stands for the rest of the text. + return TextPoint{Surface: i, Offset: line.to} + } + return TextPoint{Surface: i, Offset: line.from + offset} +} + +// beginTextArea starts collecting the texts of an area as its element is painted. +func (f *Frame) beginTextArea(s *TextSelectionState) { + s.texts, s.lines, s.parent = s.texts[:0], s.lines[:0], -1 + if s.scrollNode >= 0 && int(s.scrollNode) < len(f.Nodes) { + s.scrollRect = f.Nodes[s.scrollNode].Rect + } +} + +// endTextArea keeps the selection inside the texts the paint drew, and follows a +// drag the paint scrolled the texts under. +func (f *Frame) endTextArea(s *TextSelectionState) { + // A press that has not moved yet holds an empty selection, which is the start of + // a drag and not one to drop. + s.Selection.dragging = s.pressed + s.Selection.Clamp(len(s.texts), s.length) + s.Selection.dragging = false + if s.pressed && s.moved { + s.extendTo(s.pointer) + } +} + +// beginSelectableText collects a Text of the area being painted, whose element +// put it in r; addSelectableLine then gives each of its lines as painted, and +// paintSelection draws its selected part and the region over it that takes the +// pointer for the area, before its words are drawn over that. +func (f *Frame) beginSelectableText(n *Node, r Rect, style gfx.TextStyle, alignment gfx.Alignment) { + s := f.area + t := selectableText{text: n.Text, style: style, align: alignment, first: int32(len(s.lines)), bounds: r} + t.tab = n.Parent >= 0 && n.Parent == s.parent && f.Nodes[n.Parent].Dir == row + s.parent = n.Parent + s.texts = append(s.texts, t) + f.lineAt = 0 +} + +func (f *Frame) addSelectableLine(n *Node, shown string, bounds Rect, last bool) { + s := f.area + line := selectableLine{shown: shown, bounds: bounds} + line.from, line.to, line.visible, f.lineAt = sourceOfLine(n.Text, shown, f.lineAt, last) + s.lines = append(s.lines, line) + s.texts[len(s.texts)-1].count++ +} + +func (f *Frame) paintSelection() { + s := f.area + canvas := f.Surface + if canvas == nil { + return + } + surface := len(s.texts) - 1 + t := &s.texts[surface] + canvas.HitWithOptions(s.handlers.parts.At(surface), t.bounds, "", gfx.HitOptions{Role: gfx.RoleGroup, Cursor: gfx.PointerCursorText, Presentational: true}) + start, end := s.Selection.In(surface).rangeIn(t.text) + if start >= end { + return + } + color := fade(f.Palette.Selection, f.Opacity) + for _, line := range s.lines[t.first : t.first+t.count] { + lo, hi := max(start, line.from), min(end, line.to) + if lo >= hi { + continue + } + from, to := min(lo-line.from, line.visible), hi-line.from + if to > line.visible { + to = len(line.shown) // into the ellipsis, which stands for the rest + } + f.selectionSpans = canvas.TextSelectionStyle(f.selectionSpans[:0], line.shown, t.style, from, to) + origin := canvas.LabelOrigin(line.shown, line.bounds, t.style, t.align) + for _, span := range f.selectionSpans { + canvas.Fill(Rect{X: origin + span.X, Y: line.bounds.Y, Width: span.Width, Height: line.bounds.Height}, color) + } + } +} + +// sourceOfLine finds a line a Text was broken into in its source, from pos on: the +// bytes it covers, how many bytes of shown are the source's own, and where the next +// line is looked for. A line is the source as it is, without the spaces a break +// took; the last may end in an ellipsis, standing for the rest of the text. +func sourceOfLine(source, shown string, pos int, last bool) (from, to, visible, next int) { + pos = min(pos, len(source)) + if shown == "" { + if pos < len(source) && source[pos] == '\n' { + pos++ + } + return pos, pos, 0, pos + } + if at := strings.Index(source[pos:], shown); at >= 0 { + from = pos + at + return from, from + len(shown), len(shown), from + len(shown) + } + prefix := strings.TrimSuffix(shown, ellipsisMark) + if at := strings.Index(source[pos:], prefix); at >= 0 { + return pos + at, len(source), len(prefix), len(source) + } + if last { + return pos, len(source), 0, len(source) + } + return pos, pos, 0, pos +} + +const ellipsisMark = "…" diff --git a/components/text_selection_test.go b/base/text_selection_test.go similarity index 79% rename from components/text_selection_test.go rename to base/text_selection_test.go index c2c6978a6..46f3b69db 100644 --- a/components/text_selection_test.go +++ b/base/text_selection_test.go @@ -1,4 +1,4 @@ -package components +package base import ( "testing" @@ -17,7 +17,7 @@ func selectionAt(point gfx.Point) (TextPoint, bool) { return TextPoint{Surface: surface, Offset: min(int(point.X), len(selectionTexts[surface]))}, true } -func selectionText(surface int, part MarkdownSelection) string { +func selectionText(surface int, part TextRange) string { text := []byte(selectionTexts[surface]) start, end := part.Range(text) return string(text[start:end]) @@ -25,25 +25,25 @@ func selectionText(surface int, part MarkdownSelection) string { func selectionLength(surface int) int { return len(selectionTexts[surface]) } -func press(x, y float32) gfx.PointerEvent { +func selectPress(x, y float32) gfx.PointerEvent { return gfx.PointerEvent{Kind: gfx.PointerDown, Button: gfx.PointerButtonPrimary, X: x, Y: y} } -func drag(x, y float32) gfx.PointerEvent { +func selectDrag(x, y float32) gfx.PointerEvent { return gfx.PointerEvent{Kind: gfx.PointerMove, Button: gfx.PointerButtonPrimary, X: x, Y: y, Captured: true} } -func release(x, y float32) gfx.PointerEvent { +func selectRelease(x, y float32) gfx.PointerEvent { return gfx.PointerEvent{Kind: gfx.PointerUp, Button: gfx.PointerButtonPrimary, X: x, Y: y, Captured: true} } func TestTextSelectionDragsFromOneSurfaceIntoAnother(t *testing.T) { var selection TextSelection - if result := selection.Pointer(press(6, 1), selectionAt); !result.Handled || !result.Changed || !selection.Dragging() { + if result := selection.Pointer(selectPress(6, 1), selectionAt); !result.Handled || !result.Changed || !selection.Dragging() { t.Fatalf("press = %+v dragging=%v", result, selection.Dragging()) } - selection.Pointer(drag(3, 31), selectionAt) - result := selection.Pointer(release(5, 31), selectionAt) + selection.Pointer(selectDrag(3, 31), selectionAt) + result := selection.Pointer(selectRelease(5, 31), selectionAt) if !result.Handled || selection.Dragging() { t.Fatalf("release = %+v dragging=%v", result, selection.Dragging()) } @@ -67,10 +67,10 @@ func TestTextSelectionDraggedBackwardCopiesTheSameText(t *testing.T) { func TestTextSelectionInKeepsTheDragOrderWithinOneSurface(t *testing.T) { var selection TextSelection selection.Select(TextPoint{Surface: 1, Offset: 4}, TextPoint{Surface: 1, Offset: 1}) - if got := selection.In(1); got != (MarkdownSelection{Anchor: 4, Focus: 1}) { + if got := selection.In(1); got != (TextRange{Anchor: 4, Focus: 1}) { t.Fatalf("In = %+v: a drag upward was turned round", got) } - if got := selection.In(0); got != (MarkdownSelection{}) { + if got := selection.In(0); got != (TextRange{}) { t.Fatalf("a surface outside the selection covers %+v", got) } } @@ -91,13 +91,13 @@ func TestTextSelectionCoversWholeSurfacesBetweenItsEnds(t *testing.T) { func TestTextSelectionPressOnNothingIsLeftToTheCaller(t *testing.T) { var selection TextSelection selection.Select(TextPoint{Surface: 0, Offset: 1}, TextPoint{Surface: 0, Offset: 4}) - if result := selection.Pointer(press(0, 500), selectionAt); result.Handled || result.Changed { + if result := selection.Pointer(selectPress(0, 500), selectionAt); result.Handled || result.Changed { t.Fatalf("press off every surface = %+v", result) } if selection.Empty() { t.Fatal("a press the selection did not take cleared it") } - secondary := press(1, 1) + secondary := selectPress(1, 1) secondary.Button = gfx.PointerButtonSecondary if result := selection.Pointer(secondary, selectionAt); result.Handled { t.Fatalf("a secondary press = %+v", result) @@ -106,8 +106,8 @@ func TestTextSelectionPressOnNothingIsLeftToTheCaller(t *testing.T) { func TestTextSelectionClickWithoutDragSelectsNothing(t *testing.T) { var selection TextSelection - selection.Pointer(press(2, 1), selectionAt) - selection.Pointer(release(2, 1), selectionAt) + selection.Pointer(selectPress(2, 1), selectionAt) + selection.Pointer(selectRelease(2, 1), selectionAt) if !selection.Empty() || selection.Dragging() || selection != (TextSelection{}) { t.Fatalf("a click left %+v", selection) } @@ -115,22 +115,22 @@ func TestTextSelectionClickWithoutDragSelectsNothing(t *testing.T) { func TestTextSelectionMovesWithoutAHeldButtonDoNothing(t *testing.T) { var selection TextSelection - selection.Pointer(press(2, 1), selectionAt) - hover := drag(8, 1) + selection.Pointer(selectPress(2, 1), selectionAt) + hover := selectDrag(8, 1) hover.Captured = false if result := selection.Pointer(hover, selectionAt); result.Handled || selection.Focus.Offset != 2 { t.Fatalf("a hovering move = %+v focus=%+v", result, selection.Focus) } var idle TextSelection - if result := idle.Pointer(drag(8, 1), selectionAt); result.Handled { + if result := idle.Pointer(selectDrag(8, 1), selectionAt); result.Handled { t.Fatalf("a move with no drag = %+v", result) } } func TestTextSelectionKeepsWhatWasSelectedWhenThePointerLeavesTheWindow(t *testing.T) { var selection TextSelection - selection.Pointer(press(2, 1), selectionAt) - selection.Pointer(drag(7, 1), selectionAt) + selection.Pointer(selectPress(2, 1), selectionAt) + selection.Pointer(selectDrag(7, 1), selectionAt) exit := gfx.PointerEvent{Kind: gfx.PointerExit} if result := selection.Pointer(exit, selectionAt); !result.Handled || selection.Dragging() || selection.Empty() { t.Fatalf("exit = %+v selection=%+v", result, selection) @@ -165,9 +165,9 @@ func TestTextSelectionClampFollowsTextThatChanged(t *testing.T) { func TestTextSelectionPointerPathDoesNotAllocate(t *testing.T) { var selection TextSelection allocs := testing.AllocsPerRun(100, func() { - selection.Pointer(press(2, 1), selectionAt) - selection.Pointer(drag(7, 31), selectionAt) - selection.Pointer(release(7, 31), selectionAt) + selection.Pointer(selectPress(2, 1), selectionAt) + selection.Pointer(selectDrag(7, 31), selectionAt) + selection.Pointer(selectRelease(7, 31), selectionAt) _ = selection.In(1) }) if allocs != 0 { @@ -177,11 +177,11 @@ func TestTextSelectionPointerPathDoesNotAllocate(t *testing.T) { func BenchmarkTextSelectionDrag(b *testing.B) { var selection TextSelection - selection.Pointer(press(2, 1), selectionAt) + selection.Pointer(selectPress(2, 1), selectionAt) b.ReportAllocs() for b.Loop() { - selection.Pointer(drag(7, 31), selectionAt) - selection.Pointer(drag(3, 11), selectionAt) + selection.Pointer(selectDrag(7, 31), selectionAt) + selection.Pointer(selectDrag(3, 11), selectionAt) } } @@ -198,13 +198,13 @@ func BenchmarkTextSelectionIn(b *testing.B) { func TestTextSelectionEndDragKeepsTheSelection(t *testing.T) { var selection TextSelection - selection.Pointer(press(2, 1), selectionAt) - selection.Pointer(drag(7, 1), selectionAt) + selection.Pointer(selectPress(2, 1), selectionAt) + selection.Pointer(selectDrag(7, 1), selectionAt) selection.EndDrag() if selection.Dragging() || selection.Empty() { t.Fatalf("EndDrag left %+v", selection) } - if result := selection.Pointer(drag(1, 1), selectionAt); result.Handled || selection.Focus.Offset != 7 { + if result := selection.Pointer(selectDrag(1, 1), selectionAt); result.Handled || selection.Focus.Offset != 7 { t.Fatalf("a move after EndDrag = %+v focus=%+v", result, selection.Focus) } } diff --git a/components/doc.go b/components/doc.go index 407fa8107..3abe264ff 100644 --- a/components/doc.go +++ b/components/doc.go @@ -151,13 +151,11 @@ // editor's caret turns over on the terminal's rhythm and comes to rest lit // when the window is left alone. The application keeps one next to its text // and passes the result as ShowCaret. -// - Text selection: `TextSelection` follows a pointer drag that begins in one -// painted text and ends in another (a MarkdownView, a table, a plain block): -// `TextSelection.Pointer` begins, extends and ends it, `TextSelection.In` -// gives the part of each text to paint highlighted, and `TextSelection.Text` -// joins what a copy puts on the clipboard. The application numbers its texts -// in reading order and says where each lies; the caller-owned value -// schedules nothing and allocates nothing while the pointer moves. +// - Text selection: a drag that begins in one painted text and ends in another +// (a MarkdownView, a table, a plain block) is followed by ui.TextSelection, +// whose In gives the TextRange of each text to paint highlighted and Text joins +// what a copy puts on the clipboard. Texts the page declares with ui.Text take +// part in a ui.TextSelectionArea instead, without painting. // - Find bar: `PaintFindBar` paints the find and replace bar of an editor over // two InputSnapshot fields, with option toggles, a count and step buttons; // `FindBarCommandForKey` maps Command or Control+F, F3 and Enter to its diff --git a/components/markdown.go b/components/markdown.go index 4445d099d..2f24d1783 100644 --- a/components/markdown.go +++ b/components/markdown.go @@ -6,6 +6,7 @@ import ( "unicode/utf8" "unsafe" + "github.com/vivaui/viva/base" "github.com/vivaui/viva/gfx" "github.com/vivaui/viva/markdown" ) @@ -100,39 +101,6 @@ func MarkdownLookFor(theme gfx.Theme) MarkdownLook { } } -// MarkdownSelection is a range of the rendered text of a MarkdownView, in byte -// offsets. Anchor is where the user began and Focus is where the pointer is now; -// either may be ahead of the other. Range clamps and orders them against the -// view's text, so a selection that was made before a message changed still -// copies the part that is there. -type MarkdownSelection struct { - Anchor, Focus int -} - -// Range returns the selected bytes, ordered and clamped to text. Clamping snaps -// both ends back to the start of the rune they point into, because a selection -// kept while a streaming message shortened can land inside a multi-byte -// character; without the snap SelectedText would return invalid UTF-8. -func (s MarkdownSelection) Range(text []byte) (start, end int) { - start, end = s.Anchor, s.Focus - if start > end { - start, end = end, start - } - start = snapRune(text, min(max(start, 0), len(text))) - end = snapRune(text, min(max(end, 0), len(text))) - return start, end -} - -// snapRune moves offset back to the leading byte of the rune it points into. -// Offsets that are already at a boundary, including len(text), are returned as -// they are. -func snapRune(text []byte, offset int) int { - for offset > 0 && offset < len(text) && text[offset]&0xC0 == 0x80 { - offset-- - } - return offset -} - // MarkdownCode is a fenced code block of a laid-out document: where it is, so // the application can put a copy button on it, and what it holds. type MarkdownCode struct { @@ -157,7 +125,7 @@ type MarkdownPaint struct { // LinkCount of the views before it. Base int // Selection is highlighted behind its text. The zero range paints nothing. - Selection MarkdownSelection + Selection base.TextRange } var _ gfx.TextPlacement = (*MarkdownView)(nil) @@ -209,7 +177,7 @@ func (v *MarkdownView) TextLen() int { return len(v.plain) } // SelectedText returns the rendered text of sel: what a copy of the selection // puts on the clipboard. Offsets are clamped to the laid-out text, so an empty // view or a selection outside it returns "". -func (v *MarkdownView) SelectedText(sel MarkdownSelection) string { +func (v *MarkdownView) SelectedText(sel base.TextRange) string { start, end := sel.Range(v.plain) return string(v.plain[start:end]) } diff --git a/components/markdown_test.go b/components/markdown_test.go index 525aa7b0c..c475f67c7 100644 --- a/components/markdown_test.go +++ b/components/markdown_test.go @@ -6,6 +6,7 @@ import ( "testing" "unicode/utf8" + "github.com/vivaui/viva/base" "github.com/vivaui/viva/gfx" "github.com/vivaui/viva/markdown" ) @@ -54,22 +55,22 @@ func TestMarkdownSelectionRangeClampsAndOrders(t *testing.T) { const digits = "0123456789" // ASCII, so every offset is a rune boundary tests := []struct { name string - sel MarkdownSelection + sel base.TextRange text string start int end int }{ - {name: "empty", sel: MarkdownSelection{Anchor: 4, Focus: 4}, text: digits, start: 4, end: 4}, - {name: "forward", sel: MarkdownSelection{Anchor: 2, Focus: 7}, text: digits, start: 2, end: 7}, - {name: "reversed", sel: MarkdownSelection{Anchor: 7, Focus: 2}, text: digits, start: 2, end: 7}, - {name: "negative", sel: MarkdownSelection{Anchor: -3, Focus: 4}, text: digits, start: 0, end: 4}, - {name: "past the end", sel: MarkdownSelection{Anchor: 4, Focus: 99}, text: digits, start: 4, end: 10}, - {name: "outside both ways", sel: MarkdownSelection{Anchor: -8, Focus: 99}, text: digits, start: 0, end: 10}, - {name: "empty text", sel: MarkdownSelection{Anchor: -1, Focus: 3}, text: "", start: 0, end: 0}, - {name: "start inside a rune", sel: MarkdownSelection{Anchor: 3, Focus: 5}, text: "a 中", start: 2, end: 5}, - {name: "end inside a rune", sel: MarkdownSelection{Anchor: 0, Focus: 4}, text: "a 中", start: 0, end: 2}, - {name: "both inside a rune", sel: MarkdownSelection{Anchor: 4, Focus: 3}, text: "a 中", start: 2, end: 2}, - {name: "clamped into a rune", sel: MarkdownSelection{Anchor: 3, Focus: 6}, text: "a 中", start: 2, end: 5}, + {name: "empty", sel: base.TextRange{Anchor: 4, Focus: 4}, text: digits, start: 4, end: 4}, + {name: "forward", sel: base.TextRange{Anchor: 2, Focus: 7}, text: digits, start: 2, end: 7}, + {name: "reversed", sel: base.TextRange{Anchor: 7, Focus: 2}, text: digits, start: 2, end: 7}, + {name: "negative", sel: base.TextRange{Anchor: -3, Focus: 4}, text: digits, start: 0, end: 4}, + {name: "past the end", sel: base.TextRange{Anchor: 4, Focus: 99}, text: digits, start: 4, end: 10}, + {name: "outside both ways", sel: base.TextRange{Anchor: -8, Focus: 99}, text: digits, start: 0, end: 10}, + {name: "empty text", sel: base.TextRange{Anchor: -1, Focus: 3}, text: "", start: 0, end: 0}, + {name: "start inside a rune", sel: base.TextRange{Anchor: 3, Focus: 5}, text: "a 中", start: 2, end: 5}, + {name: "end inside a rune", sel: base.TextRange{Anchor: 0, Focus: 4}, text: "a 中", start: 0, end: 2}, + {name: "both inside a rune", sel: base.TextRange{Anchor: 4, Focus: 3}, text: "a 中", start: 2, end: 2}, + {name: "clamped into a rune", sel: base.TextRange{Anchor: 3, Focus: 6}, text: "a 中", start: 2, end: 5}, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { @@ -95,7 +96,7 @@ func TestMarkdownSelectionClampedMidRuneIsValidUTF8(t *testing.T) { view.Layout(canvas, style, &doc, 400) } layout("a `中") - sel := MarkdownSelection{Anchor: 3, Focus: view.TextLen()} + sel := base.TextRange{Anchor: 3, Focus: view.TextLen()} if got := view.SelectedText(sel); got != "中" { t.Fatalf("SelectedText before the change = %q, want %q", got, "中") } @@ -114,7 +115,7 @@ func TestEmptyMarkdownViewHasNoTextToSelect(t *testing.T) { if got := view.TextLen(); got != 0 { t.Fatalf("TextLen = %d, want 0", got) } - if got := view.SelectedText(MarkdownSelection{Anchor: -2, Focus: 5}); got != "" { + if got := view.SelectedText(base.TextRange{Anchor: -2, Focus: 5}); got != "" { t.Fatalf("SelectedText = %q, want empty", got) } } @@ -125,10 +126,10 @@ func TestMarkdownSelectionUsesRenderedTextWithoutSoftWraps(t *testing.T) { t.Fatalf("the paragraph did not wrap: %+v", view.pieces) } const want = "alpha beta gamma delta epsilon" - if got := view.SelectedText(MarkdownSelection{Anchor: 0, Focus: view.TextLen()}); got != want { + if got := view.SelectedText(base.TextRange{Anchor: 0, Focus: view.TextLen()}); got != want { t.Fatalf("selected %q, want %q", got, want) } - if got := view.SelectedText(MarkdownSelection{Anchor: 11, Focus: 16}); got != "gamma" { + if got := view.SelectedText(base.TextRange{Anchor: 11, Focus: 16}); got != "gamma" { t.Fatalf("selected %q, want gamma", got) } } @@ -136,7 +137,7 @@ func TestMarkdownSelectionUsesRenderedTextWithoutSoftWraps(t *testing.T) { func TestMarkdownSelectionHasOneBreakBetweenBlocks(t *testing.T) { view, _ := layoutMarkdown(t, "first paragraph\n\nsecond paragraph", 200, MarkdownStyle{Size: 12}) const want = "first paragraph\nsecond paragraph" - if got := view.SelectedText(MarkdownSelection{Anchor: 0, Focus: view.TextLen()}); got != want { + if got := view.SelectedText(base.TextRange{Anchor: 0, Focus: view.TextLen()}); got != want { t.Fatalf("selected %q, want %q", got, want) } } @@ -145,7 +146,7 @@ func TestMarkdownSelectionUsesVisibleInlineTextAndSpacing(t *testing.T) { src := "before **bold** and `code` and a [link](https://example.com/x) after" view, _ := layoutMarkdown(t, src, 200, MarkdownStyle{Size: 12}) const want = "before bold and code and a link after" - if got := view.SelectedText(MarkdownSelection{Anchor: 0, Focus: view.TextLen()}); got != want { + if got := view.SelectedText(base.TextRange{Anchor: 0, Focus: view.TextLen()}); got != want { t.Fatalf("selected %q, want %q", got, want) } } @@ -154,7 +155,7 @@ func TestMarkdownSelectionReadsTableCellsInRenderedOrder(t *testing.T) { src := "| Name | Value |\n|:--|--:|\n| ssh | shell |\n| ftp | old |\n" view, _ := layoutMarkdown(t, src, 300, MarkdownStyle{Size: 12}) const want = "Name Value\nssh shell\nftp old" - if got := view.SelectedText(MarkdownSelection{Anchor: 0, Focus: view.TextLen()}); got != want { + if got := view.SelectedText(base.TextRange{Anchor: 0, Focus: view.TextLen()}); got != want { t.Fatalf("selected %q, want %q", got, want) } } @@ -189,7 +190,7 @@ func TestFencedCodeCopiesSourceLinesWithoutVisualWraps(t *testing.T) { t.Fatalf("the long code line did not wrap: %d pieces", mono) } want := line + "\nsecond line" - if got := view.SelectedText(MarkdownSelection{Anchor: 0, Focus: view.TextLen()}); got != want { + if got := view.SelectedText(base.TextRange{Anchor: 0, Focus: view.TextLen()}); got != want { t.Fatalf("selected %q, want %q", got, want) } } @@ -197,7 +198,7 @@ func TestFencedCodeCopiesSourceLinesWithoutVisualWraps(t *testing.T) { func TestFencedCodeKeepsTabsAndCopiesThem(t *testing.T) { view, _ := layoutMarkdown(t, "```\n\tfoo\tbar\n```\n", 300, MarkdownStyle{Size: 12}) const want = "\tfoo\tbar" - if got := view.SelectedText(MarkdownSelection{Anchor: 0, Focus: view.TextLen()}); got != want { + if got := view.SelectedText(base.TextRange{Anchor: 0, Focus: view.TextLen()}); got != want { t.Fatalf("selected %q, want %q", got, want) } tests := []struct { @@ -211,7 +212,7 @@ func TestFencedCodeKeepsTabsAndCopiesThem(t *testing.T) { {start: 5, end: 8, want: "bar"}, } for _, test := range tests { - if got := view.SelectedText(MarkdownSelection{Anchor: test.start, Focus: test.end}); got != test.want { + if got := view.SelectedText(base.TextRange{Anchor: test.start, Focus: test.end}); got != test.want { t.Errorf("select %d..%d = %q, want %q", test.start, test.end, got, test.want) } } @@ -222,7 +223,7 @@ func TestCodeChunkBoundariesDoNotSplitATab(t *testing.T) { // to end before it, and the next one owns the whole tab. view, _ := layoutMarkdown(t, "```\nabcde\tX\n```\n", 56, MarkdownStyle{Size: 12}) const want = "abcde\tX" - if got := view.SelectedText(MarkdownSelection{Anchor: 0, Focus: view.TextLen()}); got != want { + if got := view.SelectedText(base.TextRange{Anchor: 0, Focus: view.TextLen()}); got != want { t.Fatalf("selected %q, want %q", got, want) } last := int32(0) @@ -387,7 +388,7 @@ func TestMarkdownPaintsPaintedSelection(t *testing.T) { selected := gfx.Color{Red: 1, Alpha: 1} var painted gfx.Canvas view.Paint(&painted, MarkdownPaint{ - Look: MarkdownLook{Selection: selected}, X: 10, Y: 20, Selection: MarkdownSelection{Anchor: 0, Focus: 5}, + Look: MarkdownLook{Selection: selected}, X: 10, Y: 20, Selection: base.TextRange{Anchor: 0, Focus: 5}, }) rects := markdownSelectionRects(&painted, selected) if len(rects) != 1 { @@ -410,7 +411,7 @@ func TestMarkdownPaintsNoSelectionForAnEmptyRange(t *testing.T) { selected := gfx.Color{Red: 1, Alpha: 1} var painted gfx.Canvas view.Paint(&painted, MarkdownPaint{ - Look: MarkdownLook{Selection: selected}, Selection: MarkdownSelection{Anchor: 4, Focus: 4}, + Look: MarkdownLook{Selection: selected}, Selection: base.TextRange{Anchor: 4, Focus: 4}, }) if rects := markdownSelectionRects(&painted, selected); len(rects) != 0 { t.Fatalf("empty selection painted %+v", rects) @@ -428,7 +429,7 @@ func TestMarkdownSelectionIsClippedToVisibleLines(t *testing.T) { } second := view.pieces[1] selected := gfx.Color{Red: 1, Alpha: 1} - paint := func(selection MarkdownSelection) *gfx.Canvas { + paint := func(selection base.TextRange) *gfx.Canvas { var painted gfx.Canvas view.Paint(&painted, MarkdownPaint{ Look: MarkdownLook{Selection: selected}, Selection: selection, @@ -436,10 +437,10 @@ func TestMarkdownSelectionIsClippedToVisibleLines(t *testing.T) { }) return &painted } - if rects := markdownSelectionRects(paint(MarkdownSelection{Anchor: 0, Focus: 5}), selected); len(rects) != 0 { + if rects := markdownSelectionRects(paint(base.TextRange{Anchor: 0, Focus: 5}), selected); len(rects) != 0 { t.Fatalf("a selection above the clip painted %+v", rects) } - if rects := markdownSelectionRects(paint(MarkdownSelection{Anchor: 0, Focus: 12}), selected); len(rects) != 1 { + if rects := markdownSelectionRects(paint(base.TextRange{Anchor: 0, Focus: 12}), selected); len(rects) != 1 { t.Fatalf("the visible line painted %d selection rectangles, want 1", len(rects)) } } @@ -454,7 +455,7 @@ func TestMarkdownCodeSelectionCoversATabAsCells(t *testing.T) { behind := gfx.Color{Green: 1, Alpha: 1} var painted gfx.Canvas view.Paint(&painted, MarkdownPaint{ - Look: MarkdownLook{Selection: selected, CodeFill: behind}, Selection: MarkdownSelection{Anchor: 5, Focus: 6}, + Look: MarkdownLook{Selection: selected, CodeFill: behind}, Selection: base.TextRange{Anchor: 5, Focus: 6}, }) rects := markdownSelectionRects(&painted, selected) if len(rects) != 1 { @@ -617,7 +618,7 @@ func TestMarkdownLayoutAndPaintDoNotAllocateOnceWarm(t *testing.T) { canvas := markdownCanvas() var view MarkdownView look := MarkdownLookFor(gfx.DarkTheme()) - selection := MarkdownSelection{Anchor: 2, Focus: 40} + selection := base.TextRange{Anchor: 2, Focus: 40} run := func() { canvas.Reset() view.Layout(canvas, MarkdownStyle{Size: 13}, &doc, 400) @@ -661,7 +662,7 @@ func TestMarkdownCandidateLineMeasurementsMatchWhatIsPainted(t *testing.T) { const width = 132 view.Layout(nonlinearMarkdownCanvas(), MarkdownStyle{Size: 12}, &doc, width) want := strings.NewReplacer("**", "", "`", "").Replace(test.src) - if got := view.SelectedText(MarkdownSelection{Focus: view.TextLen()}); got != want { + if got := view.SelectedText(base.TextRange{Focus: view.TextLen()}); got != want { t.Fatalf("rendered text = %q, want %q", got, want) } for _, piece := range view.pieces { @@ -704,7 +705,7 @@ func TestMarkdownClosingPunctuationMovesWithThePrecedingText(t *testing.T) { if moved == nil || moved.x != 0 || moved.y == 0 { t.Fatalf("punctuation was not moved with its preceding text: %+v", view.pieces) } - if got := view.SelectedText(MarkdownSelection{Focus: view.TextLen()}); got != "abcdef。" { + if got := view.SelectedText(base.TextRange{Focus: view.TextLen()}); got != "abcdef。" { t.Fatalf("rendered text = %q", got) } } @@ -717,7 +718,7 @@ func TestMarkdownLongClosingRunKeepsPunctuationInsideTheColumn(t *testing.T) { var view MarkdownView const width = 40 view.Layout(markdownCanvas(), MarkdownStyle{Size: 12}, &doc, width) - if got := view.SelectedText(MarkdownSelection{Focus: view.TextLen()}); got != "abcdefg。" { + if got := view.SelectedText(base.TextRange{Focus: view.TextLen()}); got != "abcdefg。" { t.Fatalf("rendered text = %q", got) } for _, piece := range view.pieces { @@ -740,7 +741,7 @@ func TestMarkdownLongClosingRunKeepsPunctuationInsideTheColumn(t *testing.T) { func TestMarkdownMonoClosingRunMovesItsSuffixWithThePunctuation(t *testing.T) { const width = 40 view, canvas := paintedMarkdown(t, "a`bcdefgh`。", width) - if got := view.SelectedText(MarkdownSelection{Focus: view.TextLen()}); got != "abcdefgh。" { + if got := view.SelectedText(base.TextRange{Focus: view.TextLen()}); got != "abcdefgh。" { t.Fatalf("rendered text = %q, want %q", got, "abcdefgh。") } var code []*mdPiece @@ -791,7 +792,7 @@ func TestMarkdownClosingPunctuationUsesTheJoinedShapedWidth(t *testing.T) { var view MarkdownView const width = 40 view.Layout(nonlinearMarkdownCanvas(), MarkdownStyle{Size: 12}, &doc, width) - if got := view.SelectedText(MarkdownSelection{Focus: view.TextLen()}); got != "xbcdef。" { + if got := view.SelectedText(base.TextRange{Focus: view.TextLen()}); got != "xbcdef。" { t.Fatalf("rendered text = %q", got) } for _, piece := range view.pieces { @@ -847,7 +848,7 @@ func TestMarkdownClosingPunctuationKeepsThePrecedingSpanStyle(t *testing.T) { func TestMarkdownBreakpointRewindPaintsEachPieceBackgroundAndLinkOnce(t *testing.T) { src := "a**bcdef**。 [link](https://example.com)" view, _ := layoutMarkdown(t, src, 40, MarkdownStyle{Size: 12}) - if got := view.SelectedText(MarkdownSelection{Focus: view.TextLen()}); got != "abcdef。 link" { + if got := view.SelectedText(base.TextRange{Focus: view.TextLen()}); got != "abcdef。 link" { t.Fatalf("rendered text = %q", got) } paintedFor := func(label string) map[string]int { @@ -907,7 +908,7 @@ func TestMarkdownReflowKeepsShapedTextInsideTheColumn(t *testing.T) { t.Errorf("at %v wide, piece %q is at %v..%v", width, p.text, p.x, p.x+p.w) } } - if got, want := view.SelectedText(MarkdownSelection{Focus: view.TextLen()}), "端口绑定在 127.0.0.1,外部访问仍要从宿主机转发。"; got != want { + if got, want := view.SelectedText(base.TextRange{Focus: view.TextLen()}), "端口绑定在 127.0.0.1,外部访问仍要从宿主机转发。"; got != want { t.Errorf("at %v wide, rendered text = %q, want %q", width, got, want) } } @@ -920,7 +921,7 @@ func TestLongTokensWrapByCompleteUTF8Characters(t *testing.T) { var view MarkdownView const width = 72 view.Layout(nonlinearMarkdownCanvas(), MarkdownStyle{Size: 12}, &doc, width) - if got := view.SelectedText(MarkdownSelection{Focus: view.TextLen()}); got != token { + if got := view.SelectedText(base.TextRange{Focus: view.TextLen()}); got != token { t.Fatalf("rendered text = %q, want %q", got, token) } for _, p := range view.pieces { @@ -1146,7 +1147,7 @@ func TestMarkdownStrikeOnInlineCodeCoversOnlyTheTextArea(t *testing.T) { func TestInlineCodeCopyDoesNotIncludeVisualPadding(t *testing.T) { src := "端口绑`127.0.0.1`还是" view, _ := layoutMarkdown(t, src, 220, MarkdownStyle{Size: 12}) - if got := view.SelectedText(MarkdownSelection{Focus: view.TextLen()}); got != "端口绑127.0.0.1还是" { + if got := view.SelectedText(base.TextRange{Focus: view.TextLen()}); got != "端口绑127.0.0.1还是" { t.Errorf("copied text = %q", got) } var piece *mdPiece @@ -1159,7 +1160,7 @@ func TestInlineCodeCopyDoesNotIncludeVisualPadding(t *testing.T) { if piece == nil { t.Fatal("no inline code piece") } - selected := view.SelectedText(MarkdownSelection{Anchor: int(piece.plainLo), Focus: int(piece.plainHi)}) + selected := view.SelectedText(base.TextRange{Anchor: int(piece.plainLo), Focus: int(piece.plainHi)}) if selected != "127.0.0.1" { t.Errorf("selected inline code = %q", selected) } @@ -1168,7 +1169,7 @@ func TestInlineCodeCopyDoesNotIncludeVisualPadding(t *testing.T) { func TestMarkdownAdjacentInlineCodeAndPunctuationKeepFullFragments(t *testing.T) { view, _ := layoutMarkdown(t, "`a` `bb`,前`127.0.0.1`后", 220, MarkdownStyle{Size: 12}) const want = "a bb,前127.0.0.1后" - if got := view.SelectedText(MarkdownSelection{Focus: view.TextLen()}); got != want { + if got := view.SelectedText(base.TextRange{Focus: view.TextLen()}); got != want { t.Fatalf("rendered text = %q, want %q", got, want) } for _, text := range []string{"a", "bb", "127.0.0.1"} { @@ -1208,7 +1209,7 @@ func TestMarkdownTinyWidthsTerminateWithValidText(t *testing.T) { doc.Parse(test.src) var view MarkdownView view.Layout(nonlinearMarkdownCanvas(), MarkdownStyle{Size: 12}, &doc, 40) - got := view.SelectedText(MarkdownSelection{Focus: view.TextLen()}) + got := view.SelectedText(base.TextRange{Focus: view.TextLen()}) if got != test.want { t.Fatalf("rendered text = %q, want %q", got, test.want) } @@ -1243,7 +1244,7 @@ func TestInlineCodeSelectionRectsStayInsideThePaddedBackground(t *testing.T) { var painted gfx.Canvas view.Paint(&painted, MarkdownPaint{ Look: MarkdownLook{Selection: selected}, - Selection: MarkdownSelection{Anchor: int(piece.plainLo), Focus: int(piece.plainHi)}, + Selection: base.TextRange{Anchor: int(piece.plainLo), Focus: int(piece.plainHi)}, }) rects := markdownSelectionRects(&painted, selected) if len(rects) != 1 { @@ -1287,7 +1288,7 @@ func TestMarkdownPaintNestsItsClipAndRestoresTheCallerStack(t *testing.T) { view.Layout(markdownCanvas(), MarkdownStyle{Size: 12}, &doc, 300) selection := gfx.Color{Red: 1, Alpha: 1} view.Paint(&canvas, MarkdownPaint{ - Look: MarkdownLook{Selection: selection}, Selection: MarkdownSelection{Anchor: 0, Focus: view.TextLen()}, + Look: MarkdownLook{Selection: selection}, Selection: base.TextRange{Anchor: 0, Focus: view.TextLen()}, X: inner.X, Y: inner.Y, Clip: inner, Links: gfx.Scope(1), }) if clips := canvas.Clips(); len(clips) != 1 || clips[0].Bounds != outer { @@ -1503,7 +1504,7 @@ func TestFencedCodeBlankLinesLayOut(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { view, _ := layoutMarkdown(t, test.src, 300, MarkdownStyle{Size: 12}) - if got := view.SelectedText(MarkdownSelection{Anchor: 0, Focus: view.TextLen()}); got != test.want { + if got := view.SelectedText(base.TextRange{Anchor: 0, Focus: view.TextLen()}); got != test.want { t.Fatalf("selected %q, want %q", got, test.want) } }) @@ -1513,7 +1514,7 @@ func TestFencedCodeBlankLinesLayOut(t *testing.T) { func TestFencedCodeToleratesInvalidUTF8(t *testing.T) { view, _ := layoutMarkdown(t, "```\n\xff\n```\n", 300, MarkdownStyle{Size: 12}) const want = "\xff" - if got := view.SelectedText(MarkdownSelection{Anchor: 0, Focus: view.TextLen()}); got != want { + if got := view.SelectedText(base.TextRange{Anchor: 0, Focus: view.TextLen()}); got != want { t.Fatalf("selected %q, want %q", got, want) } } @@ -1528,7 +1529,7 @@ func TestInlineCodeSelectionUsesItsOwnCellWidth(t *testing.T) { var painted gfx.Canvas // "alpha " is six bytes, then the four bytes of the inline code. view.Paint(&painted, MarkdownPaint{ - Look: MarkdownLook{Selection: selected}, Selection: MarkdownSelection{Anchor: 6, Focus: 10}, + Look: MarkdownLook{Selection: selected}, Selection: base.TextRange{Anchor: 6, Focus: 10}, }) rects := markdownSelectionRects(&painted, selected) if len(rects) != 1 { @@ -1757,7 +1758,7 @@ func TestHeadingInlineCodeSelectionUsesItsOwnCellWidth(t *testing.T) { var painted gfx.Canvas view.Paint(&painted, MarkdownPaint{ Look: MarkdownLook{Selection: selected}, - Selection: MarkdownSelection{Anchor: int(piece.plainLo), Focus: int(piece.plainHi)}, + Selection: base.TextRange{Anchor: int(piece.plainLo), Focus: int(piece.plainHi)}, }) rects := markdownSelectionRects(&painted, selected) if len(rects) != 1 { diff --git a/docs/skills/building-with-viva/SKILL.md b/docs/skills/building-with-viva/SKILL.md index 9d180cfeb..c09092bdf 100644 --- a/docs/skills/building-with-viva/SKILL.md +++ b/docs/skills/building-with-viva/SKILL.md @@ -90,6 +90,7 @@ func (m *model) page(c ui.C) { - A heavy or stateful page control lives in an opt-in package under `ui/`; import it only when the page uses it. - Editors and visuals: `ui/codeeditor`, `ui/textview`, `ui/chart`, `ui/markdown`, `ui/image`, `ui/calendar`, `ui/carousel`, `ui/columnresize`, `ui/reordergrid`. Navigation and overlays: `ui/command`, `ui/menubar`, `ui/navigationmenu`, `ui/sidebar`, `ui/hovercard`. Data and inputs: `ui/avatar`, `ui/avatareditor`, `ui/attachment`, `ui/metriccard`, `ui/marker`, `ui/skeleton`, `ui/aspectratio`, `ui/questionnaire`, `ui/messagescroller`, `ui/message`, `ui/inputgroup`, `ui/inputotp`, `ui/multiselect`, `ui/hierarchypicker`, `ui/buttongroup`, `ui/togglegroup`, `ui/steps`, `ui/descriptions`, `ui/timeline`, `ui/rate`, `ui/inputnumber`, `ui/datepicker`, `ui/timepicker`, `ui/transfer`, `ui/alert`, `ui/tag`, `ui/breadcrumb`, `ui/card`, `ui/empty`, `ui/result`, `ui/pagination`, `ui/editabletabs`, `ui/popconfirm`, `ui/divider`, `ui/typography`, `ui/validate`, `ui/upload`, `ui/anchor`, `ui/comment`, `ui/imagepreview`, `ui/mentions`, `ui/tour`, `ui/overflowlist`, `ui/statistic`, `ui/inputtag`, `ui/autocomplete`, `ui/indicator`. +- Read-only words the user may copy (an error, a fingerprint, a detail page) go in `ui.TextSelectionArea(c, &m.details).Children(...)`: the `Text`, `Paragraph` and `Wrap` inside can be dragged across, double-clicked and copied, while buttons and fields inside keep their presses. `Box.Unselectable()` takes a decorative text out. - For read-only selectable output, keep a `textview.View` in the model and call `m.output.Declare(c, textview.Spec{Source: lines, Scroll: true})`. The caller owns lines, spans and actions; `ui/textview` owns selection and drawing without an editing model. - The package name is the capability, never a `view` suffix. Name its state type by role, not by repeating the package: `calendar.State`, `message.Row`, `attachment.Card`, `hovercard.Card`. Keep locals out of the package name (`cal`, `msg`, `pic`); a model field may keep the domain noun (`m.calendar`). - Some packages expose `pkg.View(c, label, &state)` (`calendar.View`, `markdown.View`); others expose a method on the state (`avatar.New().View(c, label)`, `questionnaire.New().View(c, label)`). `go doc github.com/vivaui/viva/ui/` shows which. diff --git a/gfx/canvas.go b/gfx/canvas.go index 2fe04c2a6..e778d4eff 100644 --- a/gfx/canvas.go +++ b/gfx/canvas.go @@ -527,6 +527,12 @@ type HitOptions struct { PassPrimary bool // label makes the hit a label of its ID's control (see Canvas.HitLabel). label bool + // Presentational makes the hit a region that only takes the pointer: a part of a + // control over content that assistive technology already reads, such as the + // painted words of a selectable text, which shows the text cursor over the + // words. It has no accessibility node of its own and is never focused; a press + // on it reaches its control as a press on any part does. + Presentational bool // Autofocus gives the hit the keyboard in the paint where it first // appears, that is, when the previous paint did not declare its ID. Use it // for a page that should be ready to type into as soon as it is shown, @@ -653,6 +659,8 @@ type Hit struct { // Container marks a semantic region with no target: a menu, listbox, grid, // heading or status area. It is not hit-testable and declares no control. Container bool + // Presentational is HitOptions.Presentational. + Presentational bool // IsLabel marks a label of the control the ID names (see Canvas.HitLabel): // a press on it is a press on the control, it is no tab stop and no node of // its own, and its Label text names the control for assistive technology. @@ -1726,7 +1734,7 @@ func (canvas *Canvas) HitWithOptions(id ID, bounds Rect, label string, options H if role == 0 { role = RoleButton } - focusable := (!options.Disabled || options.FocusableWhenDisabled) && !options.SkipFocus + focusable := (!options.Disabled || options.FocusableWhenDisabled) && !options.SkipFocus && !options.Presentational if options.Secure { options.Value = "" } @@ -1753,7 +1761,7 @@ func (canvas *Canvas) HitWithOptions(id ID, bounds Rect, label string, options H Multiline: options.Multiline, ReadOnly: options.ReadOnly, Invalid: options.Invalid, Secure: options.Secure, Description: options.Description, Level: options.Level, PosInSet: options.PosInSet, SetSize: options.SetSize, Live: options.Live, Range: options.Range, - Focusable: focusable, SkipTab: focusable && options.SkipTab, Autofocus: options.Autofocus && focusable, IsLabel: options.label, Backdrop: options.Backdrop, + Focusable: focusable, SkipTab: focusable && options.SkipTab, Autofocus: options.Autofocus && focusable, IsLabel: options.label, Presentational: options.Presentational, Backdrop: options.Backdrop, PassSecondary: options.Backdrop && options.PassSecondary, PassPrimary: options.Backdrop && options.PassPrimary, HideNativeOverlays: options.HideNativeOverlays, NavigationKeys: options.NavigationKeys, diff --git a/headless/layout.go b/headless/layout.go index 0041e87a9..84e8f3ac4 100644 --- a/headless/layout.go +++ b/headless/layout.go @@ -160,14 +160,15 @@ func lineExtent(text gfx.Text, width float32) gfx.Rect { // innermostControl is the smallest control on text's layer that holds the middle // of the line. A line that runs out of its control by more than half of itself // belongs to no control and is not found. Opaque panels count; labels of a -// control, which are the text's own extent, and backdrops do not. +// control and the pointer regions of a selectable text, which are the text's own +// extent, and backdrops do not. func innermostControl(hits []gfx.Hit, text gfx.Text, width float32) (gfx.Hit, bool) { line := lineExtent(text, width) middleY := line.Y + line.Height/2 var best gfx.Hit found := false for _, hit := range hits { - if hit.Layer != text.Layer || hit.IsLabel || hit.Backdrop || hit.MovesWindow || hit.Disabled && !hit.Block { + if hit.Layer != text.Layer || hit.IsLabel || hit.Presentational || hit.Backdrop || hit.MovesWindow || hit.Disabled && !hit.Block { continue } bounds := hit.Bounds diff --git a/headless/session.go b/headless/session.go index c4326d824..cb4cbe90e 100644 --- a/headless/session.go +++ b/headless/session.go @@ -407,7 +407,7 @@ func (session *Session) CheckStrict() error { ids := map[gfx.ID]bool{} labels := map[string]bool{} for _, hit := range hits { - if hit.ID.IsZero() || hit.IsLabel || hit.Backdrop || hit.Block { + if hit.ID.IsZero() || hit.IsLabel || hit.Presentational || hit.Backdrop || hit.Block { continue } if ids[hit.ID] { diff --git a/internal/platform/web/accessibility.go b/internal/platform/web/accessibility.go index 702209130..19255da7e 100644 --- a/internal/platform/web/accessibility.go +++ b/internal/platform/web/accessibility.go @@ -57,8 +57,8 @@ func describeAccessibility(destination []accessibilityDescription, hits []gfx.Hi } } for _, hit := range hits { - if hit.Block || hit.MovesWindow || hit.IsLabel { - continue // an occluder, a move region, or a label of another node + if hit.Block || hit.MovesWindow || hit.IsLabel || hit.Presentational { + continue // an occluder, a move region, a label of another node, or a pointer region } label := hit.Label if name, ok := names[hit.ID]; ok { diff --git a/ui/edit_menu.go b/ui/edit_menu.go index 00e74fc36..306813e41 100644 --- a/ui/edit_menu.go +++ b/ui/edit_menu.go @@ -15,7 +15,7 @@ type EditMenuLabels = base.EditMenuLabels // application gives a ContextMenu of its own. func WithoutEditMenu() Option { return base.WithoutEditMenu() } -var installEditMenu sync.Once +var installEditMenu, installPrimarySelection sync.Once // useEditMenu installs the menu painter and the system clipboard the edit menu of // a TextField or TextArea needs. diff --git a/ui/markdown/markdown.go b/ui/markdown/markdown.go index 67fe0b717..bfad88664 100644 --- a/ui/markdown/markdown.go +++ b/ui/markdown/markdown.go @@ -32,6 +32,7 @@ package markdown import ( + "github.com/vivaui/viva/base" "github.com/vivaui/viva/components" "github.com/vivaui/viva/gfx" "github.com/vivaui/viva/markdown" @@ -47,7 +48,7 @@ type Style = components.MarkdownStyle type Look = components.MarkdownLook // Selection is a range of the rendered text, in byte offsets. -type Selection = components.MarkdownSelection +type Selection = base.TextRange // Code is a laid-out fenced code block. type Code = components.MarkdownCode diff --git a/ui/text_selection.go b/ui/text_selection.go new file mode 100644 index 000000000..856e9d971 --- /dev/null +++ b/ui/text_selection.go @@ -0,0 +1,32 @@ +package ui + +import ( + "github.com/vivaui/viva/app" + "github.com/vivaui/viva/base" +) + +// TextSelectionState is the selection of one TextSelectionArea; keep it in the model. +type TextSelectionState = base.TextSelectionState + +// TextSelection is a selection that may begin in one painted text and end in +// another, for texts an application paints itself; TextPoint is a place in them and +// TextRange the selected part of one; TextSelectionResult says what a pointer event +// did to it. +type ( + TextSelection = base.TextSelection + TextPoint = base.TextPoint + TextRange = base.TextRange + TextSelectionResult = base.TextSelectionResult +) + +// TextSelectionArea declares a column whose texts the user can select and copy; +// see base.TextSelectionArea. +// +// ui.TextSelectionArea(c, &m.details).Gap(6).Children(func() { +// ui.Text(c, m.fingerprint) +// }) +func TextSelectionArea(c C, state *TextSelectionState) Box { + useEditMenu() + installPrimarySelection.Do(func() { base.SetPrimarySelection = app.SetPrimarySelection }) + return base.TextSelectionArea(c, state) +} diff --git a/ui/text_selection_test.go b/ui/text_selection_test.go new file mode 100644 index 000000000..65163dd6f --- /dev/null +++ b/ui/text_selection_test.go @@ -0,0 +1,504 @@ +package ui_test + +import ( + "strings" + "testing" + "time" + + "github.com/vivaui/viva/app" + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/keymap" + "github.com/vivaui/viva/ui" +) + +// selectable is a headless window with one TextSelectionArea, declared by body. +type selectable struct { + t *testing.T + driver *app.Driver + canvas *gfx.Canvas + area ui.TextSelectionState + body func(c ui.C) +} + +func openSelectable(t *testing.T, body func(c ui.C)) *selectable { + t.Helper() + s := &selectable{t: t, body: body} + page := ui.NewPage(ui.PageConfig{View: func(c ui.C) { + ui.Column(c).Fill().Pad(16).Gap(8).Children(func() { + ui.TextSelectionArea(c, &s.area).FillWidth().Gap(4).Children(func() { s.body(c) }) + }) + }}) + s.open(page) + return s +} + +func (s *selectable) open(page *ui.Page) { + s.t.Helper() + s.canvas = &gfx.Canvas{} + driver, err := app.NewDriver(ui.Configure(page, app.Config{Width: 640, Height: 360}), s.canvas) + if err != nil { + s.t.Fatal(err) + } + s.t.Cleanup(driver.Close) + s.driver = driver + s.must(driver.Paint()) +} + +func (s *selectable) must(err error) { + s.t.Helper() + if err != nil { + s.t.Fatal(err) + } +} + +// painted is the line value as the last paint drew it. +func (s *selectable) painted(value string) gfx.Text { + s.t.Helper() + for _, text := range s.driver.Snapshot().Texts { + if text.Value == value { + return text + } + } + s.t.Fatalf("%q is not painted", value) + return gfx.Text{} +} + +func (s *selectable) text(value string) gfx.Rect { return s.painted(value).Bounds } + +// width is how wide the words of the line holding value are drawn: part of it, when +// part is a prefix of value. +func (s *selectable) width(value, part string) float32 { + return s.canvas.TextWidthStyle(part, s.painted(value).Style) +} + +// start and end are points just inside the first and the last character of a line. +func (s *selectable) start(value string) (float32, float32) { + r := s.text(value) + return r.X + 1, r.Y + r.Height/2 +} + +func (s *selectable) end(value string) (float32, float32) { + r := s.text(value) + return r.X + s.width(value, value) + 4, r.Y + r.Height/2 +} + +func (s *selectable) drag(fromX, fromY, toX, toY float32) { + s.t.Helper() + s.must(s.driver.Press(fromX, fromY, gfx.PointerButtonPrimary)) + s.must(s.driver.Move((fromX+toX)/2, (fromY+toY)/2)) + s.must(s.driver.Move(toX, toY)) + s.must(s.driver.Release(toX, toY, gfx.PointerButtonPrimary)) + s.must(s.driver.Paint()) +} + +// copied presses Primary+C and returns what reached the clipboard. +func (s *selectable) copied() string { + s.t.Helper() + s.driver.SetClipboard("") + _, err := s.driver.ShortcutChord(keymap.Primary, 'c') + s.must(err) + s.must(s.driver.Paint()) + return s.driver.Clipboard() +} + +// A drag from one text into another selects the end of the first and the start of the +// second, and copies them as their source, one per line. +func TestTextSelectionAreaDragsAcrossTexts(t *testing.T) { + s := openSelectable(t, func(c ui.C) { + ui.Text(c, "host key fingerprint") + ui.Text(c, "SHA256:abcdef") + }) + fx, fy := s.start("host key fingerprint") + tx, ty := s.end("SHA256:abcdef") + s.drag(fx, fy, tx, ty) + if got := s.copied(); got != "host key fingerprint\nSHA256:abcdef" { + t.Fatalf("copied %q", got) + } + if got := s.area.Text(); got != "host key fingerprint\nSHA256:abcdef" { + t.Fatalf("Text is %q", got) + } +} + +// A label and its value side by side in a row copy as one line, joined with a tab, so +// rows of them paste into a table. +func TestTextSelectionAreaJoinsARowWithATab(t *testing.T) { + s := openSelectable(t, func(c ui.C) { + for _, row := range [][2]string{{"Address", "10.0.0.2"}, {"Type", "ed25519"}} { + ui.Row(c).Gap(6).Children(func() { + ui.Text(c, row[0]).Width(90) + ui.Text(c, row[1]) + }) + } + }) + _, err := s.driver.ShortcutChord(keymap.Primary, 'a') + s.must(err) + s.must(s.driver.Paint()) // nothing has the focus yet: the area does not take a page-wide Select All + fx, fy := s.start("Address") + tx, ty := s.end("ed25519") + s.drag(fx, fy, tx, ty) + if got := s.copied(); got != "Address\t10.0.0.2\nType\ted25519" { + t.Fatalf("copied %q", got) + } +} + +// A double press selects the word under the pointer and a triple press its line. +func TestTextSelectionAreaSelectsAWordAndALine(t *testing.T) { + s := openSelectable(t, func(c ui.C) { + ui.Text(c, "connection refused by peer") + }) + r := s.text("connection refused by peer") + line := "connection refused by peer" + x := r.X + s.width(line, "connection ") + (s.width(line, "connection refused")-s.width(line, "connection "))/2 + y := r.Y + r.Height/2 + s.must(s.driver.ClickCount(x, y, 2)) + s.must(s.driver.Paint()) + if got := s.copied(); got != "refused" { + t.Fatalf("a double press copied %q", got) + } + s.must(s.driver.ClickCount(x, y, 3)) + s.must(s.driver.Paint()) + if got := s.copied(); got != "connection refused by peer" { + t.Fatalf("a triple press copied %q", got) + } +} + +// Shift with a press extends the selection from where it began. +func TestTextSelectionAreaShiftPressExtends(t *testing.T) { + s := openSelectable(t, func(c ui.C) { + ui.Text(c, "first line") + ui.Text(c, "second line") + }) + r := s.text("first line") + x, y := r.X+s.width("first line", "first "), r.Y+r.Height/2 + s.must(s.driver.Click(x, y)) + tx, ty := s.end("second line") + s.must(s.driver.KeyDown(gfx.KeyShiftLeft, "")) + s.must(s.driver.Click(tx, ty)) + s.must(s.driver.KeyUp(gfx.KeyShiftLeft, "")) + s.must(s.driver.Paint()) + if got := s.copied(); got != "line\nsecond line" { + t.Fatalf("copied %q", got) + } +} + +// Text that belongs to a control is not selected: a press on a button inside the area +// clicks it, and Select All leaves its words out; nor is what Unselectable takes out. +func TestTextSelectionAreaLeavesControlsAlone(t *testing.T) { + clicks := 0 + s := openSelectable(t, func(c ui.C) { + ui.Text(c, "error: timeout") + if ui.Button(c, "Retry").Clicked() { + clicks++ + } + ui.Text(c, "decoration").Unselectable() + ui.Text(c, "after") + }) + b := s.text("Retry") + s.must(s.driver.Click(b.X+b.Width/2, b.Y+b.Height/2)) + s.must(s.driver.Paint()) + if clicks != 1 { + t.Fatalf("the button inside the area was clicked %d times", clicks) + } + x, y := s.start("error: timeout") + s.must(s.driver.Click(x, y)) + s.must(s.driver.Paint()) + _, err := s.driver.ShortcutChord(keymap.Primary, 'a') + s.must(err) + s.must(s.driver.Paint()) + if got := s.copied(); got != "error: timeout\nafter" { + t.Fatalf("Select All copied %q", got) + } +} + +// A text cut short by an ellipsis copies whole. +func TestTextSelectionAreaCopiesTheTextAnEllipsisCut(t *testing.T) { + long := strings.Repeat("/very/long/remote/path", 12) + s := openSelectable(t, func(c ui.C) { + ui.Text(c, long).Ellipsis() + }) + var shown gfx.Rect + for _, text := range s.driver.Snapshot().Texts { + if strings.HasSuffix(text.Value, "…") { + shown = text.Bounds + } + } + if shown.Width == 0 { + t.Fatal("the text was not cut short") + } + y := shown.Y + shown.Height/2 + s.drag(shown.X+1, y, shown.X+shown.Width+40, y) + if got := s.copied(); got != long { + t.Fatalf("copied %d bytes of %d", len(got), len(long)) + } +} + +// Escape drops the selection; so does another control taking the keyboard, while a +// press on nothing leaves it. +func TestTextSelectionAreaDropsTheSelection(t *testing.T) { + var field string + s := &selectable{t: t} + page := ui.NewPage(ui.PageConfig{View: func(c ui.C) { + ui.Column(c).Fill().Pad(16).Gap(8).Children(func() { + ui.TextSelectionArea(c, &s.area).FillWidth().Children(func() { + ui.Text(c, "selected words") + }) + ui.Spacer(c).Height(80) + ui.TextField(c, &field, "Name", "type here").Width(200) + }) + }}) + s.open(page) + driver := s.driver + selectAll := func() { + x, y := s.start("selected words") + s.must(driver.Click(x, y)) + _, err := driver.ShortcutChord(keymap.Primary, 'a') + s.must(err) + s.must(driver.Paint()) + if !s.area.Has() { + t.Fatal("nothing was selected") + } + } + selectAll() + s.must(driver.Key(gfx.KeyEscape, 0)) + s.must(driver.Paint()) + if s.area.Has() { + t.Fatal("Escape left the selection") + } + selectAll() + s.must(driver.Click(600, 340)) + s.must(driver.Paint()) + if !s.area.Has() { + t.Fatal("a press on nothing dropped the selection") + } + r := s.text("type here") + s.must(driver.Click(r.X+r.Width/2, r.Y+r.Height/2)) + s.must(driver.Paint()) + if s.area.Has() { + t.Fatal("the selection stayed while a field had the keyboard") + } +} + +// A secondary press opens Copy and Select All; Copy puts the selection on the clipboard. +func TestTextSelectionAreaMenuCopies(t *testing.T) { + s := openSelectable(t, func(c ui.C) { + ui.Text(c, "ssh: handshake failed") + }) + fx, fy := s.start("ssh: handshake failed") + tx, ty := s.end("ssh: handshake failed") + s.drag(fx, fy, tx, ty) + s.must(s.driver.Press(fx+4, fy, gfx.PointerButtonSecondary)) + s.must(s.driver.Release(fx+4, fy, gfx.PointerButtonSecondary)) + s.must(s.driver.Paint()) + copyItem := s.text("Copy") + s.driver.SetClipboard("") + s.must(s.driver.Click(copyItem.X+copyItem.Width/2, copyItem.Y+copyItem.Height/2)) + s.must(s.driver.Paint()) + if got := s.driver.Clipboard(); got != "ssh: handshake failed" { + t.Fatalf("Copy put %q on the clipboard", got) + } +} + +// Shift with an arrow key moves the end of the selection by a character, into the next +// text past the end of one. +func TestTextSelectionAreaShiftArrowExtends(t *testing.T) { + s := openSelectable(t, func(c ui.C) { + ui.Text(c, "ab") + ui.Text(c, "cd") + }) + fx, fy := s.start("ab") + tx, ty := s.end("ab") + s.drag(fx, fy, tx, ty) + for range 2 { + s.must(s.driver.Key(gfx.KeyRight, gfx.ModifierShift)) + } + s.must(s.driver.Paint()) + if got := s.copied(); got != "ab\nc" { + t.Fatalf("copied %q", got) + } +} + +// A drag held below the scrolling area the texts are in scrolls it, and the selection +// follows into the texts it brings up. +func TestTextSelectionAreaDragScrollsItsArea(t *testing.T) { + s := &selectable{t: t} + lines := make([]string, 40) + for i := range lines { + lines[i] = "line " + string(rune('A'+i%26)) + strings.Repeat("x", i) + } + page := ui.NewPage(ui.PageConfig{View: func(c ui.C) { + ui.Scroll(c).Height(200).FillWidth().Children(func() { + ui.TextSelectionArea(c, &s.area).FillWidth().Children(func() { + for _, line := range lines { + ui.Text(c, line) + } + }) + }) + }}) + s.open(page) + x, y := s.start(lines[0]) + s.must(s.driver.Press(x, y, gfx.PointerButtonPrimary)) + s.must(s.driver.Move(x, 150)) + s.must(s.driver.Move(x, 260)) // below the area's 200 pixels + for range 20 { + s.must(s.driver.Advance(50 * time.Millisecond)) + } + s.must(s.driver.Release(x, 260, gfx.PointerButtonPrimary)) + s.must(s.driver.Paint()) + got := s.area.Text() + if !strings.HasPrefix(got, lines[0]) || strings.Count(got, "\n") < 12 { + t.Fatalf("the drag selected %d lines: %q", strings.Count(got, "\n")+1, got) + } +} + +// Selecting fills the primary selection where the desktop has one. +func TestTextSelectionAreaFillsThePrimarySelection(t *testing.T) { + s := openSelectable(t, func(c ui.C) { + ui.Text(c, "middle click pastes this") + }) + if _, err := app.PrimarySelection(); err == app.ErrUnsupported { + t.Skip("only an X11 desktop has a primary selection") + } + fx, fy := s.start("middle click pastes this") + tx, ty := s.end("middle click pastes this") + s.drag(fx, fy, tx, ty) + if got, err := app.PrimarySelection(); err != nil || got != "middle click pastes this" { + t.Fatalf("the primary selection is %q (%v)", got, err) + } +} + +func selectionPage(area *ui.TextSelectionState) func(ui.C) { + return func(c ui.C) { + ui.TextSelectionArea(c, area).FillWidth().Gap(4).Children(func() { + for i := range 40 { + ui.Row(c).Gap(6).Children(func() { + ui.Text(c, detailLabels[i%len(detailLabels)]).Width(120) + ui.Paragraph(c, "a value long enough to wrap onto a second line at this width", 2).Width(180) + }) + } + }) + } +} + +var detailLabels = []string{"Address", "Fingerprint", "Type", "Saved"} + +// A steady page of selectable texts, with part of them selected, allocates nothing. +func TestTextSelectionAreaPaintAllocatesNothing(t *testing.T) { + var area ui.TextSelectionState + view := selectionPage(&area) + page, canvas := ui.NewPage(ui.PageConfig{Theme: &pageTheme}), benchCanvas() + drawPage(page, canvas, view) + area.Selection.Select(ui.TextPoint{Surface: 3, Offset: 4}, ui.TextPoint{Surface: 30, Offset: 20}) + for range 3 { + drawPage(page, canvas, view) + } + if allocs := testing.AllocsPerRun(50, func() { drawPage(page, canvas, view) }); allocs != 0 { + t.Fatalf("a steady page of selectable texts allocates %v times", allocs) + } +} + +// BenchmarkTextSelectionArea is the cost of the same texts in an area and out of one. +func BenchmarkTextSelectionArea(b *testing.B) { + plain := func(c ui.C) { + ui.Column(c).FillWidth().Gap(4).Children(func() { + for i := range 40 { + ui.Row(c).Gap(6).Children(func() { + ui.Text(c, detailLabels[i%len(detailLabels)]).Width(120) + ui.Paragraph(c, "a value long enough to wrap onto a second line at this width", 2).Width(180) + }) + } + }) + } + var area ui.TextSelectionState + for _, bench := range []struct { + name string + view func(ui.C) + }{{"plain", plain}, {"area", selectionPage(&area)}} { + b.Run(bench.name, func(b *testing.B) { + page, canvas := ui.NewPage(ui.PageConfig{Theme: &pageTheme}), benchCanvas() + drawPage(page, canvas, bench.view) + area.Selection.Select(ui.TextPoint{Surface: 3, Offset: 4}, ui.TextPoint{Surface: 30, Offset: 20}) + b.ReportAllocs() + for b.Loop() { + drawPage(page, canvas, bench.view) + } + }) + } +} + +// A group region that names its content for assistive technology does not take the +// text inside it out of the area, as a button does. +func TestTextSelectionAreaKeepsTheTextOfAGroupRegion(t *testing.T) { + s := openSelectable(t, func(c ui.C) { + ui.Row(c).HitWith(ui.ID(c.Part("path")), "Path", gfx.HitOptions{Role: gfx.RoleGroup, SkipFocus: true, SkipTab: true}). + Children(func() { ui.Text(c, "/srv/backups/2026-11-26.tar.gz") }) + }) + fx, fy := s.start("/srv/backups/2026-11-26.tar.gz") + tx, ty := s.end("/srv/backups/2026-11-26.tar.gz") + s.drag(fx, fy, tx, ty) + if got := s.copied(); got != "/srv/backups/2026-11-26.tar.gz" { + t.Fatalf("copied %q", got) + } +} + +// A state copied into another field selects for that field, not for the one it was +// copied from. +func TestTextSelectionAreaStateCopiedByValue(t *testing.T) { + var first, second ui.TextSelectionState + showSecond := false + s := &selectable{t: t} + page := ui.NewPage(ui.PageConfig{View: func(c ui.C) { + area := &first + if showSecond { + area = &second + } + ui.TextSelectionArea(c, area).FillWidth().Children(func() { ui.Text(c, "copied state") }) + }}) + s.open(page) + fx, fy := s.start("copied state") + tx, ty := s.end("copied state") + s.drag(fx, fy, tx, ty) + second, showSecond = first, true + first.Clear() + s.must(s.driver.Paint()) + s.drag(fx, fy, fx+20, fy) + if first.Has() || !second.Has() { + t.Fatalf("first has %q, second %q", first.Text(), second.Text()) + } +} + +// Select All from the menu selects everything and gives the area the keyboard back, so +// Primary+C copies what it selected. +func TestTextSelectionAreaMenuGivesTheKeyboardBack(t *testing.T) { + s := openSelectable(t, func(c ui.C) { + ui.Text(c, "first") + ui.Text(c, "second") + }) + x, y := s.start("first") + s.must(s.driver.Press(x, y, gfx.PointerButtonSecondary)) + s.must(s.driver.Release(x, y, gfx.PointerButtonSecondary)) + s.must(s.driver.Paint()) + item := s.text("Select All") + s.must(s.driver.Click(item.X+item.Width/2, item.Y+item.Height/2)) + s.must(s.driver.Paint()) + s.must(s.driver.Paint()) + if got := s.copied(); got != "first\nsecond" { + t.Fatalf("copied %q after Select All", got) + } +} + +// A drag that begins in the blank part of the area, beside the words, selects from the +// nearest of them. +func TestTextSelectionAreaDragFromTheBlankBeside(t *testing.T) { + s := openSelectable(t, func(c ui.C) { + ui.Row(c).Gap(24).Children(func() { + ui.Spacer(c).Width(30) + ui.Text(c, "build 2026.11.26") + }) + }) + r := s.text("build 2026.11.26") + tx, ty := s.end("build 2026.11.26") + s.drag(r.X-12, ty, tx, ty) + if got := s.copied(); got != "build 2026.11.26" { + t.Fatalf("copied %q", got) + } +} From d5b05cd1053cebda8fa82d526dcba116764133c2 Mon Sep 17 00:00:00 2001 From: ccq <76206374+caichangqing1120@users.noreply.github.com> Date: Thu, 26 Nov 2026 21:57:54 +0800 Subject: [PATCH 10/16] test(ci): require the Windows offscreen frame regression --- .github/workflows/ci.yml | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 0242774e5..66d56b461 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -379,6 +379,13 @@ jobs: run: go test ./internal/platform/windows ./app -run '^Test(FileDialogInitialDirectory|DriverInterceptsOpenDirectory)$' -count=1 -v - name: Material contracts and controls (WARP) run: go test ./internal/platform/windows ./ui ./components ./headless ./app -run 'Test(Backdrop|WindowBackdrop|OpeningMaximized|Notification|TaskbarCreated|CompositionClear|CompositionFallback|CompositionCreation|CustomBackdrop|AcrylicAccent|LegacyAcrylic|RoundedOutline|Translucent|MonospaceFamilies|FontWeights|(The)?MonoWeights|(The)?InterfaceWeights|EveryListedFamilyResolves|EngineReportsTheFontsUnderline|AlwaysOnTop|SaveDialogCheckbox|FileIcon|NativeStructureABI|ResizePresents|WindowSwapChain|LiveResize|FlipWindowResize|RedrawWaits|ContinuousRedraw|NoOpFrame|SameSize|ZeroSize|ResizeTimer|RedrawQueue|NativeRedrawMessage|CompositionSupersededFrame|DragPreview|QueuedMenuKeysLeaveTerminalCompositionWithItsOwner|MenuKeysPreserveSystemChordsAndShift|TerminalMenuStopsCapturingWhenWindowLosesFocus|DisabledIMEOffersMenuShortcutDuringComposition)' -count=1 -v + - name: Offscreen incremental frame pixels + run: | + $test = 'TestOffscreenIncrementalUpdatesDrawWhatARebuildDraws' + go test -json ./internal/platform/windows -run "^${test}$" -count=1 -timeout=2m | Tee-Object -Variable events + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + $passed = $events | ConvertFrom-Json | Where-Object { $_.Action -eq 'pass' -and $_.Test -eq $test } + if (-not $passed) { throw "$test did not pass on the Windows runner" } - name: Web view partitions run: go test ./internal/platform/windows -run '^Test(APageWithoutAPartitionAsksForNoProfileOfItsOwn|APartitionNamesTheWebView2Profile|AnEphemeralPartitionIsAnOffTheRecordProfile|EphemeralPagesWithoutAPartitionEachGetAProfileOfTheirOwn)$' -count=1 -v - name: Terminal keyboard routing From 33778eb79375f6c03e455d1471e97bc7fcf7c4e8 Mon Sep 17 00:00:00 2001 From: ccq <76206374+caichangqing1120@users.noreply.github.com> Date: Thu, 26 Nov 2026 21:58:00 +0800 Subject: [PATCH 11/16] test(ci): run registered font fallback on both Windows archs --- .github/workflows/ci.yml | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 66d56b461..ac6328680 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -404,8 +404,8 @@ jobs: env: VIVA_WINDOWS_CLIPBOARD: '1' run: go test ./internal/platform/windows -run '^TestColumnClipboardNative' -count=1 -v -timeout=2m - - name: Native Direct2D text origins and hidden labels - run: go test ./internal/platform/windows -run '^Test(DirectTextLayoutOriginByValue|HiddenNativeEditorDoesNotDrawColorEmoji|TextEngineRasterizesProportionalText)$' -count=1 -v + - name: Native Direct2D text origins, hidden labels and font fallback + run: go test ./internal/platform/windows -run '^Test(DirectTextLayoutOriginByValue|HiddenNativeEditorDoesNotDrawColorEmoji|TextEngineRasterizesProportionalText|RegisteredFontDrawsFallbackCharacters)$' -count=1 -v - name: Promised file drag run: go test ./internal/platform/windows -run '^Test(ThePromiseDataObject|ThePromiseStream|ThePromiseEnumerator|PromiseNames)' -count=1 -v # The installer contracts, including WinVerifyTrust's struct layout, only @@ -430,10 +430,10 @@ jobs: go-version-file: go.mod architecture: arm64 cache: true - - name: Native ARM64 Direct2D text origins + - name: Native ARM64 Direct2D text origins and font fallback run: | if ((go env GOARCH) -ne 'arm64') { throw 'Expected native ARM64 Go' } - go test ./internal/platform/windows -run '^TestDirectTextLayoutOriginByValue$' -count=1 -v + go test ./internal/platform/windows -run '^Test(DirectTextLayoutOriginByValue|RegisteredFontDrawsFallbackCharacters)$' -count=1 -v # A noise-tolerant benchmark regression gate for the pure-Go paths: the base # revision and the pull request run the same benchmarks on the same runner, From 3df9fdf5dbc0fc4b120eb36297e37403e2013288 Mon Sep 17 00:00:00 2001 From: Xiaoyumuxi <23722032@bjtu.edu.cn> Date: Thu, 26 Nov 2026 21:58:08 +0800 Subject: [PATCH 12/16] feat(ui): show the full text of an ellipsized label on hover --- base/box.go | 2 + base/ellipsis_tooltip.go | 148 ++++++ base/flags.go | 5 +- base/frame.go | 29 +- base/layout.go | 1 + base/memo.go | 23 +- base/page.go | 32 +- base/paint.go | 35 +- base/text_wrap.go | 30 +- base/tooltip.go | 49 +- cmd/viva/templates/combobox.go.txt | 18 +- cmd/viva/templates/dropdown_menu.go.txt | 8 +- cmd/viva/templates/hierarchy_menu.go.txt | 6 +- cmd/viva/templates/multi_select.go.txt | 9 +- cmd/viva/templates/select.go.txt | 8 +- cmd/viva/templates/single_select.go.txt | 12 +- cmd/viva/templates/table.go.txt | 9 + components/combobox.go | 18 +- components/dropdown_menu.go | 8 +- components/hierarchy_menu.go | 6 +- components/multi_select.go | 9 +- components/select.go | 8 +- components/single_select.go | 12 +- components/table.go | 9 + gfx/canvas.go | 8 + gfx/embed.go | 27 +- gfx/hover_hint.go | 129 +++++ gfx/hover_hint_test.go | 112 +++++ gfx/pose.go | 2 +- gfx/presence.go | 8 +- gfx/replay.go | 26 +- gfx/wrap.go | 11 + ui/multiselect/multiselect_test.go | 53 ++ ui/tooltip_paint.go | 43 +- ui/tooltip_test.go | 600 +++++++++++++++++++++++ 35 files changed, 1415 insertions(+), 98 deletions(-) create mode 100644 base/ellipsis_tooltip.go create mode 100644 gfx/hover_hint.go create mode 100644 gfx/hover_hint_test.go diff --git a/base/box.go b/base/box.go index 427e85e5d..b6b85c8f8 100644 --- a/base/box.go +++ b/base/box.go @@ -430,6 +430,8 @@ func (b Box) MonoFace(Face gfx.MonoFace) Box { // Ellipsis keeps a Text to one line and ends it with an ellipsis when it does not // fit the width it gets, instead of clipping it. It is Paragraph(value, 1). +// A page with EllipsisTooltips, or an EllipsisTooltip on the Text or around it, +// shows the complete value in a tooltip while the pointer rests on the text. func (b Box) Ellipsis() Box { n := b.N() n.Flags |= flagWrap diff --git a/base/ellipsis_tooltip.go b/base/ellipsis_tooltip.go new file mode 100644 index 000000000..014cc5421 --- /dev/null +++ b/base/ellipsis_tooltip.go @@ -0,0 +1,148 @@ +package base + +import ( + "slices" + + "github.com/vivaui/viva/gfx" +) + +// What EllipsisTooltip and EllipsisTooltipOn set on an element, in one byte so +// that painting checks a single field. The low bits are the switch, ellipsisTipOn +// or ellipsisTipOff; the bits above are 1 + the side EllipsisTooltipOn gave. +// Zero in either part follows what the element is inside. +const ( + ellipsisTipOn uint8 = 1 + iota + ellipsisTipOff + + ellipsisTipSwitch uint8 = 3 + ellipsisTipSideShift = 2 +) + +// ellipsisState is what the text being painted does with the tooltips of +// shortened text: whether EllipsisTooltip's show, and 1 + the side every one +// of them opens on, OverflowTooltip's too; a zero side opens them below. +type ellipsisState struct { + on bool + side uint8 +} + +// popupFrom is the element a Popup was declared in, which it takes no room in +// but follows for EllipsisTooltip when it hangs off no element. +type popupFrom struct{ popup, from int32 } + +// EllipsisTooltip turns on, or with false off, the tooltip that shows the +// complete value of text shortened with an ellipsis, for the element and what +// it holds: a Text cut by Ellipsis or MaxLines, and the labels components +// shorten themselves, such as Table cells, Select values and menu items. It +// overrides PageConfig.EllipsisTooltips and an EllipsisTooltip further out. A +// Popup follows the element it hangs off (BelowBox and the like) or, placed by +// a rectangle or a point, the element it was declared in. +// +// ui.Text(c, path).Ellipsis().EllipsisTooltip(true) +// ui.Table(c, &table, spec).EllipsisTooltip(true) +func (b Box) EllipsisTooltip(on bool) Box { + b.N() + tip := ellipsisTipOff + if on { + tip = ellipsisTipOn + } + x := b.f.Extra(b.i) + x.ellipsisTip = x.ellipsisTip&^ellipsisTipSwitch | tip + b.f.ellipsisSet = true + return b +} + +// EllipsisTooltipOn opens the tooltips of the shortened text in the element and +// what it holds beside side of the text rather than below it, as TooltipOn does +// for a Tooltip: those EllipsisTooltip shows and those OverflowTooltip gives. A +// list in a sidebar on the window's left opens them to its right, over the +// content beside it, and a status bar along the window's bottom opens them +// above it. It does not turn them on. The nearest EllipsisTooltipOn decides, and +// a Popup follows it as it follows EllipsisTooltip. Without room on side, a +// tooltip opens on the opposite one. +// +// ui.Column(c).EllipsisTooltipOn(ui.TooltipRight).Children(func() { … }) +func (b Box) EllipsisTooltipOn(side TooltipSide) Box { + b.N() + x := b.f.Extra(b.i) + x.ellipsisTip = x.ellipsisTip&ellipsisTipSwitch | (uint8(side)+1)<> ellipsisTipSideShift; side != 0 { + state.side = side + } + return state +} + +// setEllipsis sets what is painted next does with the tooltips of shortened +// text, and returns what it did. Components see it on the canvas: as the hover +// hint owner, which is zero while EllipsisTooltip's are off, and the hint side. +func (f *Frame) setEllipsis(state ellipsisState) ellipsisState { + was := f.ellipsis + if state != was && f.page != nil && f.Surface != nil { + f.ellipsis = state + if state.on != was.on { + var owner gfx.Scope + if state.on { + owner = f.page.root + } + f.Surface.SetHoverHintOwner(owner) + } + if state.side != was.side { + f.Surface.SetHoverHintSide(state.side) + } + } + return was +} + +// restoreHoverHints gives the canvas back the hover hint owner and side it had +// before the frame painted, those of the page whose pane holds this one. +func (f *Frame) restoreHoverHints(owner gfx.Scope, side uint8) { + f.Surface.SetHoverHintOwner(owner) + f.Surface.SetHoverHintSide(side) +} + +// ellipsisAt is the state element i paints in: the nearest EllipsisTooltip and +// EllipsisTooltipOn on it or on what it is inside, or else the page's setting. +func (f *Frame) ellipsisAt(i int32) ellipsisState { + var tip, side uint8 + for steps := 0; i >= 0 && steps < len(f.Nodes) && (tip == 0 || side == 0); steps++ { + n := &f.Nodes[i] + set := f.Exts[n.Ext].ellipsisTip + if tip == 0 { + tip = set & ellipsisTipSwitch + } + if side == 0 { + side = set >> ellipsisTipSideShift + } + switch { + case n.Parent >= 0: + i = n.Parent + case n.AnchorRef > 0: + i = n.AnchorRef - 1 + default: + i = f.popupParent(i) + } + } + state := ellipsisState{on: f.page != nil && f.page.config.EllipsisTooltips} + return state.under(tip | side<